| import shutil
|
| from pathlib import Path
|
|
|
| import cv2
|
| import numpy as np
|
| from PIL import Image
|
| from tqdm import tqdm
|
|
|
|
|
|
|
| BASE_DIR = Path(r"C:\Users\DESKTOP\Desktop\remove_face")
|
| DATASET_DIR = BASE_DIR / "dataset"
|
|
|
| MODEL_PATH = BASE_DIR / "face_detection_yunet.onnx"
|
|
|
|
|
| REMOVED_DIR_NAME = "removed_human_faces"
|
|
|
|
|
| DELETE_INSTEAD_OF_MOVE = False
|
|
|
| IMAGE_EXTENSIONS = {
|
| ".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"
|
| }
|
|
|
|
|
|
|
| SCORE_THRESHOLD = 0.80
|
|
|
|
|
| NMS_THRESHOLD = 0.3
|
|
|
|
|
|
|
| MIN_FACE_AREA_RATIO = 0.0015
|
|
|
|
|
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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]
|
|
|
|
|
| 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,
|
| ]
|
|
|
|
|
| for p in points:
|
| if p < -0.08 or p > 1.08:
|
| return False
|
|
|
|
|
| if not (0.16 <= re_yn <= 0.55):
|
| return False
|
|
|
| if not (0.16 <= le_yn <= 0.55):
|
| return False
|
|
|
|
|
| eye_gap = abs(le_xn - re_xn)
|
|
|
| if eye_gap < 0.20 or eye_gap > 0.62:
|
| return False
|
|
|
|
|
| if abs(le_yn - re_yn) > 0.14:
|
| return False
|
|
|
|
|
| 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
|
|
|
|
|
| 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
|
|
|
|
|
| mouth_gap = abs(ml_xn - mr_xn)
|
|
|
| if mouth_gap < 0.12 or mouth_gap > 0.65:
|
| return False
|
|
|
|
|
| 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:
|
|
|
|
|
|
|
|
|
| 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)
|
|
|
|
|
| if aspect < 0.60 or aspect > 1.45:
|
| continue
|
|
|
|
|
|
|
| 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() |