Spaces:
No application file
No application file
| import cv2 | |
| import numpy as np | |
| import os | |
| def write_log_no_face_detected(image_path, log_file="no_face_detected_log.txt"): | |
| with open(log_file, "a") as log: | |
| log.write(image_path + "\n") | |
| def crop_to_face(image_path): | |
| image = cv2.imread(image_path) | |
| face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') | |
| faces = face_cascade.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) | |
| if len(faces) == 0: | |
| write_log_no_face_detected(image_path) | |
| print("No faces detected in", image_path) | |
| return None | |
| x, y, w, h = faces[0] | |
| face_cropped = image[y:y+h, x:x+w] | |
| height, width = face_cropped.shape[:2] | |
| scale_factor = max(768 / height, 768 / width) | |
| face_resized = cv2.resize(face_cropped, None, fx=scale_factor, fy=scale_factor, interpolation=cv2.INTER_AREA) | |
| final_image = np.zeros((768, 768, 3), dtype=np.uint8) | |
| center_x, center_y = (768 - face_resized.shape[1]) // 2, (768 - face_resized.shape[0]) // 2 | |
| final_image[center_y:center_y+face_resized.shape[0], center_x:center_x+face_resized.shape[1]] = face_resized | |
| return final_image | |
| def process_images(input_folder, output_folder): | |
| if not os.path.exists(output_folder): | |
| os.makedirs(output_folder) | |
| for filename in os.listdir(input_folder): | |
| if filename.lower().endswith(('.png', '.jpg', '.jpeg')): | |
| input_path = os.path.join(input_folder, filename) | |
| output_path = os.path.join(output_folder, filename) | |
| cropped_image = crop_to_face(input_path) | |
| if cropped_image is not None: | |
| cv2.imwrite(output_path, cropped_image) | |
| print(f"Processed and saved: {filename}") | |
| else: | |
| print(f"Skipped (No face detected): {filename}") | |
| input_folder = './bilder' | |
| output_folder = './output_crop' | |
| process_images(input_folder, output_folder) |