Spaces:
Running
Running
Upload 2 files
Browse filesFiles changed (2)
- app.py+160-170
- relief_workshop.py+144
10 unmodified lines111213141516171819202122232425262728293031323334353637383940414243444546474811 unmodified lines606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141154 unmodified lines1201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352368 unmodified lines24524624724824925025125225325425525625720 unmodified lines27827928028128228328428528614 unmodified lines30130230330430530630730830931031131231331431531631731831932032132232310 unmodified linesimport numpy as npfrom PIL import Imagefrom relief_workshop import build_heightmap, heightmap_to_stl# ─────────────────────────────────────────────# CORE# ─────────────────────────────────────────────def preview_depthmap(image, invert, quantize_levels, tileable, blur):if image is None:return None, "⚠️ Carica un'immagine."try:with 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:11 unmodified lineselse:tile_h = tile_h_customquantize = int(quantize_levels) if quantize_levels >= 2 else 0height_map, px_w, px_h = build_heightmap(tmp_in, max_px=int(resolution),invert=invert, blur=blur, gamma=1.1,quantize=quantize, tileable=tileable, fade_px=12,)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_")stl_tmp.write(stl_bytes)stl_tmp.close()n_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")return preview, stl_tmp.name, infoexcept Exception as e: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)# ─────────────────────────────────────────────4 unmodified lines@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; }.gradio-container {background: #0a0a0a !important;font-family: 'DM Mono', monospace !important;max-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; }"""8 unmodified linesGUIDE_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>"""20 unmodified linesrelief_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,label="Quantize — livelli (0=continuo, 4–6=gradini)")14 unmodified linesgr.Markdown("## Depth map")depth_out = gr.Image(label="Bianco = alto · Nero = basso",type="numpy", interactive=False)gr.Markdown("## Download")stl_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,]10 unmodified lines111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626311 unmodified lines757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751764 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032042052062078 unmodified lines21621721821922022122222322422522622720 unmodified lines24824925025125225325425525625725825926026126226326426526626726814 unmodified lines28328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231310 unmodified linesimport numpy as npfrom PIL import Imagefrom relief_workshop import (build_heightmap, heightmap_to_stl,blobs_to_stl, blob_preview,)# ─────────────────────────────────────────────# CORE# ─────────────────────────────────────────────def preview_depthmap(image, invert, quantize_levels, tileable, blur,no_base, separate_blobs, threshold):if image is None:return None, "⚠️ Carica un'immagine."try:with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:tmp = f.nameImage.fromarray(image).save(tmp)if no_base and separate_blobs:# Blob preview: mostra i contorni trovatiprev, n = blob_preview(tmp, threshold=int(threshold))Path(tmp).unlink(missing_ok=True)msg = f"{n} blob trovati — ognuno diventerà un cilindretto separato"if n == 0:msg = "Nessun blob trovato. Prova ad abbassare la soglia o usare un'immagine con forme bianche su nero."return prev, msgelse:# Heightmap preview normalequantize = 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, separate_blobs, threshold,invert, quantize_levels, tileable, blur, resolution,):if image is None:11 unmodified lineselse:tile_h = tile_h_customstl_tmp = tempfile.NamedTemporaryFile(suffix=".stl", delete=False, prefix="tile_")if no_base and separate_blobs:# ── Pipeline blob ──stl_bytes, n_blobs = blobs_to_stl(tmp_in,tile_w_mm=float(tile_w),tile_h_mm=float(tile_h),height_mm=float(relief_mm),threshold=int(threshold),)stl_tmp.write(stl_bytes)stl_tmp.close()Path(tmp_in).unlink(missing_ok=True)# Preview: contorni dei blob sull'immagine originalewith tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f2:tmp2 = f2.nameImage.fromarray(image).save(tmp2)preview, n_found = blob_preview(tmp2, threshold=int(threshold))Path(tmp2).unlink(missing_ok=True)n_tri = (len(stl_bytes) - 84) // 50size_kb = len(stl_bytes) / 1024info = (f"✓ {n_blobs} cilindretti separati\n\n"f"Dimensioni tile: {tile_w:.0f} × {tile_h:.0f} mm\n"f"Altezza: {relief_mm:.1f} mm + base piatta\n"f"Soglia blob: {threshold}\n"f"Mesh: {n_tri:,} triangoli totali\n"f"File: {size_kb:.0f} KB\n\n"f"Slicer: layer 0.15 mm · infill 15% · no supports")return preview, stl_tmp.name, infoelse:# ── Pipeline heightmap ──quantize = int(quantize_levels) if quantize_levels >= 2 else 0height_map, px_w, px_h = build_heightmap(tmp_in, max_px=int(resolution),invert=invert, blur=blur, gamma=1.1,quantize=quantize, tileable=tileable, fade_px=12,)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.write(stl_bytes)stl_tmp.close()n_tri = (len(stl_bytes) - 84) // 50size_kb = len(stl_bytes) / 1024base_info = "nessuna (guscio aperto)" 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")return preview, stl_tmp.name, infoexcept Exception as e:return None, None, f"❌ {e}"# ─────────────────────────────────────────────# UI CALLBACKS# ─────────────────────────────────────────────def toggle_custom_height(mode):return gr.update(visible=(mode == "Personalizzata"))def toggle_base_options(no_base):"""Quando si spunta 'Senza base', mostra slider base (se non separato) e opzione blob."""return (gr.update(visible=not no_base), # base_mm slidergr.update(visible=no_base), # separate_blobs checkbox)def toggle_blob_options(no_base, separate_blobs):"""Mostra il threshold solo se entrambe le opzioni sono attive."""show = no_base and separate_blobsreturn gr.update(visible=show)# ─────────────────────────────────────────────4 unmodified lines@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; }.gradio-container {background: #0a0a0a !important;font-family: 'DM Mono', monospace !important;max-width: 1100px !important;}.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; }.gradio-container h2 { 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; }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; }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; }.blob-box { border: 1px solid #2a1a00; background: #0f0900; border-radius: 0; padding: 10px 12px; margin-top: 4px; }.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; }"""8 unmodified linesGUIDE_HTML = """<div class="guide"><strong>bianco = alto, nero = basso</strong> — controlla la depth map prima di generare.<br><br><strong>Quantize</strong> — livelli netti invece di gradiente continuo.<br><strong>Tileable</strong> — bordi sfumati per affiancamento senza giunti.<br><strong>Senza base</strong> — guscio aperto (utile su supporto esterno).<br><strong>Separa i blob</strong> — ogni forma bianca diventa un cilindretto<br> fisicamente separato. Ideal per pois, lettere, pattern binari.<br><br><strong>Slicer:</strong> layer 0.15 mm · infill 15% · no supports · ironing top</div>"""20 unmodified linesrelief_mm = gr.Slider(1, 10, value=4, step=0.5, label="Altezza rilievo (mm)")gr.Markdown("## Base")no_base = gr.Checkbox(label="Senza base (guscio aperto)", value=False)base_mm = gr.Slider(0.5, 5, value=2, step=0.5, label="Spessore base (mm)")# Opzioni blob — visibili solo con "Senza base" attivowith gr.Group(visible=False, elem_classes=["blob-box"]) as blob_group:separate_blobs = gr.Checkbox(label="Separa i blob bianchi (ogni forma = cilindretto separato)",value=False,)threshold = gr.Slider(0, 255, value=127, step=1,label="Soglia binaria (0–255, default 127)",visible=False,)gr.Markdown("## Processing")quantize = gr.Slider(0, 12, value=0, step=1,label="Quantize — livelli (0=continuo, 4–6=gradini)")14 unmodified linesgr.Markdown("## Depth map")depth_out = gr.Image(label="Bianco = alto · Nero = basso",type="numpy", interactive=False)gr.Markdown("## Download")stl_out = gr.File(label="STL file")gr.Markdown("## Info")info_out = gr.Textbox(label="", lines=8, interactive=False)gr.HTML(GUIDE_HTML)# ── Events ──tile_h_mode.change(toggle_custom_height, tile_h_mode, tile_h_custom)def on_no_base(val):base_vis, blob_vis = toggle_base_options(val)return base_vis, blob_visno_base.change(on_no_base, no_base, [base_mm, blob_group])def on_blob_toggle(no_base_val, sep_val):return toggle_blob_options(no_base_val, sep_val)separate_blobs.change(on_blob_toggle, [no_base, separate_blobs], threshold)preview_inputs = [image_in, invert, quantize, tileable, blur,no_base, separate_blobs, threshold]gen_inputs = [image_in, tile_w, tile_h_mode, tile_h_custom,relief_mm, base_mm, no_base, separate_blobs, threshold,invert, quantize, tileable, blur, resolution,]
237 unmodified lines238239240237 unmodified linesdef save_depth_preview(height_map: np.ndarray, out_path: str):Image.fromarray((height_map * 255).astype(np.uint8)).save(out_path)237 unmodified lines238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384237 unmodified linesdef save_depth_preview(height_map: np.ndarray, out_path: str):Image.fromarray((height_map * 255).astype(np.uint8)).save(out_path)# ─────────────────────────────────────────────# BLOB PIPELINE (pezzi separati)# ─────────────────────────────────────────────def _contour_to_stl(contour, height_mm: float) -> bytes:"""Converte un singolo contorno OpenCV in un solido STL chiuso(cilindretto: cappello superiore + base piatta + pareti laterali).Il contorno è in coordinate pixel; scaliamo dopo."""import structpts = contour.reshape(-1, 2).astype(float)n = len(pts)if n < 3:return b""# Centra e normalizza — scala 1 px = 1 unità, poi il chiamante ri-scala# Triangolazione fan dalla centroide per cappello e basecx, cy = pts[:, 0].mean(), pts[:, 1].mean()def pack_tri(normal, v1, v2, v3):return struct.pack("<ffffffffffffH", *normal, *v1, *v2, *v3, 0)tris = []# Cappello superiore (z = height_mm) — fan dalla centroidefor i in range(n):a = pts[i]b = pts[(i + 1) % n]v0 = (cx, cy, height_mm)v1 = (a[0], a[1], height_mm)v2 = (b[0], b[1], height_mm)e1 = (v1[0]-v0[0], v1[1]-v0[1], 0)e2 = (v2[0]-v0[0], v2[1]-v0[1], 0)nx = e1[1]*e2[2] - e1[2]*e2[1]ny = e1[2]*e2[0] - e1[0]*e2[2]nz = e1[0]*e2[1] - e1[1]*e2[0]ln = (nx**2+ny**2+nz**2)**0.5 + 1e-12tris.append(pack_tri((nx/ln, ny/ln, nz/ln), v0, v1, v2))# Base inferiore (z = 0) — fan inversofor i in range(n):a = pts[i]b = pts[(i + 1) % n]v0 = (cx, cy, 0)v1 = (b[0], b[1], 0)v2 = (a[0], a[1], 0)tris.append(pack_tri((0, 0, -1), v0, v1, v2))# Pareti lateralifor i in range(n):a = pts[i]b = pts[(i + 1) % n]# due triangoli per ogni segmentov00 = (a[0], a[1], 0)v10 = (b[0], b[1], 0)v01 = (a[0], a[1], height_mm)v11 = (b[0], b[1], height_mm)# normale laterale approssimatadx, dy = b[0]-a[0], b[1]-a[1]ln = (dx**2+dy**2)**0.5 + 1e-12nx, ny = dy/ln, -dx/lntris.append(pack_tri((nx, ny, 0), v00, v10, v01))tris.append(pack_tri((nx, ny, 0), v10, v11, v01))header = b"\x00" * 80count = struct.pack("<I", len(tris))return header + count + b"".join(tris)def blobs_to_stl(image_path: str,tile_w_mm: float,tile_h_mm: float,height_mm: float,threshold: int = 127,min_area_px: int = 20,) -> tuple[bytes, int]:"""Pipeline blob: soglia binaria → findContours → un cilindretto per blob.Restituisce (stl_bytes, n_blobs).Tutti i cilindretti sono nella stessa mesh (un solo file STL)."""img = Image.open(image_path).convert("L")arr = np.array(img, dtype=np.uint8)# Scala pixel → mmscale_x = tile_w_mm / arr.shape[1]scale_y = tile_h_mm / arr.shape[0]# Soglia binaria_, binary = cv2.threshold(arr, threshold, 255, cv2.THRESH_BINARY)# Trova contorni esternicontours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)all_tris = []n_blobs = 0for cnt in contours:area = cv2.contourArea(cnt)if area < min_area_px:continue# Semplifica il contorno per ridurre la mesheps = 0.01 * cv2.arcLength(cnt, True)cnt = cv2.approxPolyDP(cnt, eps, True)pts = cnt.reshape(-1, 2).astype(float)if len(pts) < 3:continue# Converti pixel → mm (y invertita: OpenCV ha y verso il basso)pts[:, 0] *= scale_xpts[:, 1] = tile_h_mm - pts[:, 1] * scale_y# Genera STL del singolo blobblob_bytes = _contour_to_stl(pts.reshape(-1, 1, 2), height_mm)if blob_bytes:# Estrai solo i triangoli (salta header 84 byte)n_tri = (len(blob_bytes) - 84) // 50all_tris.append(blob_bytes[84:])n_blobs += 1if not all_tris:raise ValueError("Nessun blob trovato. Prova ad abbassare la soglia o caricare un'immagine con forme bianche su sfondo nero.")import structtotal_tris = sum(len(t) // 50 for t in all_tris)header = b"\x00" * 80count = struct.pack("<I", total_tris)return header + count + b"".join(all_tris), n_blobsdef blob_preview(image_path: str, threshold: int = 127, min_area_px: int = 20) -> np.ndarray:"""Restituisce un'immagine con i contorni trovati disegnati sopra l'originale."""img = Image.open(image_path).convert("L")arr = np.array(img, dtype=np.uint8)_, binary = cv2.threshold(arr, threshold, 255, cv2.THRESH_BINARY)contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)preview = cv2.cvtColor(arr, cv2.COLOR_GRAY2RGB)valid = [c for c in contours if cv2.contourArea(c) >= min_area_px]cv2.drawContours(preview, valid, -1, (212, 169, 18), 2)return preview, len(valid)
app.py+160-170
relief_workshop.py+144