3D part design with Inkscape and OpenSCAD#127: Autotrace with OpenSCAD

3 min read
By Bob
3D part design with Inkscape and OpenSCAD#127: Autotrace with OpenSCAD

You actually can use OpenSCAD to "auto trace" .png images, and with some fine tuning the results are not bad and are similar to any other auto trace that I have used.

If you have ever tried to trace a .png image you know the pixelation makes it a difficult job to get a decent svg out of it, while this method is far from a perfect solution, I think it can be improved upon with OpenSCAD's new python capabilities and z-depth mapping to make a really good auto tracer.

here is the code:

//
Path_to_PNG_file="/";
cut_to_svg=false;
Invert=false;
cut_Z_adjust=.11;//[-10:.001:10]

module autotrace(){
intersection(){
translate([0,0,cut_Z_adjust])
scale([1,1,.068])
surface(Path_to_PNG_file,invert=Invert,center=true);
linear_extrude(1000)
square(1000,center=true);
}}

if(cut_to_svg)
color("red",3)
projection(cut=true) 
autotrace();
else
autotrace();

As a quick example I took a screen shot from this site with Flameshot and saved it as a png file:

Flameshot
Flameshot is a free and open-source, cross-platform tool to take screenshots with many built-in features to save you time.

I picked a random image from this site as an example for this post, black objects are easy to trace and surface can make a pretty decent outline with it:

Then I loaded the .png image into my OpenSCAD code:

The "fill" option wasn't working like I wanted it to so I removed it for the time being.

With invert selected and the "cut z adjust" moved in the positive direction I can adjust to the z-level so I have a "cut" of the png image at a specific z-level.

With invert unselected I can adjust "z" in the negative direction and have a cut out:

Once I have it adjusted to the level I want I can export it as an svg file:

Then I can import it into Inkscape and clean it up:

With nothing selected I can save the png image as an .stl:

You can barely see them but there are grid lines in the screenshot, surface makes them really pop out.

Starting with a high quality black and white image is the key to getting a perfect auto trace, but even with a regular colored image you can still get decent results.

More work will need to be done.....