Last active
August 28, 2024 15:38
-
-
Save Digital39999/0bda05d30db2ba04535e7aad29291ea7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import cv2 | |
import os | |
from tqdm import tqdm | |
def blur_faces(input_folder, output_folder, aggressivity): | |
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml') | |
if not os.path.exists(output_folder): | |
os.makedirs(output_folder) | |
image_formats = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff') | |
for filename in tqdm(os.listdir(input_folder)): | |
if filename.lower().endswith(image_formats): | |
img_path = os.path.join(input_folder, filename) | |
img = cv2.imread(img_path) | |
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
faces = face_cascade.detectMultiScale( | |
gray, | |
scaleFactor=1.05, | |
minNeighbors=5, | |
minSize=(30, 30), | |
flags=cv2.CASCADE_SCALE_IMAGE | |
) | |
if len(faces) == 0: | |
print(f"No faces detected in {filename}. Moving to manual_check.") | |
manual_check_folder = os.path.join(output_folder, 'manual_check') | |
if not os.path.exists(manual_check_folder): | |
os.makedirs(manual_check_folder) | |
output_path = os.path.join(manual_check_folder, filename) | |
cv2.imwrite(output_path, img) | |
continue | |
print(f"Processing {filename}: detected {len(faces)} faces.") | |
for (x, y, w, h) in faces: | |
center = (x + w // 2, y + h // 2) | |
axes = (int((w + h) // 2 * 0.6), int((w + h) // 2 * 0.6)) | |
mask = np.zeros_like(img, dtype=np.uint8) | |
mask = cv2.ellipse(mask, center, axes, 0, 0, 360, (255, 255, 255), -1) | |
blurred_img = cv2.GaussianBlur(img, (99, 99), aggressivity) | |
img = np.where(mask == np.array([255, 255, 255]), blurred_img, img) | |
output_path = os.path.join(output_folder, filename) | |
cv2.imwrite(output_path, img) | |
def main(): | |
input_folder = input("Enter input directory containing images: ").strip() | |
output_folder = input("Enter output directory for processed images: ").strip() | |
if not os.path.exists(output_folder): | |
os.makedirs(output_folder) | |
while True: | |
try: | |
aggressivity = int(input("Enter aggressivity parameter for blur effect (1-100): ").strip()) | |
if 1 <= aggressivity <= 100: | |
break | |
else: | |
print("Error: Aggressivity parameter must be between 1 and 100.") | |
except ValueError: | |
print("Error: Please enter a valid integer.") | |
blur_faces(input_folder, output_folder, aggressivity) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment