Spaces:
Running on Zero
Running on Zero
vitor.fran commited on
Commit ·
69e2bdc
1
Parent(s): 1b86ffe
fix: face detection models directory conflict and profile support
Browse filesFiles changed (3)
- __pycache__/faceless_processing.cpython-312.pycAdded
- faceless_processing.py+134-50
- modelsDeleted
23 unmodified lines2425262728293047 unmodified lines787980818283848586878889909192933 unmodified lines97989910010110210310410510610723 unmodified lines13113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517615 unmodified lines19219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522632 unmodified lines2592602612622632642652662672683 unmodified lines272273274275276277278279280144 unmodified lines42542642742842943043123 unmodified linesos.makedirs(cascade_dir, exist_ok=True)xml_urls = {'haarcascade_frontalface_default.xml': 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml','haarcascade_frontalface_alt2.xml': 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_alt2.xml'}for name, url in xml_urls.items():path = os.path.join(cascade_dir, name)47 unmodified linesmin_silhouette_area: float = 200.0 # drop tiny isolated blobs from the silhouette (px²)# Silhouette outlinesilhouette_line_thickness: int = 3 # outer contour stroke width (px); match interior for uniform look# Edge detectioncanny_low: int = 40canny_high: int = 110bilateral_d: int = 11bilateral_sigma_color: int = 80bilateral_sigma_space: int = 80gaussian_ksize: int = 9min_contour_perimeter: float = 50.0 # filters out short noisy linesinterior_line_thickness: int = 3 # thickness of interior detail lines (>=1)# Face detection3 unmodified linesface_max_y_ratio: float = 0.6 # ignore faces below 60% image heightface_nms_iou_thresh: float = 0.4# Face erase ellipse (ratios relative to face bbox) — smaller = more conservativeface_cx_ratio: float = 0.5face_cy_ratio: float = 0.45face_rx_ratio: float = 0.35 # reduced from 0.40 to avoid erasing neck/earsface_ry_ratio: float = 0.38 # reduced from 0.42 to avoid erasing chin/neckface_erase_blur: int = 8face_erase_threshold: int = 130 # higher = sharper face mask edge, less spill23 unmodified linesdef detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:"""Detect faces and filter out false positives in lower body."""h = rgb.shape[0]gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)faces = []try:# Load local classifiers from downloaded foldercascade_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascades")path_default = os.path.join(cascade_dir, 'haarcascade_frontalface_default.xml')path_alt = os.path.join(cascade_dir, 'haarcascade_frontalface_alt2.xml')classifiers = []if os.path.exists(path_default):classifiers.append(cv2.CascadeClassifier(path_default))if os.path.exists(path_alt):classifiers.append(cv2.CascadeClassifier(path_alt))# Fallback to cv2 data directory if local files are missingif not classifiers or all(c.empty() for c in classifiers):classifiers = [cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'),cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml')]for cascade in classifiers:if cascade and not cascade.empty():detected = cascade.detectMultiScale(gray,scaleFactor=cfg.face_scale_factor,minNeighbors=cfg.face_min_neighbors,minSize=cfg.face_min_size)if len(detected) > 0:faces.extend(detected.tolist())except Exception as e:print(f"[AI] Face detection failed or cascades unavailable: {e}")# Remove detections in lower body (false positives)faces = [f for f in faces if f[1] < h * cfg.face_max_y_ratio]# Remove duplicatesfaces = _nms_faces(faces, cfg.face_nms_iou_thresh)return faces15 unmodified linesdef build_silhouette(subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:"""Draw the subject silhouette as a smooth, solid-stroke contour."""mask = subject_mask.copy()# Smooth the mask boundary to eliminate staircase jaggies before tracingif cfg.mask_smooth_ksize > 1:# Use a larger kernel (at least 15) for beautiful organic curvesk = max(15, cfg.mask_smooth_ksize if cfg.mask_smooth_ksize % 2 == 1 else cfg.mask_smooth_ksize + 1)mask = cv2.GaussianBlur(mask, (k, k), 0)_, mask = cv2.threshold(mask, cfg.mask_smooth_threshold, 255, cv2.THRESH_BINARY)contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS)silhouette = np.zeros_like(subject_mask)for cnt in contours:if cv2.contourArea(cnt) >= cfg.min_silhouette_area:# Smooth contour slightly without polygonal blockinesseps = 0.0012 * cv2.arcLength(cnt, True)smooth = cv2.approxPolyDP(cnt, eps, True)cv2.drawContours(silhouette, [smooth], -1, 255, cfg.silhouette_line_thickness)return silhouettedef build_face_erase_mask(faces: list, shape: Tuple[int, int], cfg: LineartConfig) -> np.ndarray:"""Build a soft binary mask covering face interior regions."""h, w = shapemask = np.zeros((h, w), dtype=np.uint8)for (fx, fy, fw, fh) in faces:cx = int(fx + fw * cfg.face_cx_ratio)cy = int(fy + fh * cfg.face_cy_ratio)rx = int(fw * cfg.face_rx_ratio)ry = int(fh * cfg.face_ry_ratio)cv2.ellipse(mask, (cx, cy), (rx, ry), 0, 0, 360, 255, -1)soft = np.array(Image.fromarray(mask).filter(ImageFilter.GaussianBlur(cfg.face_erase_blur)))return (soft > cfg.face_erase_threshold).astype(np.uint8) * 25532 unmodified lines_LANDMARKER_LOCK = threading.Lock()_LANDMARKER_CACHE = Nonedef get_landmarker(model_path):global _LANDMARKER_CACHEif _LANDMARKER_CACHE is None:import mediapipe as mpfrom mediapipe.tasks import pythonfrom mediapipe.tasks.python import vision3 unmodified linesbase_options=base_options,output_face_blendshapes=False,output_facial_transformation_matrixes=False,num_faces=1)_LANDMARKER_CACHE = vision.FaceLandmarker.create_from_options(options)return _LANDMARKER_CACHE144 unmodified linesinterior = build_interior_edges(rgb, subject_mask, cfg)# 5. Erase face details (keep silhouette outline of head shape)face_erase = build_face_erase_mask(faces, (h, w), cfg)interior_clean = cv2.bitwise_and(interior, cv2.bitwise_not(face_erase))# 6. Combine23 unmodified lines242526272829303147 unmodified lines798081828384858687888990919293943 unmodified lines989910010110210310410510610710823 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721815 unmodified lines23423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430532 unmodified lines3383393403413423433443453463473483 unmodified lines352353354355356357358359360361362363364144 unmodified lines50951051151251351451523 unmodified linesos.makedirs(cascade_dir, exist_ok=True)xml_urls = {'haarcascade_frontalface_default.xml': 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml','haarcascade_frontalface_alt2.xml': 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_alt2.xml','haarcascade_profileface.xml': 'https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_profileface.xml'}for name, url in xml_urls.items():path = os.path.join(cascade_dir, name)47 unmodified linesmin_silhouette_area: float = 200.0 # drop tiny isolated blobs from the silhouette (px²)# Silhouette outlinesilhouette_line_thickness: int = 4 # outer contour stroke width (px); match interior for uniform look# Edge detectioncanny_low: int = 35canny_high: int = 85bilateral_d: int = 11bilateral_sigma_color: int = 80bilateral_sigma_space: int = 80gaussian_ksize: int = 9min_contour_perimeter: float = 25.0 # filters out short noisy linesinterior_line_thickness: int = 3 # thickness of interior detail lines (>=1)# Face detection3 unmodified linesface_max_y_ratio: float = 0.6 # ignore faces below 60% image heightface_nms_iou_thresh: float = 0.4# Face erase ellipse (ratios relative to face bbox) — fallback parametersface_cx_ratio: float = 0.5face_cy_ratio: float = 0.50face_rx_ratio: float = 0.44 # adjusted for better fallback erasureface_ry_ratio: float = 0.46face_erase_blur: int = 8face_erase_threshold: int = 130 # higher = sharper face mask edge, less spill23 unmodified linesdef detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:"""Detect faces and filter out false positives in lower body."""h, w = rgb.shape[:2]faces = []# 1. MediaPipe face detection (highly robust for profile/side/tilted faces)try:import mediapipe as mpmodel_path = cfg.mediapipe_model_pathif not model_path or not os.path.exists(model_path):model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")model_path = os.path.join(model_dir, "face_landmarker.task")if os.path.exists(model_path):num_faces = 6with _LANDMARKER_LOCK:landmarker = get_landmarker(model_path, num_faces=num_faces)mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)mp_result = landmarker.detect(mp_image)if mp_result.face_landmarks:for face_lms in mp_result.face_landmarks:xs = [lm.x * w for lm in face_lms]ys = [lm.y * h for lm in face_lms]min_x, max_x = min(xs), max(xs)min_y, max_y = min(ys), max(ys)bw = max_x - min_xbh = max_y - min_ypad_x = bw * 0.15pad_y = bh * 0.15fx = int(max(0, min_x - pad_x))fy = int(max(0, min_y - pad_y))fw = int(min(w - fx, bw + 2 * pad_x))fh = int(min(h - fy, bh + 2 * pad_y))faces.append([fx, fy, fw, fh])except Exception as mp_err:print(f"[AI] MediaPipe face detection failed in detect_faces: {mp_err}")# 2. Haar Cascades (frontal and profile)try:gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))gray_eq = clahe.apply(gray)cascade_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascades")path_default = os.path.join(cascade_dir, 'haarcascade_frontalface_default.xml')path_alt = os.path.join(cascade_dir, 'haarcascade_frontalface_alt2.xml')path_profile = os.path.join(cascade_dir, 'haarcascade_profileface.xml')classifiers = []if os.path.exists(path_default):classifiers.append(cv2.CascadeClassifier(path_default))if os.path.exists(path_alt):classifiers.append(cv2.CascadeClassifier(path_alt))if os.path.exists(path_profile):classifiers.append(cv2.CascadeClassifier(path_profile))if not classifiers or all(c.empty() for c in classifiers):classifiers = [cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'),cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml'),cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_profileface.xml')]for cascade in classifiers:if cascade and not cascade.empty():for img_gray in [gray, gray_eq]:detected = cascade.detectMultiScale(img_gray,scaleFactor=cfg.face_scale_factor,minNeighbors=cfg.face_min_neighbors,minSize=cfg.face_min_size)if len(detected) > 0:faces.extend(detected.tolist())except Exception as e:print(f"[AI] Haar Cascade face detection failed: {e}")# 3. Filter and Deduplicatefaces = [f for f in faces if f[1] < h * cfg.face_max_y_ratio]faces = _nms_faces(faces, cfg.face_nms_iou_thresh)return faces15 unmodified linesdef build_silhouette(subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:"""Draw the subject silhouette as a smooth, solid-stroke contour."""mask = subject_mask.copy()h, w = mask.shape[:2]# Dynamic proportional smoothing based on image size to eliminate jaggies completelyk = int(max(w, h) * 0.035)if k % 2 == 0:k += 1k = max(25, k)mask = cv2.GaussianBlur(mask, (k, k), 0)_, mask = cv2.threshold(mask, cfg.mask_smooth_threshold, 255, cv2.THRESH_BINARY)contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS)silhouette = np.zeros_like(subject_mask)for cnt in contours:if cv2.contourArea(cnt) >= cfg.min_silhouette_area:eps = 0.0012 * cv2.arcLength(cnt, True)smooth = cv2.approxPolyDP(cnt, eps, True)cv2.drawContours(silhouette, [smooth], -1, 255, cfg.silhouette_line_thickness, lineType=cv2.LINE_AA)return silhouettedef build_face_erase_mask(rgb: np.ndarray, faces: list, cfg: LineartConfig) -> np.ndarray:"""Build a soft binary mask covering face interior regions using MediaPipe polygon or fallback ellipse."""h, w = rgb.shape[:2]mask = np.zeros((h, w), dtype=np.uint8)# 1. Exact polygon face erasure using MediaPipe FACE_OVAL landmarks (100% covers mouth/smile/eyes/nose exactly)has_mp_erase = Falsetry:import mediapipe as mpmodel_path = cfg.mediapipe_model_pathif not model_path or not os.path.exists(model_path):model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")model_path = os.path.join(model_dir, "face_landmarker.task")if os.path.exists(model_path):num_faces = 6with _LANDMARKER_LOCK:landmarker = get_landmarker(model_path, num_faces=num_faces)mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)mp_result = landmarker.detect(mp_image)if mp_result.face_landmarks: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]for face_lms in mp_result.face_landmarks:pts = []for idx in FACE_OVAL:lm = face_lms[idx]px = int(lm.x * w)py = int(lm.y * h)pts.append([px, py])pts_np = np.array(pts, np.int32).reshape((-1, 1, 2))cv2.fillPoly(mask, [pts_np], 255)has_mp_erase = Trueexcept Exception as mp_err:print(f"[AI] MediaPipe face contour polygon erase failed: {mp_err}")# 2. Bounding-box Ellipse Fallback (if MediaPipe fails or finds no faces)if not has_mp_erase or not np.any(mask):for (fx, fy, fw, fh) in faces:cx = int(fx + fw * cfg.face_cx_ratio)cy = int(fy + fh * cfg.face_cy_ratio)rx = int(fw * cfg.face_rx_ratio)ry = int(fh * cfg.face_ry_ratio)cv2.ellipse(mask, (cx, cy), (rx, ry), 0, 0, 360, 255, -1, lineType=cv2.LINE_AA)soft = np.array(Image.fromarray(mask).filter(ImageFilter.GaussianBlur(cfg.face_erase_blur)))return (soft > cfg.face_erase_threshold).astype(np.uint8) * 25532 unmodified lines_LANDMARKER_LOCK = threading.Lock()_LANDMARKER_CACHE = None_LANDMARKER_NUM_FACES = Nonedef get_landmarker(model_path, num_faces: int = 1):global _LANDMARKER_CACHE, _LANDMARKER_NUM_FACESif _LANDMARKER_CACHE is None or _LANDMARKER_NUM_FACES != num_faces:import mediapipe as mpfrom mediapipe.tasks import pythonfrom mediapipe.tasks.python import vision3 unmodified linesbase_options=base_options,output_face_blendshapes=False,output_facial_transformation_matrixes=False,num_faces=num_faces,min_face_detection_confidence=0.2,min_face_presence_confidence=0.2,min_tracking_confidence=0.2,)_LANDMARKER_CACHE = vision.FaceLandmarker.create_from_options(options)_LANDMARKER_NUM_FACES = num_facesreturn _LANDMARKER_CACHE144 unmodified linesinterior = build_interior_edges(rgb, subject_mask, cfg)# 5. Erase face details (keep silhouette outline of head shape)face_erase = build_face_erase_mask(rgb, faces, cfg)interior_clean = cv2.bitwise_and(interior, cv2.bitwise_not(face_erase))# 6. Combine
__pycache__/faceless_processing.cpython-312.pycAdded
faceless_processing.py+134-50
modelsDeleted