Categories We Write About

Detect blurry images with OpenCV

Detecting blurry images using OpenCV can be done efficiently by measuring the sharpness or focus of an image. One popular approach is to use the Laplacian variance method. The Laplacian operator highlights regions of rapid intensity change, and its variance in an image serves as a sharpness metric: higher variance means a sharper image, while a lower variance indicates blur.

Here’s a detailed explanation and a sample Python code to detect blurry images using OpenCV:


How to Detect Blurry Images with OpenCV Using Laplacian Variance

1. Convert the image to grayscale
Blur detection typically works on grayscale images to simplify processing.

2. Apply the Laplacian operator
This edge detection filter will highlight areas with rapid intensity changes.

3. Calculate the variance of the Laplacian
The variance quantifies the spread of the Laplacian values. Low variance means fewer edges, which implies blur.

4. Set a threshold
Choose a threshold variance value below which an image is considered blurry. This threshold can be fine-tuned based on your application.


Python Code Example

python
import cv2 def is_blurry(image_path, threshold=100.0): # Load the image image = cv2.imread(image_path) if image is None: raise ValueError("Image not found or unable to load.") # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply the Laplacian operator in the grayscale image laplacian = cv2.Laplacian(gray, cv2.CV_64F) # Calculate the variance of the Laplacian variance = laplacian.var() # Determine if image is blurry is_blur = variance < threshold return is_blur, variance # Example usage image_path = 'your_image.jpg' # Replace with your image path blurry, sharpness = is_blurry(image_path, threshold=100.0) print(f"Blurry: {blurry}") print(f"Laplacian Variance (Sharpness): {sharpness}")

Explanation of Parameters

  • threshold: You can adjust this based on your dataset. Common values range from 50 to 150. The best threshold depends on your image resolution and blur level.

  • Laplacian Variance:

    • High variance → Image has many edges, so it’s sharp.

    • Low variance → Few edges detected, likely blurry.


Additional Tips

  • For real-time or batch processing, consider resizing images to a fixed size before processing to maintain consistent variance values.

  • To improve robustness, you can combine Laplacian variance with other methods like Tenengrad or FFT-based sharpness metrics.

  • Visual feedback: Display the Laplacian image to understand edge detection strength.


This method provides a straightforward and fast way to detect blurry images using OpenCV and can be integrated easily into larger image processing pipelines.

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About