""" relief_workshop.py Image → 3D relief tile — versione workshop Fabrication Topologies """ import argparse import struct import sys from pathlib import Path import cv2 import numpy as np from PIL import Image def 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 gray result = cv2.bilateralFilter( gray.astype(np.uint8), d=9, 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: if levels < 2: return gray 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: 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 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 def build_heightmap( image_path: str, max_px: int = 500, invert: bool = False, blur: float = 0.5, gamma: float = 1.1, quantize: int = 0, tileable: bool = False, fade_px: int = 8, ): gray = load_and_prepare(image_path, max_px) h, w = gray.shape gray = smooth_heightmap(gray, blur) 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 def _pack_triangle(normal, v1, v2, v3) -> bytes: return struct.pack(" bytes: """ 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) 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 ── 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 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)) 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_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 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(" 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 struct pts = 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 base cx, cy = pts[:, 0].mean(), pts[:, 1].mean() def pack_tri(normal, v1, v2, v3): return struct.pack(" 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 → mm scale_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 esterni contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) all_tris = [] n_blobs = 0 for cnt in contours: area = cv2.contourArea(cnt) if area < min_area_px: continue # Semplifica il contorno per ridurre la mesh eps = 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_x pts[:, 1] = tile_h_mm - pts[:, 1] * scale_y # Genera STL del singolo blob blob_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) // 50 all_tris.append(blob_bytes[84:]) n_blobs += 1 if not all_tris: raise ValueError("Nessun blob trovato. Prova ad abbassare la soglia o caricare un'immagine con forme bianche su sfondo nero.") import struct total_tris = sum(len(t) // 50 for t in all_tris) header = b"\x00" * 80 count = struct.pack(" 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)