Spaces:
Running
Running
Upload 2 files
Browse filesFiles changed (2)
- app.py+142-76
- relief_workshop.py+126-243
12334568 unmodified lines15161718181920213 unmodified lines2526272828293132303132333634383536404137383940414243474849444546474819 unmodified lines686970757172787374757677787984808182878384852 unmodified lines888990919293949599969798991004 unmodified lines1051061071081091101111121131141151161171181191151201211221233 unmodified lines1271281291251261271281291301301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681331691701711721351731741751761391401411421431441451461471481491771781791801811821831841851861871881891901911921931941571951961601611971981992002012022032041632052061651661672072082092102112122132142152162172182192202212222232242251692262272282292302312322332342352361721731741751761771781791801811821831841851862372382392402412422432442451891901911922462472482492502512522532542552562572582591952602612621982632642653 unmodified lines26927027120820927227327427527627721521621727827928028128228328428511 unmodified lines2972982992353003013023 unmodified lines306307308245309310247311312249313314315316317318319255320321322323324"""app.py — Pattern Ground Relief GeneratorGradio 5.x — compatibile Python 3.13 — HuggingFace SpacesGradio 5.x — Python 3.13 — HuggingFace Spaces"""
import tempfile8 unmodified lines
# ─────────────────────────────────────────────# CORE FUNCTIONS# CORE# ─────────────────────────────────────────────
def preview_depthmap(image, invert, quantize_levels, tileable, blur):3 unmodified lines with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f: tmp = f.name Image.fromarray(image).save(tmp)
quantize = int(quantize_levels) if quantize_levels >= 2 else 0 height_map, px_w, px_h = build_heightmap( tmp, max_px=300, invert=invert, blur=blur, gamma=1.1, tmp, max_px=300, invert=invert, blur=blur, gamma=1.1, quantize=quantize, tileable=tileable, fade_px=12, ) Path(tmp).unlink(missing_ok=True)
preview = (height_map * 255).astype(np.uint8) info = f"Depth map {px_w}×{px_h}px — bianco=alto, nero=basso" msg = f"Depth map {px_w}×{px_h}px — bianco=alto, nero=basso" if invert: info += " (invertita)" return preview, info msg += " (invertita)" return preview, msg except Exception as e: return None, f"❌ {e}"
def generate_stl( image, tile_w, tile_h_mode, tile_h_custom, relief_mm, base_mm, image, tile_w, tile_h_mode, tile_h_custom, relief_mm, base_mm, no_base, invert, quantize_levels, tileable, blur, resolution,): if image is None:19 unmodified lines ) Path(tmp_in).unlink(missing_ok=True)
# Depth map preview preview = (height_map * 255).astype(np.uint8)
# Generate STL bytes effective_base = 0.0 if no_base else float(base_mm)
stl_bytes = heightmap_to_stl( height_map, px_w, px_h, tile_w_mm=float(tile_w), tile_h_mm=float(tile_h), relief_mm=float(relief_mm), base_mm=float(base_mm), base_mm=effective_base, )
# Write to named temp file (Gradio 5 needs a real path) stl_tmp = tempfile.NamedTemporaryFile( suffix=".stl", delete=False, prefix="tile_" )2 unmodified lines
n_tri = (len(stl_bytes) - 84) // 50 size_kb = len(stl_bytes) / 1024 base_info = "nessuna" if no_base else f"{effective_base:.1f} mm"
info = ( f"✓ Tile generata\n\n" f"Dimensioni: {tile_w:.0f} × {tile_h:.0f} mm\n" f"Altezza: {base_mm:.1f} base + {relief_mm:.1f} rilievo = {base_mm+relief_mm:.1f} mm\n" f"Rilievo: {relief_mm:.1f} mm\n" f"Base: {base_info}\n" f"Mesh: {px_w}×{px_h}px — {n_tri:,} triangoli\n" f"File: {size_kb:.0f} KB\n\n" f"Slicer: layer 0.15 mm · infill 15% · no supports"4 unmodified lines return None, None, f"❌ {e}"
def toggle_custom(mode): return gr.update(visible=(mode == "Personalizzata"))
def toggle_base_slider(no_base): return gr.update(visible=not no_base)
# ─────────────────────────────────────────────# UI# ─────────────────────────────────────────────
CSS = """@import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Instrument+Serif:ital@0;1&display=swap');@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=DM+Mono:ital,wght@0,400;0,500;1,400&display=swap');
body { background: #0a0a0a !important; }
3 unmodified lines max-width: 1100px !important;}
h1 { font-family: 'Instrument Serif', serif !important; font-size: 2rem !important; color: #f2efe8 !important; font-weight: 400 !important; letter-spacing: -0.02em !important;/* ── HEADER ── */.pg-header { padding: 28px 0 22px; border-bottom: 1px solid #1e1e1e; margin-bottom: 4px;}.pg-num { font-family: 'DM Mono', monospace; font-size: 10px; letter-spacing: 0.2em; color: #333; margin-bottom: 6px; display: block;}.pg-logo { font-family: 'Bebas Neue', sans-serif; font-size: 56px; letter-spacing: 0.1em; color: #f2efe8; line-height: 1; display: block;}.pg-logo .accent { color: #d4a912; }.pg-sub { font-family: 'DM Mono', monospace; font-size: 9px; letter-spacing: 0.22em; color: #444; text-transform: uppercase; margin-top: 8px; display: block;}.pg-rule { width: 100%; height: 1px; background: #1e1e1e; margin-top: 20px;}
h2 {/* ── SECTION LABELS ── */.gradio-container h2,.section-label { font-family: 'DM Mono', monospace !important; font-size: 0.6rem !important; font-size: 9px !important; letter-spacing: 0.2em !important; color: #d4a912 !important; text-transform: uppercase !important; border-bottom: 1px solid #222 !important; padding-bottom: 0.4rem !important; margin-top: 1.2rem !important;}
.gr-button { font-family: 'DM Mono', monospace !important; text-transform: uppercase !important; letter-spacing: 0.08em !important; font-size: 0.72rem !important; border-radius: 0 !important; border-bottom: 1px solid #1e1e1e !important; padding-bottom: 6px !important; margin-top: 20px !important; font-weight: 400 !important;}
/* ── BUTTONS ── */button.primary { background: #d4a912 !important; color: #0a0a0a !important; border: none !important; border-radius: 0 !important; font-family: 'DM Mono', monospace !important; text-transform: uppercase !important; letter-spacing: 0.1em !important; font-size: 0.7rem !important; font-weight: 500 !important;}
button.secondary { background: transparent !important; color: #888 !important; border: 1px solid #333 !important; color: #555 !important; border: 1px solid #2a2a2a !important; border-radius: 0 !important; font-family: 'DM Mono', monospace !important; text-transform: uppercase !important; letter-spacing: 0.1em !important; font-size: 0.7rem !important;}"""button:hover { opacity: 0.85 !important; }
HEADER = """# Pattern Ground**Fabrication Topologies — Vectorealism × Dropcity · Design Week Milano 2026**/* ── INPUTS ── */label span { font-family: 'DM Mono', monospace !important; font-size: 10px !important; letter-spacing: 0.1em !important; color: #666 !important; text-transform: uppercase !important;}input[type=range] { accent-color: #d4a912 !important; }input[type=checkbox] { accent-color: #d4a912 !important; }textarea { background: #0d0d0d !important; border: 1px solid #1e1e1e !important; color: #888 !important; font-family: 'DM Mono', monospace !important; font-size: 12px !important; border-radius: 0 !important;}
Converti un'immagine in una tile di rilievo 3D pronta per la stampa./* ── GUIDE ── */.guide { font-family: 'DM Mono', monospace; font-size: 11px; line-height: 1.9; color: #555; margin-top: 16px;}.guide strong { color: #888; font-weight: 500; }"""
GUIDE = """**Come funziona**
Ogni pixel dell'immagine diventa un'altezza: **bianco = alto, nero = basso** (o inverso con Invert).Controlla sempre la depth map prima di generare l'STL.
**Quantize** — divide il rilievo in N livelli netti invece di un gradiente continuo.Ottimo per pattern urbani: sanpietrini, griglia, muratura. Prova 4–6 livelli.
**Tileable** — sfuma i bordi così le tile si affiancano senza giunti visibili nella griglia.
**Immagini che funzionano bene:** foto di pavimentazioni, mappe b/n di edifici, texture geometriche,pattern a contrasto alto. Evita foto a colori complesse senza preprocessarle in bianco/nero.
**Slicer:** layer height 0.15 mm · infill 15% · no supports · ironing on top surface.HEADER_HTML = """<div class="pg-header"> <span class="pg-num">02 / Pattern Ground</span> <span class="pg-logo">Pattern <span class="accent">Ground</span></span> <span class="pg-sub">Fabrication Topologies · Vectorealism × Dropcity · Design Week Milano 2026</span> <div class="pg-rule"></div></div>"""
def toggle_custom(mode): return gr.update(visible=(mode == "Personalizzata"))
GUIDE_HTML = """<div class="guide"><strong>bianco = alto, nero = basso</strong> (o inverso con Invert).<br>Controlla sempre la depth map prima di generare l'STL.<br><br><strong>Quantize</strong> — divide il rilievo in N livelli netti.<br>Ottimo per pattern urbani: sanpietrini, griglia, muratura.<br><br><strong>Tileable</strong> — sfuma i bordi per affiancamento senza giunti.<br><br><strong>Senza base</strong> — mesh aperta sotto: utile se vuoi montare la tile<br>su un supporto o se la stampi su un piano già livellato.<br><br><strong>Slicer:</strong> layer 0.15 mm · infill 15% · no supports · ironing top</div>"""
with gr.Blocks(css=CSS, title="Pattern Ground") as demo: gr.Markdown(HEADER) gr.HTML(HEADER_HTML)
with gr.Row(): # ── Colonna sinistra ── with gr.Column(scale=1):
gr.Markdown("## Immagine")3 unmodified lines tile_w = gr.Slider(20, 200, value=100, step=5, label="Larghezza (mm)") tile_h_mode = gr.Radio( ["Quadrata (uguale alla larghezza)", "Proporzioni originali", "Personalizzata"], value="Quadrata (uguale alla larghezza)", label="Altezza", value="Quadrata (uguale alla larghezza)", label="Altezza", ) tile_h_custom = gr.Slider(20, 200, value=100, step=5, label="Altezza personalizzata (mm)", visible=False)
gr.Markdown("## Rilievo") with gr.Row(): relief_mm = gr.Slider(1, 10, value=4, step=0.5, label="Altezza rilievo (mm)") base_mm = gr.Slider(1, 5, value=2, step=0.5, label="Base (mm)") relief_mm = gr.Slider(1, 10, value=4, step=0.5, label="Altezza rilievo (mm)")
gr.Markdown("## Base") no_base = gr.Checkbox(label="Senza base (mesh aperta sotto)", value=False) base_mm = gr.Slider(0.5, 5, value=2, step=0.5, label="Spessore base (mm)")
gr.Markdown("## Processing") quantize = gr.Slider(0, 12, value=0, step=1,11 unmodified lines preview_btn = gr.Button("Depth map preview", variant="secondary") gen_btn = gr.Button("Genera STL", variant="primary")
# ── Colonna destra ── with gr.Column(scale=1): gr.Markdown("## Depth map") depth_out = gr.Image(label="Bianco = alto · Nero = basso",3 unmodified lines stl_out = gr.File(label="STL file")
gr.Markdown("## Info") info_out = gr.Textbox(label="", lines=7, interactive=False) info_out = gr.Textbox(label="", lines=8, interactive=False)
gr.Markdown(GUIDE) gr.HTML(GUIDE_HTML)
# ── Events ── # Events tile_h_mode.change(toggle_custom, tile_h_mode, tile_h_custom) no_base.change(toggle_base_slider, no_base, base_mm)
preview_inputs = [image_in, invert, quantize, tileable, blur] gen_inputs = [ image_in, tile_w, tile_h_mode, tile_h_custom, relief_mm, base_mm, invert, quantize, tileable, blur, resolution, relief_mm, base_mm, no_base, invert, quantize, tileable, blur, resolution, ]
preview_btn.click(preview_depthmap, preview_inputs, [depth_out, info_out])1234567891011121314154566 unmodified lines13141528293031163317181920213940222324254426274748282951523031323334353658373861394041424344686970714546474849775051805253545556855758596 unmodified lines666768989969707110272104105731077475110767711378791168081821191201211221231241251268384129130131132858687886 unmodified lines95969714514614714814998991001011021031041051061541551561071081091101111121131141151161171181611191201211221651661671681691701711721731741751761771781791801811231241251261271281291301311321331341351361371841851861871881381391401411911921421431441451461471481491501511521531541551561571581591601951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392401611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342351 unmodified line237238239248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357240"""relief_workshop.pyImage → 3D relief tile — versione workshop Fabrication Topologies
Uso: python relief_workshop.py input.png [opzioni]
Esempi: python relief_workshop.py pattern.png python relief_workshop.py pattern.png --width 100 --height 100 --relief 4 --base 2 python relief_workshop.py pattern.png --width 100 --height 100 --invert --tileable python relief_workshop.py pattern.png --width 100 --height 100 --relief 6 --quantize 4
Dipendenze: pip install numpy pillow scipy opencv-python-headless"""
import argparse6 unmodified linesfrom PIL import Image
# ─────────────────────────────────────────────# PROCESSING# ─────────────────────────────────────────────
def load_and_prepare(image_path: str, max_px: int) -> np.ndarray: """Carica l'immagine, converte in grigio, ridimensiona.""" img = Image.open(image_path).convert("RGB") ratio = min(max_px / img.width, max_px / img.height) new_w = max(2, int(img.width * ratio)) new_h = max(2, int(img.height * ratio)) img = img.resize((new_w, new_h), Image.LANCZOS) gray = np.array(img.convert("L"), dtype=np.float32) return gray return np.array(img.convert("L"), dtype=np.float32)
def smooth_heightmap(gray: np.ndarray, blur: float) -> np.ndarray: """Bilateral filter + smoothing leggero.""" if blur <= 0: return gray sigma_color = min(60, blur * 15) sigma_space = min(10, blur * 3) result = cv2.bilateralFilter( gray.astype(np.uint8), d=9, sigmaColor=sigma_color, sigmaSpace=sigma_space sigmaColor=min(60, blur * 15), sigmaSpace=min(10, blur * 3) ).astype(np.float32) return result
def quantize_heightmap(gray: np.ndarray, levels: int) -> np.ndarray: """Quantizza i livelli di altezza: crea un effetto a gradini netti.""" if levels < 2: return gray # Divide in N livelli e rimappa normalized = gray / 255.0 quantized = np.floor(normalized * levels) / levels return (quantized * 255.0).astype(np.float32)
def make_tileable(gray: np.ndarray, fade_px: int) -> np.ndarray: """ Sfuma i bordi verso la media dell'immagine per permettere l'affiancamento senza scalini visibili ai giunti. """ if fade_px <= 0: return gray h, w = gray.shape mean_val = float(np.mean(gray)) result = gray.copy()
fade = min(fade_px, w // 4, h // 4) for i in range(fade): alpha = i / fade # 0 al bordo → 1 all'interno alpha = i / fade result[i, :] = alpha * gray[i, :] + (1 - alpha) * mean_val result[h - 1 - i, :] = alpha * gray[h - 1 - i, :] + (1 - alpha) * mean_val result[:, i] = alpha * result[:, i] + (1 - alpha) * mean_val result[:, w - 1 - i] = alpha * result[:, w - 1 - i] + (1 - alpha) * mean_val
return result
6 unmodified lines quantize: int = 0, tileable: bool = False, fade_px: int = 8,) -> tuple[np.ndarray, int, int]: """Pipeline completa da immagine a heightmap normalizzata [0,1]."""): gray = load_and_prepare(image_path, max_px) h, w = gray.shape
gray = smooth_heightmap(gray, blur)
# Gamma correction gray = np.power(gray / 255.0, gamma) * 255.0
if quantize >= 2: gray = quantize_heightmap(gray, quantize)
if tileable: gray = make_tileable(gray, fade_px)
if invert: gray = 255.0 - gray
gray = np.clip(gray, 0, 255) return gray / 255.0, w, h
# Normalizza [0, 1] height_map = gray / 255.0 return height_map, w, h
# ─────────────────────────────────────────────# STL GENERATION# ─────────────────────────────────────────────
def _pack_triangle(normal, v1, v2, v3) -> bytes: return struct.pack( "<ffffffffffffH", *normal, *v1, *v2, *v3, 0 ) return struct.pack("<ffffffffffffH", *normal, *v1, *v2, *v3, 0)
def heightmap_to_stl(6 unmodified lines base_mm: float,) -> bytes: """ Genera un file STL binario da una heightmap normalizzata [0,1].
La superficie superiore è il rilievo. La base è piatta a z=0 (superficie inferiore a z=-base_mm internamente, ma tutto shiftato così il bottom è a z=0 e il rilievo è in positivo). Genera STL da heightmap [0,1]. Se base_mm == 0: mesh aperta sotto (solo superficie + pareti che scendono fino al punto più basso del rilievo, nessun piano inferiore). Se base_mm > 0: solido chiuso con base piatta. """ pixel_x = tile_w_mm / (px_w - 1) pixel_y = tile_h_mm / (px_h - 1) no_base = (base_mm <= 0)
# z assoluto di ogni pixel della superficie # base a z=0, rilievo sale fino a relief_mm def z(row, col): def z_surf(row, col): # z della superficie di rilievo return base_mm + height_map[row, col] * relief_mm
def z_bottom(row, col): # z del bordo inferiore: 0 se c'è la base, minimo locale se no if no_base: return height_map[row, col] * relief_mm # inizia dal rilievo stesso (min=0) return 0.0
triangles = []
# ── Superficie superiore (rilievo) ── # ── Superficie superiore ── for row in range(px_h - 1): for col in range(px_w - 1): x0, x1 = col * pixel_x, (col + 1) * pixel_x y0, y1 = (px_h - 1 - row) * pixel_y, (px_h - 2 - row) * pixel_y
z00 = z(row, col) z10 = z(row, col + 1) z01 = z(row + 1, col) z11 = z(row + 1, col + 1)
v00 = (x0, y0, z00) v10 = (x1, y0, z10) v01 = (x0, y1, z01) v11 = (x1, y1, z11)
# Triangolo 1 e1 = np.subtract(v10, v00) e2 = np.subtract(v01, v00) n = np.cross(e1, e2) nn = n / (np.linalg.norm(n) + 1e-12) y0 = (px_h - 1 - row) * pixel_y y1 = (px_h - 2 - row) * pixel_y
z00 = z_surf(row, col) z10 = z_surf(row, col + 1) z01 = z_surf(row + 1, col) z11 = z_surf(row + 1, col + 1)
v00, v10 = (x0, y0, z00), (x1, y0, z10) v01, v11 = (x0, y1, z01), (x1, y1, z11)
e1 = np.subtract(v10, v00); e2 = np.subtract(v01, v00) n = np.cross(e1, e2); nn = n / (np.linalg.norm(n) + 1e-12) triangles.append(_pack_triangle(nn, v00, v10, v01))
# Triangolo 2 e1 = np.subtract(v01, v11) e2 = np.subtract(v10, v11) n = np.cross(e1, e2) nn = n / (np.linalg.norm(n) + 1e-12) e1 = np.subtract(v01, v11); e2 = np.subtract(v10, v11) n = np.cross(e1, e2); nn = n / (np.linalg.norm(n) + 1e-12) triangles.append(_pack_triangle(nn, v11, v01, v10))
# ── Base inferiore (piatta a z=0) ── for row in range(px_h - 1): # ── Base inferiore (solo se base_mm > 0) ── if not no_base: for row in range(px_h - 1): for col in range(px_w - 1): x0, x1 = col * pixel_x, (col + 1) * pixel_x y0 = (px_h - 1 - row) * pixel_y y1 = (px_h - 2 - row) * pixel_y n = (0.0, 0.0, -1.0) triangles.append(_pack_triangle(n, (x0,y0,0),(x0,y1,0),(x1,y0,0))) triangles.append(_pack_triangle(n, (x1,y1,0),(x1,y0,0),(x0,y1,0)))
W, H = tile_w_mm, tile_h_mm
if no_base: # Senza base: le pareti laterali collegano la superficie al suo stesso # bordo inferiore (z = height_map * relief_mm, cioè parte da 0 al minimo) # Fronte (y=0, row = px_h-1) for col in range(px_w - 1): x0, x1 = col * pixel_x, (col + 1) * pixel_x y0, y1 = (px_h - 1 - row) * pixel_y, (px_h - 2 - row) * pixel_y n = (0.0, 0.0, -1.0) triangles.append(_pack_triangle(n, (x0, y0, 0), (x0, y1, 0), (x1, y0, 0))) triangles.append(_pack_triangle(n, (x1, y1, 0), (x1, y0, 0), (x0, y1, 0)))
W = tile_w_mm H = tile_h_mm
# ── Pareti laterali ── # Fronte (y=0) for col in range(px_w - 1): x0, x1 = col * pixel_x, (col + 1) * pixel_x z0_top = z(px_h - 1, col) z1_top = z(px_h - 1, col + 1) n = (0.0, -1.0, 0.0) triangles.append(_pack_triangle(n, (x0, 0, 0), (x1, 0, z1_top), (x0, 0, z0_top))) triangles.append(_pack_triangle(n, (x0, 0, 0), (x1, 0, 0), (x1, 0, z1_top)))
# Retro (y=H) for col in range(px_w - 1): x0, x1 = col * pixel_x, (col + 1) * pixel_x z0_top = z(0, col) z1_top = z(0, col + 1) n = (0.0, 1.0, 0.0) triangles.append(_pack_triangle(n, (x0, H, z0_top), (x1, H, z1_top), (x0, H, 0))) triangles.append(_pack_triangle(n, (x1, H, z1_top), (x1, H, 0), (x0, H, 0)))
# Sinistra (x=0) for row in range(px_h - 1): y0 = (px_h - 1 - row) * pixel_y y1 = (px_h - 2 - row) * pixel_y z0_top = z(row, 0) z1_top = z(row + 1, 0) n = (-1.0, 0.0, 0.0) triangles.append(_pack_triangle(n, (0, y0, z0_top), (0, y1, z1_top), (0, y0, 0))) triangles.append(_pack_triangle(n, (0, y1, 0), (0, y0, 0), (0, y1, z1_top)))
# Destra (x=W) for row in range(px_h - 1): y0 = (px_h - 1 - row) * pixel_y y1 = (px_h - 2 - row) * pixel_y z0_top = z(row, px_w - 1) z1_top = z(row + 1, px_w - 1) n = (1.0, 0.0, 0.0) triangles.append(_pack_triangle(n, (W, y0, 0), (W, y1, z1_top), (W, y0, z0_top))) triangles.append(_pack_triangle(n, (W, y0, 0), (W, y1, 0), (W, y1, z1_top))) zt0 = z_surf(px_h - 1, col); zt1 = z_surf(px_h - 1, col + 1) zb0 = height_map[px_h-1, col] * relief_mm zb1 = height_map[px_h-1, col+1] * relief_mm n = (0.0, -1.0, 0.0) triangles.append(_pack_triangle(n, (x0,0,zb0),(x1,0,zt1),(x0,0,zt0))) triangles.append(_pack_triangle(n, (x0,0,zb0),(x1,0,zb1),(x1,0,zt1)))
# Retro (y=H, row = 0) for col in range(px_w - 1): x0, x1 = col * pixel_x, (col + 1) * pixel_x zt0 = z_surf(0, col); zt1 = z_surf(0, col + 1) zb0 = height_map[0, col] * relief_mm zb1 = height_map[0, col+1] * relief_mm n = (0.0, 1.0, 0.0) triangles.append(_pack_triangle(n, (x0,H,zt0),(x1,H,zt1),(x0,H,zb0))) triangles.append(_pack_triangle(n, (x1,H,zt1),(x1,H,zb1),(x0,H,zb0)))
# Sinistra (x=0, col=0) for row in range(px_h - 1): y0 = (px_h - 1 - row) * pixel_y y1 = (px_h - 2 - row) * pixel_y zt0 = z_surf(row, 0); zt1 = z_surf(row + 1, 0) zb0 = height_map[row, 0] * relief_mm zb1 = height_map[row+1, 0] * relief_mm n = (-1.0, 0.0, 0.0) triangles.append(_pack_triangle(n, (0,y0,zt0),(0,y1,zt1),(0,y0,zb0))) triangles.append(_pack_triangle(n, (0,y1,zt1),(0,y1,zb1),(0,y0,zb0)))
# Destra (x=W, col=px_w-1) for row in range(px_h - 1): y0 = (px_h - 1 - row) * pixel_y y1 = (px_h - 2 - row) * pixel_y zt0 = z_surf(row, px_w-1); zt1 = z_surf(row+1, px_w-1) zb0 = height_map[row, px_w-1] * relief_mm zb1 = height_map[row+1, px_w-1] * relief_mm n = (1.0, 0.0, 0.0) triangles.append(_pack_triangle(n, (W,y0,zb0),(W,y1,zt1),(W,y0,zt0))) triangles.append(_pack_triangle(n, (W,y0,zb0),(W,y1,zb1),(W,y1,zt1)))
else: # Con base: pareti vanno da z=0 alla superficie # Fronte for col in range(px_w - 1): x0, x1 = col * pixel_x, (col + 1) * pixel_x zt0 = z_surf(px_h-1, col); zt1 = z_surf(px_h-1, col+1) n = (0.0, -1.0, 0.0) triangles.append(_pack_triangle(n,(x0,0,0),(x1,0,zt1),(x0,0,zt0))) triangles.append(_pack_triangle(n,(x0,0,0),(x1,0,0),(x1,0,zt1)))
# Retro for col in range(px_w - 1): x0, x1 = col * pixel_x, (col + 1) * pixel_x zt0 = z_surf(0, col); zt1 = z_surf(0, col+1) n = (0.0, 1.0, 0.0) triangles.append(_pack_triangle(n,(x0,H,zt0),(x1,H,zt1),(x0,H,0))) triangles.append(_pack_triangle(n,(x1,H,zt1),(x1,H,0),(x0,H,0)))
# Sinistra for row in range(px_h - 1): y0 = (px_h-1-row)*pixel_y; y1 = (px_h-2-row)*pixel_y zt0 = z_surf(row,0); zt1 = z_surf(row+1,0) n = (-1.0, 0.0, 0.0) triangles.append(_pack_triangle(n,(0,y0,zt0),(0,y1,zt1),(0,y0,0))) triangles.append(_pack_triangle(n,(0,y1,0),(0,y0,0),(0,y1,zt1)))
# Destra for row in range(px_h - 1): y0 = (px_h-1-row)*pixel_y; y1 = (px_h-2-row)*pixel_y zt0 = z_surf(row,px_w-1); zt1 = z_surf(row+1,px_w-1) n = (1.0, 0.0, 0.0) triangles.append(_pack_triangle(n,(W,y0,0),(W,y1,zt1),(W,y0,zt0))) triangles.append(_pack_triangle(n,(W,y0,0),(W,y1,0),(W,y1,zt1)))
header = b"\x00" * 80 count = struct.pack("<I", len(triangles))1 unmodified line
def save_depth_preview(height_map: np.ndarray, out_path: str): """Salva la depth map come PNG per verifica visiva.""" preview = (height_map * 255).astype(np.uint8) Image.fromarray(preview).save(out_path)
# ─────────────────────────────────────────────# CLI# ─────────────────────────────────────────────
def main(): parser = argparse.ArgumentParser( description="Image → 3D relief tile STL — Fabrication Topologies workshop", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="""Parametri chiave: --width / --height dimensioni della tile in mm (default 100×100) --relief altezza massima del rilievo in mm (default 4) --base spessore della base piatta in mm (default 2) --invert inverte: scuro=alto invece di bianco=alto --quantize N quantizza in N livelli di altezza (effetto a gradini) es: --quantize 4 → 4 livelli netti, bello per pattern urbani --tileable sfuma i bordi per affiancamento senza giunti visibili --blur forza del smoothing (default 0.5, 0=nessuno, 2=molto) --resolution max pixel per lato (default 500, pi�� alto = più dettaglio ma più lento) --preview salva anche la depth map come PNG per verifica """, )
parser.add_argument("input", help="Immagine di input (PNG, JPG, ...)") parser.add_argument("--output", "-o", help="File STL di output (default: input_relief.stl)") parser.add_argument("--width", type=float, default=100.0, help="Larghezza tile in mm (default 100)") parser.add_argument("--height", type=float, default=100.0, help="Altezza tile in mm (default 100, 0=proporzioni originali)") parser.add_argument("--relief", type=float, default=4.0, help="Spessore massimo rilievo in mm (default 4)") parser.add_argument("--base", type=float, default=2.0, help="Spessore base piatta in mm (default 2)") parser.add_argument("--invert", action="store_true", help="Inverte: scuro=alto, bianco=basso") parser.add_argument("--quantize", type=int, default=0, metavar="N", help="Quantizza in N livelli (0=continuo)") parser.add_argument("--tileable", action="store_true", help="Sfuma i bordi per affiancamento") parser.add_argument("--fade", type=int, default=12, help="Pixel di fade per --tileable (default 12)") parser.add_argument("--blur", type=float, default=0.5, help="Smoothing (0=nessuno, 0.5=default, 2=molto)") parser.add_argument("--gamma", type=float, default=1.1, help="Correzione contrasto (default 1.1)") parser.add_argument("--resolution", type=int, default=500, help="Max pixel per lato (default 500)") parser.add_argument("--preview", action="store_true", help="Salva depth map PNG per verifica")
args = parser.parse_args()
# Output path input_path = Path(args.input) if not input_path.exists(): print(f"Errore: file non trovato: {args.input}") sys.exit(1)
output_path = Path(args.output) if args.output else input_path.with_name(input_path.stem + "_relief.stl")
print(f"Input: {input_path}") print(f"Output: {output_path}") print(f"Tile: {args.width:.1f} × {args.height:.1f} mm") print(f"Rilievo: {args.relief:.1f} mm | Base: {args.base:.1f} mm") print(f"Totale Z: {args.relief + args.base:.1f} mm") print(f"Opzioni: invert={args.invert} quantize={args.quantize} tileable={args.tileable}") print()
# Build heightmap print("Elaborazione immagine...") height_map, px_w, px_h = build_heightmap( str(input_path), max_px=args.resolution, invert=args.invert, blur=args.blur, gamma=args.gamma, quantize=args.quantize, tileable=args.tileable, fade_px=args.fade, ) print(f"Risoluzione mesh: {px_w} × {px_h} px ({px_w * px_h:,} vertici)")
if args.preview: preview_path = input_path.with_name(input_path.stem + "_depthmap.png") save_depth_preview(height_map, str(preview_path)) print(f"Depth map salvata: {preview_path}")
# Calcola altezza tile se proporzioni originali tile_h = args.height if args.height > 0 else args.width * px_h / px_w
# Generate STL print("Generazione STL...") stl_bytes = heightmap_to_stl( height_map, px_w, px_h, tile_w_mm=args.width, tile_h_mm=tile_h, relief_mm=args.relief, base_mm=args.base, )
with open(output_path, "wb") as f: f.write(stl_bytes)
size_kb = len(stl_bytes) / 1024 print(f"\n✓ STL salvato: {output_path} ({size_kb:.0f} KB)") print(f" Triangoli: {(len(stl_bytes) - 84) // 50:,}")
if size_kb > 30_000: print(" Avviso: file grande, considera --resolution 300 per ridurre le dimensioni")
print() print("Impostazioni slicer consigliate:") print(" Layer height: 0.15 mm | Infill: 15% | No supports")
if __name__ == "__main__": main() Image.fromarray((height_map * 255).astype(np.uint8)).save(out_path)app.py+142-76
relief_workshop.py+126-243