Spaces:
Running on Zero
Running on Zero
Update faceless_processing.py
#1
by vitordigitizing - opened
33 unmodified lines343536373837383963 unmodified lines10310410510810610710825 unmodified lines13413513614014113713813914314414014114214614314814914414515215314614714831 unmodified lines1801811821911831931841851862 unmodified lines18919019120220319219319457 unmodified lines25225325426725525625721 unmodified lines27928028129529628228328438 unmodified lines3233243253413423433443453263273483283293303523313323543333343353363373383603393623633643653663403413429 unmodified lines3523533543823553563853863873573583592 unmodified lines36236336439636536636736836937037137240037337437537637737837938038140440538238338438538638740838838939039139239341339439539640 unmodified lines43743843946046144044144221 unmodified lines46446546648946746846912 unmodified lines4824834845084854864875 unmodified lines4934944955204964974983 unmodified lines50250350453053150550650750850951053853951151251377 unmodified lines59159259362362459459559657 unmodified lines65465565668868969065765865917 unmodified lines6776786797146806816823 unmodified lines68668768872468933 unmodified lines_LINEART_AVAILABLE = True
def get_lineart_detector(): """ Lazy-load the controlnet_aux LineartDetector (informative-drawings model63 unmodified linesget_lineart_detector()
@dataclassclass LineartConfig: # Backward compatibility fields25 unmodified lines lineart_image_resolution: int = 1024 lineart_coarse: bool = True # AUMENTADO: Força a ignorar dobras de roupa e focar só na estrutura lineart_threshold: int = 100 # EQUILÍBRIO: 80 é forte o suficiente para ignorar sombra, mas não apaga o rosto. lineart_threshold: int = 80 # AJUSTE DE CABELO E CORPO: Diminuído para capturar fios e dobras de roupa. lineart_min_perimeter: float = 70.0 # EQUILÍBRIO: 60 pixels corta fios curtos, preservando linhas estruturais. lineart_min_perimeter: float = 60.0 # Diminuído para manter os traços mais próximos da borda. interior_erode_size: int = 1 # AJUSTE GERAL: Afinado para traços internos mais delicados. interior_line_thickness: int = 2
# ---- Canny fallback parametros ---- canny_low: int = 35 canny_high: int = 7531 unmodified lines mediapipe_num_faces: int = 6
# --- AJUSTE DE SOBRANCELHA --- # Reduzido drasticamente para um traço fino e sutil. eyebrow_thickness: int = 2 # Zerado (era 1). Isso remove o "borrão" que deixava a sobrancelha grossa demais. eyebrow_dilate: int = 0
# Face shape2 unmodified lines face_oval_skip_top_ratio: float = 0.50
def _nms_faces(faces: list, iou_thresh: float) -> list: if not faces: return []57 unmodified lines faces = sorted(faces, key=lambda f: f[2] * f[3], reverse=True)[:max_faces] return faces
def build_subject_mask(rgb: np.ndarray, cfg: LineartConfig, alpha_channel: Optional[np.ndarray] = None) -> np.ndarray: if alpha_channel is not None:21 unmodified lines spline_pts = np.stack([x_new, y_new], axis=1).astype(np.int32) return spline_pts.reshape((-1, 1, 2)) except Exception:
return None
38 unmodified lines
def _line_strength_from_detector(pil_lineart: Image.Image, target_hw: Tuple[int, int]) -> np.ndarray: """ Convert the detector output into a polarity-normalised "line strength" map where lines = bright (255) on a black (0) background, resized to target. Handles either polarity (black-on-white or white-on-black). """ h, w = target_hw gray = np.array(pil_lineart.convert("L")) # Determine background from the image corners corners = [gray[0, 0], gray[0, -1], gray[-1, 0], gray[-1, -1]] bg = float(np.median(corners)) if bg > 127: strength = 255 - gray # dark lines on light bg -> invert strength = 255 - gray else: strength = gray # already light lines on dark bg strength = gray if strength.shape[:2] != (h, w): strength = cv2.resize(strength, (w, h), interpolation=cv2.INTER_LINEAR) return strength.astype(np.uint8)
def build_interior_edges(rgb: np.ndarray, subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray: """ Detect structural lines (clothing folds, lapels, collars, cuffs, hair) using the neural LineartDetector. Produces continuous, illustrator-style strokes. Falls back to the legacy Canny pipeline if controlnet_aux is unavailable. """ h, w = rgb.shape[:2] detector = get_lineart_detector()
9 unmodified lines ) strength = _line_strength_from_detector(pil_out, (h, w))
# Threshold to a binary line map _, edges = cv2.threshold(strength, cfg.lineart_threshold, 255, cv2.THRESH_BINARY)
# Keep lines only inside the subject. Use a SMALL erosion so that # face-shape, hairline and jaw lines (which sit close to the # silhouette) are preserved instead of being eaten away. erode_size = getattr(cfg, 'interior_erode_size', 3) erode_size = max(1, erode_size) if erode_size % 2 == 0:2 unmodified lines eroded_mask = cv2.erode(subject_mask, kernel_erode, iterations=1) edges = cv2.bitwise_and(edges, eroded_mask)
# Remove speckle: drop tiny contours # --- O "ASPIRADOR DE PÓ" MATEMÁTICO --- # Remove pontos solitários grossos antes da medição kernel_clean = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) edges = cv2.morphologyEx(edges, cv2.MORPH_OPEN, kernel_clean, iterations=1)
contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) filtered = np.zeros_like(edges) for cnt in contours: if cv2.arcLength(cnt, False) < cfg.lineart_min_perimeter: perimeter = cv2.arcLength(cnt, False) area = cv2.contourArea(cnt) # Barreira dupla: Remove traços menores que 60px E bolinhas grossas. if perimeter < cfg.lineart_min_perimeter or (perimeter < 150 and area < 10.0): continue cv2.drawContours(filtered, [cnt], -1, 255, cfg.interior_line_thickness)
# Gentle dilation for solid, embroiderable strokes ernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) # Suavização final para cantos realistas de linha de costura kernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) filtered = cv2.dilate(filtered, kernel_dilate, iterations=1) filtered = cv2.GaussianBlur(filtered, (3, 3), 0) # CORREÇÃO: cv2.threshold retorna uma tupla (_, imagem_resultante) filtered = cv2.threshold(filtered, 127, 255, cv2.THRESH_BINARY) _, filtered = cv2.threshold(filtered, 127, 255, cv2.THRESH_BINARY) return filtered except Exception as e: print(f"[AI] Neural lineart failed, falling back to Canny: {e}")
# ---------------- Legacy Canny fallback ---------------- return _build_interior_edges_canny(rgb, subject_mask, cfg)
40 unmodified lines output_face_blendshapes=False, output_facial_transformation_matrixes=False, num_faces=num_faces, # Lower confidence thresholds so smiling / tilted / smaller faces # are still detected and their eyebrows get drawn. min_face_detection_confidence=0.2, min_face_presence_confidence=0.2, min_tracking_confidence=0.2,21 unmodified lines
LEFT_EYEBROW = [70, 63, 105, 66, 107, 55, 65, 52, 53, 46] RIGHT_EYEBROW = [336, 296, 334, 293, 300, 285, 295, 282, 283, 276] # MediaPipe face oval (head/jaw outline), ordered around the perimeter. FACE_OVAL = [10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288, 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136, 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109]12 unmodified lines return False
def draw_eyebrow_landmarks(face_lms, origin_x, origin_y, scale_x, scale_y): # Eyebrows for indices in [LEFT_EYEBROW, RIGHT_EYEBROW]: pts = [] for idx in indices:5 unmodified lines cv2.polylines(eyebrows_layer, [pts_np], isClosed=False, color=255, thickness=eyebrow_thickness, lineType=cv2.LINE_AA)
# Face oval (head / jaw outline) — gives the "formato do rosto" if draw_oval: oval_pts = [] for idx in FACE_OVAL:3 unmodified lines oval_pts.append([px, py]) oval_np = np.array(oval_pts, np.int32) if len(oval_np) >= 4: # Optionally drop the top (forehead) points so the outline # doesn't cut a hard line across the hair. if oval_skip_top > 0: y_min = oval_np[:, 1].min() y_max = oval_np[:, 1].max() cutoff = y_min + (y_max - y_min) * oval_skip_top kept = oval_np[oval_np[:, 1] >= cutoff] if len(kept) >= 4: # open arc (jaw + cheeks), not closed, to leave the # crown of the head to the hair/silhouette lines arc = kept.reshape((-1, 1, 2)) cv2.polylines(eyebrows_layer, [arc], isClosed=False, color=255, thickness=oval_thickness,77 unmodified lines rgb = img_np[:, :, :3] h, w = rgb.shape[:2]
# If no alpha was provided, derive a subject mask with rembg for a clean # silhouette and to confine interior lines to the subject. if alpha_channel is None and _SESSION_ISNET is not None: try: cut = remove(Image.fromarray(rgb).convert("RGBA"), session=_SESSION_ISNET, only_mask=True)57 unmodified lines return total > 0 and (visible / total) >= 0.03
def remove_background_subject(img: Image.Image) -> Image.Image: try: rgba = img.convert("RGBA")17 unmodified lines return remove_background_subject(img)
def build_faceless_embroidery_assets(img: Image.Image, cfg: Optional[LineartConfig] = None, **kwargs) -> Tuple[Image.Image, Image.Image]: if cfg is None: cfg = LineartConfig()3 unmodified lines cfg.negative_prompt = kwargs["negative_prompt"] lineart = make_faceless_lineart(img, cfg) cutout = make_faceless_cutout(img) return lineart, cutout return lineart, cutoutfaceless_processing.py+24-59