Spaces:
Running
Running
Upload 2 files
Browse filesFiles changed (2)
- app.py+142-76
- relief_workshop.py+126-243
1234568 unmodified lines151617181920213 unmodified lines2526272829303132333435363738394041424344454647484950515219 unmodified lines727374757677787980818283848586878889902 unmodified lines939495969798991001011024 unmodified lines1071081091101111121131141151161171183 unmodified lines1221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002013 unmodified lines20520620720820921021121221321421521621721821922011 unmodified lines2322332342352362372383 unmodified lines242243244245246247248249250251252253254255256257258"""app.py — Pattern Ground Relief GeneratorGradio 5.x — compatibile Python 3.13 — HuggingFace Spaces"""import tempfile8 unmodified lines# ─────────────────────────────────────────────# CORE FUNCTIONS# ─────────────────────────────────────────────def preview_depthmap(image, invert, quantize_levels, tileable, blur):3 unmodified lineswith tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:tmp = f.nameImage.fromarray(image).save(tmp)quantize = int(quantize_levels) if quantize_levels >= 2 else 0height_map, px_w, px_h = build_heightmap(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"if invert:info += " (invertita)"return preview, infoexcept Exception as e:return None, f"❌ {e}"def generate_stl(image,tile_w, tile_h_mode, tile_h_custom,relief_mm, base_mm,invert, quantize_levels, tileable, blur, resolution,):if image is None:19 unmodified lines)Path(tmp_in).unlink(missing_ok=True)# Depth map previewpreview = (height_map * 255).astype(np.uint8)# Generate STL bytesstl_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),)# Write to named temp file (Gradio 5 needs a real path)stl_tmp = tempfile.NamedTemporaryFile(suffix=".stl", delete=False, prefix="tile_")2 unmodified linesn_tri = (len(stl_bytes) - 84) // 50size_kb = len(stl_bytes) / 1024info = (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"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 linesreturn None, None, f"❌ {e}"# ─────────────────────────────────────────────# UI# ─────────────────────────────────────────────CSS = """@import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Instrument+Serif:ital@0;1&display=swap');body { background: #0a0a0a !important; }3 unmodified linesmax-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;}h2 {font-family: 'DM Mono', monospace !important;font-size: 0.6rem !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;}button.primary {background: #d4a912 !important;color: #0a0a0a !important;border: none !important;}button.secondary {background: transparent !important;color: #888 !important;border: 1px solid #333 !important;}"""HEADER = """# Pattern Ground**Fabrication Topologies — Vectorealism × Dropcity · Design Week Milano 2026**Converti un'immagine in una tile di rilievo 3D pronta per la stampa."""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."""def toggle_custom(mode):return gr.update(visible=(mode == "Personalizzata"))with gr.Blocks(css=CSS, title="Pattern Ground") as demo:gr.Markdown(HEADER)with gr.Row():# ── Colonna sinistra ──with gr.Column(scale=1):gr.Markdown("## Immagine")3 unmodified linestile_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",)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)")gr.Markdown("## Processing")quantize = gr.Slider(0, 12, value=0, step=1,11 unmodified linespreview_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 linesstl_out = gr.File(label="STL file")gr.Markdown("## Info")info_out = gr.Textbox(label="", lines=7, interactive=False)gr.Markdown(GUIDE)# ── Events ──tile_h_mode.change(toggle_custom, tile_h_mode, tile_h_custom)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,]preview_btn.click(preview_depthmap, preview_inputs, [depth_out, info_out])1234568 unmodified lines151617181920213 unmodified lines25262728293031323334353637383940414243444546474819 unmodified lines6869707172737475767778798081828384852 unmodified lines8889909192939495969798991004 unmodified lines1051061071081091101111121131141151161171181191201211221233 unmodified lines1271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642653 unmodified lines26927027127227327427527627727827928028128228328428511 unmodified lines2972982993003013023 unmodified lines306307308309310311312313314315316317318319320321322323324"""app.py — Pattern Ground Relief GeneratorGradio 5.x — Python 3.13 — HuggingFace Spaces"""import tempfile8 unmodified lines# ─────────────────────────────────────────────# CORE# ─────────────────────────────────────────────def preview_depthmap(image, invert, quantize_levels, tileable, blur):3 unmodified lineswith tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:tmp = f.nameImage.fromarray(image).save(tmp)quantize = int(quantize_levels) if quantize_levels >= 2 else 0height_map, px_w, px_h = build_heightmap(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)msg = f"Depth map {px_w}×{px_h}px — bianco=alto, nero=basso"if invert:msg += " (invertita)"return preview, msgexcept Exception as e:return None, f"❌ {e}"def generate_stl(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)preview = (height_map * 255).astype(np.uint8)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=effective_base,)stl_tmp = tempfile.NamedTemporaryFile(suffix=".stl", delete=False, prefix="tile_")2 unmodified linesn_tri = (len(stl_bytes) - 84) // 50size_kb = len(stl_bytes) / 1024base_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"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 linesreturn 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=Bebas+Neue&family=DM+Mono:ital,wght@0,400;0,500;1,400&display=swap');body { background: #0a0a0a !important; }3 unmodified linesmax-width: 1100px !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;}/* ── SECTION LABELS ── */.gradio-container h2,.section-label {font-family: 'DM Mono', monospace !important;font-size: 9px !important;letter-spacing: 0.2em !important;color: #d4a912 !important;text-transform: uppercase !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: #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; }/* ── 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;}/* ── 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; }"""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>"""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.HTML(HEADER_HTML)with gr.Row():with gr.Column(scale=1):gr.Markdown("## Immagine")3 unmodified linestile_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",)tile_h_custom = gr.Slider(20, 200, value=100, step=5,label="Altezza personalizzata (mm)", visible=False)gr.Markdown("## Rilievo")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 linespreview_btn = gr.Button("Depth map preview", variant="secondary")gen_btn = gr.Button("Genera STL", variant="primary")with gr.Column(scale=1):gr.Markdown("## Depth map")depth_out = gr.Image(label="Bianco = alto · Nero = basso",3 unmodified linesstl_out = gr.File(label="STL file")gr.Markdown("## Info")info_out = gr.Textbox(label="", lines=8, interactive=False)gr.HTML(GUIDE_HTML)# Eventstile_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, no_base,invert, quantize, tileable, blur, resolution,]preview_btn.click(preview_depthmap, preview_inputs, [depth_out, info_out])
1234567891011121314151617186 unmodified lines252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687886 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341356 unmodified lines1421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422431 unmodified line245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357"""relief_workshop.pyImage → 3D relief tile — versione workshop Fabrication TopologiesUso:python relief_workshop.py input.png [opzioni]Esempi:python relief_workshop.py pattern.pngpython relief_workshop.py pattern.png --width 100 --height 100 --relief 4 --base 2python relief_workshop.py pattern.png --width 100 --height 100 --invert --tileablepython relief_workshop.py pattern.png --width 100 --height 100 --relief 6 --quantize 4Dipendenze: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 graydef smooth_heightmap(gray: np.ndarray, blur: float) -> np.ndarray:"""Bilateral filter + smoothing leggero."""if blur <= 0:return graysigma_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).astype(np.float32)return resultdef 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 rimappanormalized = gray / 255.0quantized = np.floor(normalized * levels) / levelsreturn (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'affiancamentosenza scalini visibili ai giunti."""if fade_px <= 0:return grayh, w = gray.shapemean_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'internoresult[i, :] = alpha * gray[i, :] + (1 - alpha) * mean_valresult[h - 1 - i, :] = alpha * gray[h - 1 - i, :] + (1 - alpha) * mean_valresult[:, i] = alpha * result[:, i] + (1 - alpha) * mean_valresult[:, w - 1 - i] = alpha * result[:, w - 1 - i] + (1 - alpha) * mean_valreturn result6 unmodified linesquantize: 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.shapegray = smooth_heightmap(gray, blur)# Gamma correctiongray = np.power(gray / 255.0, gamma) * 255.0if quantize >= 2:gray = quantize_heightmap(gray, quantize)if tileable:gray = make_tileable(gray, fade_px)if invert:gray = 255.0 - graygray = np.clip(gray, 0, 255)# Normalizza [0, 1]height_map = gray / 255.0return height_map, w, h# ─────────────────────────────────────────────# STL GENERATION# ─────────────────────────────────────────────def _pack_triangle(normal, v1, v2, v3) -> bytes:return struct.pack("<ffffffffffffH",*normal, *v1, *v2, *v3, 0)def heightmap_to_stl(6 unmodified linesbase_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)."""pixel_x = tile_w_mm / (px_w - 1)pixel_y = tile_h_mm / (px_h - 1)# z assoluto di ogni pixel della superficie# base a z=0, rilievo sale fino a relief_mmdef z(row, col):return base_mm + height_map[row, col] * relief_mmtriangles = []# ── Superficie superiore (rilievo) ──for row in range(px_h - 1):for col in range(px_w - 1):x0, x1 = col * pixel_x, (col + 1) * pixel_xy0, y1 = (px_h - 1 - row) * pixel_y, (px_h - 2 - row) * pixel_yz00 = 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 1e1 = 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 2e1 = 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):for col in range(px_w - 1):x0, x1 = col * pixel_x, (col + 1) * pixel_xy0, y1 = (px_h - 1 - row) * pixel_y, (px_h - 2 - row) * pixel_yn = (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_mmH = tile_h_mm# ── Pareti laterali ──# Fronte (y=0)for col in range(px_w - 1):x0, x1 = col * pixel_x, (col + 1) * pixel_xz0_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_xz0_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_yy1 = (px_h - 2 - row) * pixel_yz0_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_yy1 = (px_h - 2 - row) * pixel_yz0_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)))header = b"\x00" * 80count = struct.pack("<I", len(triangles))1 unmodified linedef 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 pathinput_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 heightmapprint("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 originalitile_h = args.height if args.height > 0 else args.width * px_h / px_w# Generate STLprint("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) / 1024print(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()1234566 unmodified lines13141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596 unmodified lines66676869707172737475767778798081828384858687886 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342351 unmodified line237238239240"""relief_workshop.pyImage → 3D relief tile — versione workshop Fabrication Topologies"""import argparse6 unmodified linesfrom PIL import Imagedef load_and_prepare(image_path: str, max_px: int) -> np.ndarray: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)return np.array(img.convert("L"), dtype=np.float32)def smooth_heightmap(gray: np.ndarray, blur: float) -> np.ndarray:if blur <= 0:return grayresult = cv2.bilateralFilter(gray.astype(np.uint8), d=9,sigmaColor=min(60, blur * 15),sigmaSpace=min(10, blur * 3)).astype(np.float32)return resultdef quantize_heightmap(gray: np.ndarray, levels: int) -> np.ndarray:if levels < 2:return graynormalized = gray / 255.0quantized = np.floor(normalized * levels) / levelsreturn (quantized * 255.0).astype(np.float32)def make_tileable(gray: np.ndarray, fade_px: int) -> np.ndarray:if fade_px <= 0:return grayh, w = gray.shapemean_val = float(np.mean(gray))result = gray.copy()fade = min(fade_px, w // 4, h // 4)for i in range(fade):alpha = i / faderesult[i, :] = alpha * gray[i, :] + (1 - alpha) * mean_valresult[h - 1 - i, :] = alpha * gray[h - 1 - i, :] + (1 - alpha) * mean_valresult[:, i] = alpha * result[:, i] + (1 - alpha) * mean_valresult[:, w - 1 - i] = alpha * result[:, w - 1 - i] + (1 - alpha) * mean_valreturn result6 unmodified linesquantize: int = 0,tileable: bool = False,fade_px: int = 8,):gray = load_and_prepare(image_path, max_px)h, w = gray.shapegray = smooth_heightmap(gray, blur)gray = np.power(gray / 255.0, gamma) * 255.0if quantize >= 2:gray = quantize_heightmap(gray, quantize)if tileable:gray = make_tileable(gray, fade_px)if invert:gray = 255.0 - graygray = np.clip(gray, 0, 255)return gray / 255.0, w, hdef _pack_triangle(normal, v1, v2, v3) -> bytes:return struct.pack("<ffffffffffffH", *normal, *v1, *v2, *v3, 0)def heightmap_to_stl(6 unmodified linesbase_mm: float,) -> bytes:"""Genera STL da heightmap [0,1].Se base_mm == 0: mesh aperta sotto (solo superficie + pareti che scendonofino 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)def z_surf(row, col):# z della superficie di rilievoreturn base_mm + height_map[row, col] * relief_mmdef z_bottom(row, col):# z del bordo inferiore: 0 se c'è la base, minimo locale se noif no_base:return height_map[row, col] * relief_mm # inizia dal rilievo stesso (min=0)return 0.0triangles = []# ── Superficie superiore ──for row in range(px_h - 1):for col in range(px_w - 1):x0, x1 = col * pixel_x, (col + 1) * pixel_xy0 = (px_h - 1 - row) * pixel_yy1 = (px_h - 2 - row) * pixel_yz00 = 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))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 (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_xy0 = (px_h - 1 - row) * pixel_yy1 = (px_h - 2 - row) * pixel_yn = (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_mmif 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_xzt0 = z_surf(px_h - 1, col); zt1 = z_surf(px_h - 1, col + 1)zb0 = height_map[px_h-1, col] * relief_mmzb1 = height_map[px_h-1, col+1] * relief_mmn = (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_xzt0 = z_surf(0, col); zt1 = z_surf(0, col + 1)zb0 = height_map[0, col] * relief_mmzb1 = height_map[0, col+1] * relief_mmn = (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_yy1 = (px_h - 2 - row) * pixel_yzt0 = z_surf(row, 0); zt1 = z_surf(row + 1, 0)zb0 = height_map[row, 0] * relief_mmzb1 = height_map[row+1, 0] * relief_mmn = (-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_yy1 = (px_h - 2 - row) * pixel_yzt0 = z_surf(row, px_w-1); zt1 = z_surf(row+1, px_w-1)zb0 = height_map[row, px_w-1] * relief_mmzb1 = height_map[row+1, px_w-1] * relief_mmn = (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# Frontefor col in range(px_w - 1):x0, x1 = col * pixel_x, (col + 1) * pixel_xzt0 = 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)))# Retrofor col in range(px_w - 1):x0, x1 = col * pixel_x, (col + 1) * pixel_xzt0 = 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)))# Sinistrafor row in range(px_h - 1):y0 = (px_h-1-row)*pixel_y; y1 = (px_h-2-row)*pixel_yzt0 = 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)))# Destrafor row in range(px_h - 1):y0 = (px_h-1-row)*pixel_y; y1 = (px_h-2-row)*pixel_yzt0 = 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" * 80count = struct.pack("<I", len(triangles))1 unmodified linedef save_depth_preview(height_map: np.ndarray, out_path: str):Image.fromarray((height_map * 255).astype(np.uint8)).save(out_path)
app.py+142-76
relief_workshop.py+126-243