mechanical-engineering-skills

Tutorial: Image2Gcode (photo or sketch → printer-ready G-code)

Skill: image2gcode · Paper: Z. Wang, Y. Jadhav, P. Pak, A. Barati Farimani, Image2Gcode: Image-to-G-code generation for additive manufacturing using diffusion-transformer model, Additive Manufacturing Letters 17 (2026) 100374, doi:10.1016/j.addlet.2026.100374

Image2Gcode skips CAD and slicing for 2D and 2.5D parts. The image becomes a boundary silhouette, a toolpath is generated as per-layer (X, Y, E) keypoints, and post-processing writes printer-ready G-code. The paper’s generator is a diffusion model (DinoV2 encoder + 1-D U-Net) trained on Slice-100K. Its weights are available from the authors on request, so this skill bundles the exact input and output contract with a deterministic perimeter-plus-infill generator in the model’s slot. See ddpm_hook.md for dropping in the trained model.

Use cases

Setup

npx skills add BaratiLab/mechanical-engineering-skills --skill image2gcode
pip install opencv-python-headless shapely numpy matplotlib
python examples/make_sketch.py sketch.png        # a synthetic pen sketch with a hole and a slot

Walkthrough: pen sketch → 60 mm part

1. Preprocess (edge detection → contour hierarchy → filled 224 × 224 silhouette):

python scripts/i2g.py preprocess sketch.png --out sil.png --mode sketch

Sketch and silhouette

Check the silhouette before going on: material white, holes black.

2. Generate (60 mm long, 15 layers × 0.2 mm, 2 perimeters, 25% rectilinear):

python scripts/i2g.py generate sil.png --size-mm 60 --layers 15 --out part.gcode

Toolpath area: 1276.4 mm², against 1278.7 mm² for the drawn part at that scale (0.2% off).

3. Validate and plot

python scripts/i2g.py validate part.gcode --bed 220 220 250
python scripts/i2g.py plot part.gcode --out paths.png --layers 0,1
ok: true · layers 15 · z 0.2–3.0 mm · filament 600.7 mm · travel 22 575 mm

Toolpaths

Two perimeters close around the outline and both holes, and the infill alternates ±45° and stays inside the walls.

4. Keypoints (the model’s representation) and re-emission

python scripts/i2g.py keypoints part.gcode --out kp.npz     # (layers, Nmax, 3) in [-1,1] + mask
python scripts/i2g.py emit kp.npz --layer 0 --size-mm 40 --out layer0_40mm.gcode

The parser handles absolute and relative modes, mid-file G92 E resets, and constant-E travels (examples/tricky_modes.gcode is in the tests). emit rescales the same keypoints to any physical size with --flow-mult for your printer, which is the paper’s point about decoupling geometry from machine settings.

Lessons the tests encode

Prompts to try