Scoring the clarity of an image

I am currently implementing a feature for scoring the clarity of images, which requires grading the sharpness of pictures. I found some information online and discovered two methods to achieve this: one is using the Laplacian algorithm, and the other is using the Sobel algorithm. I would like to ask what are the differences between these two algorithms? Which one is more suitable for my scenario?

Most articles recommend using the Laplacian algorithm, why is that?

Moreover, I noticed that when using the Laplacian algorithm, the code is very simple, which seems somewhat unbelievable to me. Can this algorithm really score image clarity?

There’s another question; some answers mentioned that if variance falls below ‘100’, it can be considered as blurry. How did they come up with this ‘100’? Is it accurate?

Here’s my code (openCV-python4.9.0):

import cv2
def laplacian_score(image_path):
    # Read the image
    image = cv2.imread(image_path)
    # Convert to grayscale image.
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # Perform edge detection using the Laplace operator.
    laplacian = cv2.Laplacian(gray, cv2.CV_64F)
    # Calculate the variance of the Laplace operator.
    variance = laplacian.var()
    cv2.imshow("Demo", gray)
    # Set the threshold
    threshold = 100
    # Determine whether the image is blurry.
    if variance > threshold:
        print("The image is not blurry, Laplacian operator variance:", variance)
        print("The image is blurry, Laplacian operator variance:", variance)

The Laplacian method does work, but I’m dubious of the fixed threshold of 100. In fact, in my experience the value is highly dependent on the optics, lighting, and the scene being imaged. I have used it for providing feedback while focusing an optic, and I have found that it works best for guiding the operator to a maximum score, but is less useful for pass/fail testing.

I’m not sure what your application is, but a few comments on picking the best focus:

  1. Focus often isn’t uniform across the image, particularly with lower quality optics. You might find that the corners aren’t in focus when the center of the image is, or that focus varies left-to-right across the image. The focus setting with the highest overall score might not be the same as the the one you would objectively choose.
  2. I’ve had good luck using Aruco markers of varying sizes and counting the number of markers that are detected. That has some advantages over a global score when it comes to focusing.

It seem like your application is different, but I would caution against expecting there to be a simple threshold value for general pass/fail testing unless you are doing something that is highly controlled.

1 Like

Thank you for your detailed answer, I strongly agree with your view on the fixed threshold. I will conduct a large number of image tests to verify whether this threshold is reliable.