Spaces:
Running on Zero
Running on Zero
Update faceless_processing.py
Browse files239 unmodified lines2402412422432442452462472483 unmodified lines25225325425525625725825926026126226326426526612 unmodified lines279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329239 unmodified linesdef detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:h, w = rgb.shape[:2]faces = []mediapipe_success = False# 1. MediaPipe face detection (highly robust for profile/side/tilted faces)try:import mediapipe as mpmodel_path = cfg.mediapipe_model_path3 unmodified linesif os.path.exists(model_path):num_faces = getattr(cfg, 'mediapipe_num_faces', 6)min_conf = getattr(cfg, 'min_face_detection_confidence', 0.68)with _LANDMARKER_LOCK:landmarker = get_landmarker(model_path, num_faces=num_faces, min_detection_confidence=min_conf)mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)mp_result = landmarker.detect(mp_image)# Mark success since the API was successfully executedmediapipe_success = Trueif mp_result.face_landmarks:for face_lms in mp_result.face_landmarks:xs = [lm.x * w for lm in face_lms]12 unmodified linesfw = 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) - Only run as a fallback if MediaPipe is not installed/workingif not mediapipe_success: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]:# Make Haar Cascades stricter to avoid false positives (minNeighbors=8)min_neighbors = max(8, cfg.face_min_neighbors)detected = cascade.detectMultiScale(img_gray,scaleFactor=cfg.face_scale_factor,minNeighbors=min_neighbors,minSize=cfg.face_min_size)if detected is not None and 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]239 unmodified lines2402412422432442452462472483 unmodified lines25225325425525625725825926026126226312 unmodified lines276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399239 unmodified linesdef detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:h, w = rgb.shape[:2]faces = []# 1. MediaPipe face detection on global image (finds large/medium faces)mediapipe_faces = []try:import mediapipe as mpmodel_path = cfg.mediapipe_model_path3 unmodified linesif os.path.exists(model_path):num_faces = getattr(cfg, 'mediapipe_num_faces', 6)min_conf = getattr(cfg, 'min_face_detection_confidence', 0.45)with _LANDMARKER_LOCK:landmarker = get_landmarker(model_path, num_faces=num_faces, min_detection_confidence=min_conf)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]12 unmodified linesfw = int(min(w - fx, bw + 2 * pad_x))fh = int(min(h - fy, bh + 2 * pad_y))mediapipe_faces.append([fx, fy, fw, fh])except Exception as mp_err:print(f"[AI] MediaPipe global face detection failed: {mp_err}")# Add globally detected faces to faces listfaces.extend(mediapipe_faces)# 2. Haar Cascades (frontal and profile)# Haar Cascades find candidates (especially small/blurry faces in groups)haar_candidates = []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 detected is not None and len(detected) > 0:haar_candidates.extend(detected.tolist())except Exception as e:print(f"[AI] Haar Cascade face detection failed: {e}")# 3. Crop-and-Verify Haar Candidates using MediaPipe# Only verify candidates if MediaPipe is availableverified_haar_faces = []if haar_candidates:# Deduplicate Haar candidates first using NMShaar_candidates = _nms_faces(haar_candidates, cfg.face_nms_iou_thresh)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):min_conf = getattr(cfg, 'min_face_detection_confidence', 0.45)# Use a slightly lower threshold for crop verification since we cropped precisely around the face boxcrop_min_conf = max(0.35, min_conf - 0.10)with _LANDMARKER_LOCK:landmarker = get_landmarker(model_path, num_faces=1, min_detection_confidence=crop_min_conf)for (fx, fy, fw, fh) in haar_candidates:# Check if this Haar box overlaps significantly with any globally detected MediaPipe facealready_detected = Falsefor (mx, my, mw, mh) in mediapipe_faces:ix1 = max(fx, mx)iy1 = max(fy, my)ix2 = min(fx+fw, mx+mw)iy2 = min(fy+fh, my+mh)iw = max(0, ix2 - ix1)ih = max(0, iy2 - iy1)inter = iw * iharea_haar = fw * fhif area_haar > 0 and (inter / area_haar) > 0.50:already_detected = Truebreakif already_detected:continue# Crop with 35% paddingpad_w = int(fw * 0.35)pad_h = int(fh * 0.35)x1 = max(0, fx - pad_w)y1 = max(0, fy - pad_h)x2 = min(w, fx + fw + pad_w)y2 = min(h, fy + fh + pad_h)crop_w, crop_h = x2 - x1, y2 - y1if crop_w < 20 or crop_h < 20:continuecrop = rgb[y1:y2, x1:x2]# Resize crop to 256x256 to help MediaPipe detect small faces easilycrop_resized = cv2.resize(crop, (256, 256), interpolation=cv2.INTER_CUBIC)crop_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=crop_resized)crop_result = landmarker.detect(crop_image)if crop_result.face_landmarks:# It is a verified human face!verified_haar_faces.append([fx, fy, fw, fh])print(f"[lineart] Verified face candidate at [{fx}, {fy}, {fw}, {fh}] using crop-based MediaPipe.")else:# If model_path doesn't exist, we fall back to trusting Haar Cascades directlyverified_haar_faces = haar_candidatesexcept Exception as verify_err:print(f"[AI] Crop verification failed, falling back to trusting Haar candidates: {verify_err}")verified_haar_faces = haar_candidatesfaces.extend(verified_haar_faces)# 3. Filter and Deduplicatefaces = [f for f in faces if f[1] < h * cfg.face_max_y_ratio]
faceless_processing.py+118-48