import shutil from pathlib import Path import cv2 import numpy as np from PIL import Image from tqdm import tqdm # === AYARLAR === BASE_DIR = Path(r"C:\Users\DESKTOP\Desktop\remove_face") DATASET_DIR = BASE_DIR / "dataset" MODEL_PATH = BASE_DIR / "face_detection_yunet.onnx" # Dataset DIŞINA taşır: REMOVED_DIR_NAME = "removed_human_faces" # False = silmez, taşır DELETE_INSTEAD_OF_MOVE = False IMAGE_EXTENSIONS = { ".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff" } # Güvenli mod: # Hayvan/doğa/doku silinmesin diye yüksek tuttuk. SCORE_THRESHOLD = 0.80 # NMS ayarı NMS_THRESHOLD = 0.3 # Çok küçük yüzleri yok say. # Daha küçük yaparsan doğa/doku false positive artabilir. MIN_FACE_AREA_RATIO = 0.0015 # Büyük görselleri tarama için küçültür. # 1920 doğa false positive artırdı; 1280 daha güvenli. MAX_IMAGE_SIDE_FOR_SCAN = 1280 def is_image_file(path: Path) -> bool: return path.suffix.lower() in IMAGE_EXTENSIONS def cv2_read_unicode(image_path: Path): """ Windows yolları için güvenli okuma. """ try: data = np.fromfile(str(image_path), dtype=np.uint8) return cv2.imdecode(data, cv2.IMREAD_COLOR) except Exception: return None def resize_for_scan(image): h, w = image.shape[:2] max_side = max(h, w) if max_side <= MAX_IMAGE_SIDE_FOR_SCAN: return image, 1.0 scale = MAX_IMAGE_SIDE_FOR_SCAN / max_side new_w = int(w * scale) new_h = int(h * scale) resized = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA) return resized, scale def valid_yunet_landmarks(face) -> bool: """ YuNet landmark geometrisini kontrol eder. Doğa, hayvan, kaktüs, çiçek, doku false positive'lerini azaltmak için. """ x, y, fw, fh = face[:4] if fw <= 0 or fh <= 0: return False # YuNet landmark sırası: # right_eye_x, right_eye_y, # left_eye_x, left_eye_y, # nose_x, nose_y, # mouth_right_x, mouth_right_y, # mouth_left_x, mouth_left_y re_x, re_y = face[4], face[5] le_x, le_y = face[6], face[7] nose_x, nose_y = face[8], face[9] mr_x, mr_y = face[10], face[11] ml_x, ml_y = face[12], face[13] # Landmark'ları yüz kutusuna göre normalize et re_xn, re_yn = (re_x - x) / fw, (re_y - y) / fh le_xn, le_yn = (le_x - x) / fw, (le_y - y) / fh nose_xn, nose_yn = (nose_x - x) / fw, (nose_y - y) / fh mr_xn, mr_yn = (mr_x - x) / fw, (mr_y - y) / fh ml_xn, ml_yn = (ml_x - x) / fw, (ml_y - y) / fh points = [ re_xn, re_yn, le_xn, le_yn, nose_xn, nose_yn, mr_xn, mr_yn, ml_xn, ml_yn, ] # Noktalar kutunun çok dışına taşmamalı for p in points: if p < -0.08 or p > 1.08: return False # Gözler yüzün üst yarısında olmalı if not (0.16 <= re_yn <= 0.55): return False if not (0.16 <= le_yn <= 0.55): return False # Gözler yatayda mantıklı ayrık olmalı eye_gap = abs(le_xn - re_xn) if eye_gap < 0.20 or eye_gap > 0.62: return False # Gözler çok farklı yükseklikte olmamalı if abs(le_yn - re_yn) > 0.14: return False # Burun iki gözün altında ve orta bölgede olmalı avg_eye_y = (re_yn + le_yn) * 0.5 if nose_yn <= avg_eye_y: return False if not (0.28 <= nose_xn <= 0.72): return False if not (0.35 <= nose_yn <= 0.78): return False # Ağız burundan aşağıda olmalı mouth_y = (mr_yn + ml_yn) * 0.5 if mouth_y <= nose_yn: return False if not (0.52 <= mouth_y <= 0.95): return False # Ağız köşeleri mantıklı ayrık olmalı mouth_gap = abs(ml_xn - mr_xn) if mouth_gap < 0.12 or mouth_gap > 0.65: return False # Burun yaklaşık iki gözün arasında olmalı eye_min_x = min(re_xn, le_xn) eye_max_x = max(re_xn, le_xn) if not (eye_min_x - 0.12 <= nose_xn <= eye_max_x + 0.12): return False return True def has_human_face_yunet(image_path: Path, detector) -> bool: try: with Image.open(image_path) as img: img.verify() image = cv2_read_unicode(image_path) if image is None: print(f"[WARN] OpenCV okuyamadı: {image_path}") return False original_h, original_w = image.shape[:2] original_area = original_h * original_w scan_image, scale = resize_for_scan(image) h, w = scan_image.shape[:2] detector.setInputSize((w, h)) _, faces = detector.detect(scan_image) if faces is None: return False for face in faces: # YuNet format: # x, y, w, h, right_eye_x, right_eye_y, left_eye_x, left_eye_y, # nose_x, nose_y, mouth_right_x, mouth_right_y, # mouth_left_x, mouth_left_y, score x, y, fw, fh = face[:4] score = float(face[-1]) if score < SCORE_THRESHOLD: continue if fw <= 0 or fh <= 0: continue original_face_w = fw / scale original_face_h = fh / scale face_area_ratio = (original_face_w * original_face_h) / original_area if face_area_ratio < MIN_FACE_AREA_RATIO: continue aspect = fw / float(fh) # Daha dar oran: doğa/hayvan false positive azaltır. if aspect < 0.60 or aspect > 1.45: continue # En önemli yeni filtre: # Yüz landmark geometrisi insan yüzüne benzemiyorsa taşıma. if not valid_yunet_landmarks(face): continue return True return False except Exception as e: print(f"[WARN] Okunamadı: {image_path} | {e}") return False def safe_move(src: Path, dataset_root: Path, removed_root: Path): relative_path = src.relative_to(dataset_root) dst = removed_root / relative_path dst.parent.mkdir(parents=True, exist_ok=True) if dst.exists(): stem = dst.stem suffix = dst.suffix counter = 1 while dst.exists(): dst = dst.with_name(f"{stem}_{counter}{suffix}") counter += 1 shutil.move(str(src), str(dst)) def main(): dataset_root = Path(DATASET_DIR) if not dataset_root.exists(): raise FileNotFoundError(f"Dataset klasörü bulunamadı: {dataset_root}") if not MODEL_PATH.exists(): raise FileNotFoundError(f"YuNet model dosyası bulunamadı: {MODEL_PATH}") removed_root = dataset_root.parent / REMOVED_DIR_NAME removed_root.mkdir(exist_ok=True) print("YuNet face detector yükleniyor...") detector = cv2.FaceDetectorYN.create( model=str(MODEL_PATH), config="", input_size=(320, 320), score_threshold=SCORE_THRESHOLD, nms_threshold=NMS_THRESHOLD, top_k=5000, ) image_files = [ p for p in dataset_root.rglob("*") if p.is_file() and is_image_file(p) ] print(f"Toplam kalan görsel bulundu: {len(image_files)}") print(f"Taşınacak klasör: {removed_root}") print(f"SCORE_THRESHOLD: {SCORE_THRESHOLD}") print(f"MIN_FACE_AREA_RATIO: {MIN_FACE_AREA_RATIO}") print(f"MAX_IMAGE_SIDE_FOR_SCAN: {MAX_IMAGE_SIDE_FOR_SCAN}") print("Mod: OpenCV YuNet strict landmark human face detector") print("Not: Bu mod hayvan/doğa silmemek için insan yüzlerini daha katı seçer.") face_count = 0 for image_path in tqdm(image_files, desc="YuNet strict insan yüzü taraması"): if has_human_face_yunet(image_path, detector): face_count += 1 if DELETE_INSTEAD_OF_MOVE: image_path.unlink() print(f"[DELETE] {image_path}") else: safe_move(image_path, dataset_root, removed_root) print(f"[MOVE] {image_path}") print("\nTamamlandı.") print(f"YuNet strict insan yüzü olarak taşınan görsel sayısı: {face_count}") if not DELETE_INSTEAD_OF_MOVE: print(f"Taşınan dosyalar burada: {removed_root}") print("Hugging Face'e sadece dataset klasörünü yükle.") if __name__ == "__main__": main()