Skip to content

Face Blurring Tool #469

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 126 additions & 0 deletions Face Blurring Tool/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
# Face Blur
```bash
python demo.py
# Choose: 1) Your own image, 2) Webcam capture, or 3) Test pattern
``` Tool

A powerful yet simple Python tool for automatically detecting and blurring faces in images, videos, and live webcam feeds.

## 🚀 Get Started in 2 Minutes!

### 1. Install
```bash
pip install -r requirements.txt
```

### 2. Test
```bash
python demo.py
```

### 3. Use
```bash
# Blur a photo
python face_blur.py --input your_photo.jpg

# Live webcam blur
python face_blur.py --input 0 --mode webcam

# Process video
python face_blur.py --input video.mp4 --mode video
```

That's it! 🎉

### More Quick Examples
```bash
# Better quality detection
python face_blur.py --input photo.jpg --method mediapipe

# Pixelate faces for privacy
python face_blur.py --input photo.jpg --blur-type pixelate

# Process entire folder
python face_blur.py --input ./photos --mode batch
```

**Need Help?** Having issues? Try `python demo.py` first!

## Features

- 🔍 **Smart Detection**: Multiple AI methods (Haar Cascades, MediaPipe, DNN)
- 🌊 **Various Blur Effects**: Gaussian, motion blur, and pixelation
- 📸 **Multiple Sources**: Images, videos, webcam, batch processing
- ⚡ **Real-time**: Optimized for live webcam processing
- 🎛️ **Customizable**: Adjustable blur intensity and detection settings
- 🌍 **Cross-platform**: Windows, macOS, Linux

## Usage Examples

### Images
```bash
# Basic image processing
python face_blur.py --input selfie.jpg --mode image

# High quality with MediaPipe
python face_blur.py --input photo.jpg --method mediapipe

# Custom blur effect
python face_blur.py --input photo.jpg --blur-type pixelate --blur-intensity 25
```

### Videos
```bash
# Process video file
python face_blur.py --input family_video.mp4 --mode video

# Custom output location
python face_blur.py --input video.mp4 --mode video --output blurred_video.mp4
```

### Webcam
```bash
# Live webcam blur
python face_blur.py --input 0 --mode webcam

# Save webcam session
python face_blur.py --input 0 --mode webcam --save-webcam
```

### Batch Processing
```bash
# Process all images in folder
python face_blur.py --input ./photos --mode batch --output ./blurred_photos
```

## Options

| Parameter | Description | Default | Options |
|-----------|-------------|---------|---------|
| `--input` | Input file/directory/camera | Required | File path, directory, or `0` for webcam |
| `--mode` | Processing mode | `image` | `image`, `video`, `webcam`, `batch` |
| `--method` | Detection method | `haar` | `haar`, `mediapipe`, `dnn` |
| `--blur-type` | Blur effect type | `gaussian` | `gaussian`, `motion`, `pixelate` |
| `--blur-intensity` | Blur strength | `21` | Any odd number |
| `--output` | Output location | Auto | File/directory path |

## Detection Methods

- **Haar Cascades** (`haar`) - Fast, lightweight, good for real-time
- **MediaPipe** (`mediapipe`) - Modern AI, very accurate and fast
- **DNN** (`dnn`) - Deep learning, highest accuracy (requires model download)

## Blur Types

- **Gaussian** - Smooth, natural blur
- **Motion** - Simulates camera movement
- **Pixelate** - Reduces resolution for privacy

## Requirements

- opencv-python>=4.8.0
- numpy>=1.21.0
- mediapipe>=0.10.0
- argparse
- pathlib
- MediaPipe (optional, for better accuracy)
181 changes: 181 additions & 0 deletions Face Blurring Tool/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
#!/usr/bin/env python3
"""
Face Blur Demo
==============

Simple demonstration of the face blurring tool.
Run this to test the functionality quickly!
"""

import cv2
import numpy as np
import os

def get_demo_image():
"""Get a demo image from user input or create a simple one."""
print("📸 Choose your demo option:")
print("1. Use your own image (recommended)")
print("2. Use webcam to capture a photo")
print("3. Create a simple test pattern")

try:
choice = input("Enter choice (1/2/3): ").strip()

if choice == "1":
# User provides image
image_path = input("Enter path to your image: ").strip().strip('"')
if os.path.exists(image_path):
img = cv2.imread(image_path)
if img is not None:
# Copy to demo location
cv2.imwrite("demo_face.jpg", img)
print(f"✔️ Using your image: {image_path}")
return True
else:
print("✖️ Could not read the image file")
else:
print("✖️ File not found")

elif choice == "2":
# Capture from webcam
return capture_from_webcam()

elif choice == "3":
# Create test pattern
return create_test_pattern()

except KeyboardInterrupt:
print("\n Demo cancelled by user")
return False

# Fallback to test pattern
print("⚠️ Falling back to test pattern...")
return create_test_pattern()

def capture_from_webcam():
"""Capture a photo from webcam for demo."""
try:
print("📷 Opening webcam... Press SPACE to capture, ESC to cancel")
cap = cv2.VideoCapture(0)

if not cap.isOpened():
print("✖️ Could not open webcam")
return False

while True:
ret, frame = cap.read()
if not ret:
print("✖️ Failed to read from webcam")
break

# Show preview
cv2.putText(frame, "Press SPACE to capture, ESC to cancel", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
cv2.imshow('Webcam - Demo Capture', frame)

key = cv2.waitKey(1) & 0xFF
if key == 32: # SPACE key
cv2.imwrite("demo_face.jpg", frame)
print("Photo captured for demo!")
cap.release()
cv2.destroyAllWindows()
return True
elif key == 27: # ESC key
break

cap.release()
cv2.destroyAllWindows()
return False

except Exception as e:
print(f"✖️ Webcam capture failed: {e}")
return False

def create_test_pattern():
"""Create a simple test pattern as fallback."""
print("Creating test pattern...")
img = np.ones((400, 600, 3), dtype=np.uint8) * 240

# Draw a simple face that's more likely to be detected
center = (300, 200)

# Face oval
cv2.ellipse(img, center, (80, 100), 0, 0, 360, (200, 180, 160), -1)

# Eyes (larger and more prominent)
cv2.ellipse(img, (270, 180), (15, 8), 0, 0, 360, (50, 50, 50), -1)
cv2.ellipse(img, (330, 180), (15, 8), 0, 0, 360, (50, 50, 50), -1)

# Eye pupils
cv2.circle(img, (270, 180), 5, (0, 0, 0), -1)
cv2.circle(img, (330, 180), 5, (0, 0, 0), -1)

# Nose
points = np.array([[300, 200], [295, 215], [305, 215]], np.int32)
cv2.fillPoly(img, [points], (150, 120, 100))

# Mouth
cv2.ellipse(img, (300, 240), (20, 10), 0, 0, 180, (100, 50, 50), 3)

# Hair
cv2.ellipse(img, (300, 120), (90, 40), 0, 0, 180, (100, 80, 60), -1)

cv2.imwrite("demo_face.jpg", img)
print("Test pattern created")
return True

def quick_demo():
"""Run a quick demo of the face blurring tool."""
print("Face Blur Tool - Quick Demo")
print("=" * 35)

# Get demo image from user
if not get_demo_image():
print("✖️ Could not get demo image. Exiting...")
return

# Try to import and use the main tool
try:
from face_blur import FaceBlurrer

# Test with different methods
methods = ['haar', 'mediapipe']

print("\n Testing face detection methods...")

for method in methods:
try:
print(f" Testing {method}...")
blurrer = FaceBlurrer(method=method, blur_type='gaussian', blur_intensity=25)
success = blurrer.process_image("demo_face.jpg", f"demo_blurred_{method}.jpg")

if success:
print(f" {method} method worked!")
else:
print(f" ⚠️ {method} method had issues")

except Exception as e:
print(f"✖️ {method} method failed: {e}")

print(f"\n🎉 Demo completed! Check the generated images.")

# Ask about webcam test
try:
response = input("\n📹 Want to test with webcam? (y/n): ").lower()
if response == 'y':
print("🚀 Starting webcam demo... Press 'q' to quit!")
blurrer = FaceBlurrer(method='haar', blur_type='gaussian', blur_intensity=21)
blurrer.process_webcam()
except KeyboardInterrupt:
print("\n Demo stopped by user")

except ImportError as e:
print(f"✖️ Could not import face_blur module: {e}")
print(" Make sure face_blur.py is in the same directory!")

def main():
"""Main demo function."""
quick_demo()

if __name__ == "__main__":
main()
Loading