Lesson 3 of 12
Face Blur Privacy Tool
Build a privacy protection tool that automatically detects and blurs all faces in photos or videos — useful for publishing images while protecting the identities of individuals.
Face Blur Implementation
Face Blur Implementation
import cv2
import numpy as np
class FaceBlurTool:
"""
Automatically detects and blurs faces in images and videos.
Useful for privacy protection before publishing.
"""
def __init__(self, blur_strength=25):
self.face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
)
self.blur_strength = blur_strength # Must be odd
def detect_faces(self, gray):
"""Detect faces with histogram equalisation for better accuracy."""
gray_eq = cv2.equalizeHist(gray)
faces = self.face_cascade.detectMultiScale(
gray_eq,
scaleFactor=1.05,
minNeighbors=4,
minSize=(30, 30)
)
return faces if len(faces) > 0 else []
def blur_face(self, image, x, y, w, h, method="gaussian"):
"""Apply blur to a face region."""
# Add 20% padding around the detected face
pad_x = int(w * 0.2)
pad_y = int(h * 0.2)
img_h, img_w = image.shape[:2]
x1 = max(0, x - pad_x)
y1 = max(0, y - pad_y)
x2 = min(img_w, x + w + pad_x)
y2 = min(img_h, y + h + pad_y)
face_region = image[y1:y2, x1:x2]
if method == "gaussian":
k = self.blur_strength | 1 # Ensure odd
blurred = cv2.GaussianBlur(face_region, (k, k), 0)
elif method == "pixelate":
# Pixelation: shrink then enlarge
small = cv2.resize(face_region, (20, 20), interpolation=cv2.INTER_LINEAR)
blurred = cv2.resize(small, (x2-x1, y2-y1), interpolation=cv2.INTER_NEAREST)
else: # black box
blurred = np.zeros_like(face_region)
image[y1:y2, x1:x2] = blurred
return image
def process_image(self, image_path, output_path="blurred_faces.jpg",
method="gaussian"):
"""Process a single image."""
image = cv2.imread(image_path)
if image is None:
print(f"Could not load: {image_path}")
return 0
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = self.detect_faces(gray)
print(f"Detected {len(faces)} face(s) in '{image_path}'")
for (x, y, w, h) in faces:
image = self.blur_face(image, x, y, w, h, method=method)
cv2.imwrite(output_path, image)
print(f"Saved: {output_path} (method: {method})")
return len(faces)
def process_video(self, video_path, output_path="blurred_video.mp4",
method="gaussian"):
"""Process an entire video file."""
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS) or 25
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
writer = cv2.VideoWriter(output_path, fourcc, fps, (w, h))
frame_count = 0
total_faces = 0
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = self.detect_faces(gray)
total_faces += len(faces)
for (fx, fy, fw, fh) in faces:
frame = self.blur_face(frame, fx, fy, fw, fh, method=method)
writer.write(frame)
frame_count += 1
if frame_count % 50 == 0:
pct = frame_count / total * 100 if total > 0 else 0
print(f" Frame {frame_count}/{total} ({pct:.1f}%)...")
cap.release()
writer.release()
print(f"Video complete: {frame_count} frames, {total_faces} face detections")
print(f"Saved: {output_path}")
# Process an image
blurrer = FaceBlurTool(blur_strength=55)
blurrer.process_image("group_photo.jpg", method="gaussian")
# Process a video
# blurrer.process_video("meeting_recording.mp4", method="pixelate")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment
Finished this lesson?
0 of 12 in Module 12