import sys sys.path.insert(0, "services/recolor") import numpy as np from PIL import Image import cv2 from fabric_recolor.segmentation.birefnet import BirefnetMatteSegmenter from fabric_recolor.segmentation.prompts import NEGATIVE_PROMPTS, CAVITY_PROMPTS from fabric_recolor.masks import ( alpha_hysteresis, clean_binary, largest_component, fill_small_holes, recessed_pocket_labels, cavity_anchors, _silhouette_bands, ) src = "data/media/originals/fd/fd12e584a23312c7c5edda1015fe9715d3f5fd19a2ef3d375d635cefab91f54b.jpg" img = Image.open(src).convert("RGB") W0, H0 = img.width, img.height scale = min(1.0, 1600 / max(H0, W0)) seg = img.resize((round(W0*scale), round(H0*scale)), Image.BILINEAR) arr = np.asarray(seg) sb = BirefnetMatteSegmenter() sb._load() matte = alpha_hysteresis(sb._matte(seg), ramp_px=max(4, round(8*scale))) mask = clean_binary((matte >= 0.5).astype(np.uint8), 0.002) mask = largest_component(mask) mask = fill_small_holes(mask, 0.01) depth = sb._depth_map(seg) iso = Image.fromarray(arr * mask[..., None].astype(np.uint8)) raw = sb._neg_segmenter().negatives_instances(iso, NEGATIVE_PROMPTS) cav_ids = {i for i,p in enumerate(NEGATIVE_PROMPTS) if p in CAVITY_PROMPTS} inst = [(m, idx in cav_ids) for m, idx in raw] anchors = cavity_anchors(inst, mask) print("anchors px:", int(anchors.sum())) if anchors.any(): print("anchor depth: med=%.3f p10=%.3f p90=%.3f" % ( np.median(depth[anchors>0]), np.percentile(depth[anchors>0],10), np.percentile(depth[anchors>0],90))) for th in (0.25, 0.3, 0.35, 0.4): pockets = recessed_pocket_labels(mask, depth, rim_frac=0.10, deficit_min=th) n = int(pockets.max()) big = [] for i in range(1, n+1): c = (pockets == i) & (mask > 0) a = int(c.sum()) if a > 3000: anch = int((c & (anchors>0)).sum()) band,_ = _silhouette_bands(mask, 6) tb = bool((c & (band>0)).any()) big.append((i, a, f"anch={anch}", f"band={tb}", f"d_med={np.median(depth[c]):.2f}")) print(f"th={th}: {big}") pockets = recessed_pocket_labels(mask, depth, rim_frac=0.10, deficit_min=0.3) viz = arr.copy() viz[pockets > 0] = (viz[pockets > 0] * 0.35 + np.array([255,40,40])*0.65).astype(np.uint8) viz[anchors > 0] = [0, 255, 255] Image.fromarray(viz).save("tmp/dbg-pocket-6413.png") print("saved dbg-pocket-6413.png")