Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

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.

Medium Python 3.9+ Jun 27, 2026 Automation & scripting 1 views 0 copies

Requires third-party packages — install first
pip install opencv-python numpy

Python code

42 lines
Python 3.9+
from 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

stdout
[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

  1. Use a different blur detection method like the Variance of Laplacian on a sharpness detection library
  2. 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

Sponsored Reserved space — layout preview until AdSense is connected

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Automation & scripting

Related tutorials and quizzes for this topic.