Advertisement
j0h

img2scad

j0h
Jun 21st, 2025
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.04 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. from PIL import Image
  4. import numpy as np
  5.  
  6. # === CONFIG ===
  7. INPUT_IMAGE = "t.png"
  8. OUTPUT_SCAD = "output.scad"
  9. PIXEL_SIZE = 1       # mm per pixel (X and Y)
  10. MAX_HEIGHT = 10.0    # max Z height in mm
  11. DOWNSCALE = 3        # Skip every N pixels for speed (set to 1 for full res)
  12.              # Full res will result in very long openscad load times
  13.  
  14. # === LOAD AND PROCESS IMAGE ===
  15. img = Image.open(INPUT_IMAGE).convert("L")
  16. data = np.array(img)
  17.  
  18. # Optionally downscale to speed up output
  19. data = data[::DOWNSCALE, ::DOWNSCALE]
  20.  
  21. # Normalize grayscale to height
  22. zscale = MAX_HEIGHT / 255.0
  23. heights = data * zscale
  24.  
  25. rows, cols = heights.shape
  26.  
  27. # === WRITE SCAD FILE ===
  28. with open(OUTPUT_SCAD, "w") as f:
  29.     f.write("// Generated by img2scad.py\n")
  30.     f.write("union() {\n")
  31.  
  32.     for y in range(rows):
  33.         for x in range(cols):
  34.             h = heights[y, x]
  35.             if h > 0:
  36.                 # OpenSCAD coordinate system: [x, y, z]
  37.                 f.write(f"  translate([{x * PIXEL_SIZE}, {y * PIXEL_SIZE}, 0])\n")
  38.                 f.write(f"    cube([{PIXEL_SIZE}, {PIXEL_SIZE}, {h:.2f}]);\n")
  39.  
  40.     f.write("}\n")
  41.  
  42. print(f"Done. Output written to: {OUTPUT_SCAD}")
  43.  
  44. '''
  45. Notes:
  46. openSCAD will take forever to load a prebuilt complex openscad file IF you load that object from the start.
  47. (even if you have manifold selected in the rendering options of developer mode)
  48. (becuase init still uses CSG regardless)
  49. The work around is to load a blank output file, then generate the data using this script.
  50. then, provided you have manifold selected, reloading the data will be much faster.
  51.  
  52. 2. This is true, to 200K objects. at over 200K objects, openscad will default to CSG modeling, which is the same
  53. as being broken.
  54.  
  55. 3. background subtraction concept forgoing complex image processing:
  56. for h < some min_hight
  57. render no objects.
  58. this may help keep object count low, where you can continue to reap the benifits of manifold rendering.
  59.  
  60. h < 3
  61. but Im pretty tired finding other ppls bugs. Ima go sleep.
  62.  
  63.  
  64. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement