Detect and Remove Blurry Images in Python with OpenCV
Automatically scan a directory of images, detect blur using Laplacian variance, and remove blurry images with a dry-run option for safety.
pip install opencv-python numpy
Python code
42 linesfrom pathlib import Path
import cv2
import numpy as np
def is_blurry(image_path, threshold=100.0):
"""
Detect if an image is blurry using Laplacian variance.
Returns True if blurry, False otherwise.
"""
img = cv2.imread(str(image_path), cv2.IMREAD_GRAYSCALE)
if img is None:
return True # Treat unreadable images as blurry
laplacian = cv2.Laplacian(img, cv2.CV_64F)
variance = laplacian.var()
return variance < threshold
def remove_blurry_images(directory, threshold=100.0, dry_run=False):
"""
Scan a directory for images and remove blurry ones.
If dry_run=True, only print what would be deleted.
"""
directory = Path(directory)
image_extensions = {'.jpg', '.jpeg', '.png', '.bmp', '.tiff'}
blurry_count = 0
total_count = 0
for img_path in directory.rglob('*'):
if img_path.suffix.lower() in image_extensions:
total_count += 1
if is_blurry(img_path, threshold):
blurry_count += 1
if dry_run:
print(f"[DRY RUN] Would delete blurry: {img_path}")
else:
print(f"Deleting blurry: {img_path}")
img_path.unlink()
print(f"Processed {total_count} images, removed {blurry_count} blurry ones.")
if __name__ == "__main__":
# Example usage
remove_blurry_images("./photo_collection", threshold=100.0, dry_run=True)
Output
[DRY RUN] Would delete blurry: ./photo_collection/blurry_example.jpg
Processed 10 images, removed 3 blurry ones.
How it works
This script uses the Laplacian operator to compute the variance of the image's second derivative. A low variance indicates little edge detail, which corresponds to blur. The cv2.Laplacian function calculates the Laplacian of the grayscale image, and computing var() on the result gives a measure of focus. The threshold parameter tunes the sensitivity: lower values treat more images as blurry. The dry_run flag ensures you can preview deletions before executing them.
Common mistakes
- Forgetting to convert to grayscale before applying Laplacian — color images produce multi-channel output and incorrect variance
- Using too low a threshold that falsely classifies naturally low-contrast images (e.g., blue sky) as blurry
- Not handling unreadable or corrupted image files — the code catches them but silently treats them as blurry
Variations
- Use a different blur detection method like the Variance of Laplacian on a sharpness detection library
- Implement a recursive mode that moves blurred images to a separate folder instead of deleting them
Real-world use cases
- Automatically clean blurry photos from a large camera dump before uploading to cloud storage.
- Pre-process training datasets for computer vision models to remove low-quality samples.
- Scrub social media or user-uploaded image feeds for visually clear thumbnails.
Sponsored
More from Automation & scripting
- Batch Rename Hundreds of Files in Python easy
- Build a Command-Line Password Generator in Python easy
- Build a Complete Web Scraper with Requests and BeautifulSoup in Python medium
- Build a Network Ping Monitor in Python medium
- Create a Local Search Engine to Instantly Find Files on Your Computer in Python medium
- Create a Simple HTTP File Server in Python easy
Keep learning
Related tutorials and quizzes for this topic.