Created
June 6, 2023 17:14
-
-
Save AndreiMoraru123/c5115893834a3b8e42f3fb1837875993 to your computer and use it in GitHub Desktop.
Privacy Protection Blur using Haar Cascades in OpenCV
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 cv2 | |
import matplotlib.pyplot as plt | |
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml') | |
profile_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_profileface.xml') | |
plate_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_russian_plate_number.xml') | |
def blur_regions(image, regions): | |
for (x, y, w, h) in regions: | |
kernel_size = max(1, int(min(w, h) / 3.0)) | |
kernel_size += kernel_size % 2 - 1 | |
face_image = image[y:y + h, x:x + w] | |
blurred_face = cv2.medianBlur(face_image, kernel_size) | |
image[y:y + h, x:x + w] = blurred_face | |
return image | |
def detect_and_blur(image_path): | |
image = cv2.imread(image_path) | |
original_image = image.copy() | |
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.05, minNeighbors=3) | |
image = blur_regions(image, faces) | |
profile_faces = profile_cascade.detectMultiScale(gray, scaleFactor=1.05, minNeighbors=3) | |
image = blur_regions(image, profile_faces) | |
plates = plate_cascade.detectMultiScale(gray, scaleFactor=1.05, minNeighbors=3) | |
image = blur_regions(image, plates) | |
original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB) | |
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) | |
fig, ax = plt.subplots(1, 2, figsize=(10, 5)) | |
ax[0].imshow(original_image) | |
ax[0].set_title("Original Image") | |
ax[1].imshow(image) | |
ax[1].set_title("Blurred Image") | |
plt.show() |
Author
AndreiMoraru123
commented
Jun 6, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment