Determining if an image is tricky and it isn't as straight forward as using the variance from the Laplacian function...
Consider the following images, which images do you consider blurry?
Disclaimer — images 2 to 4 was generated with thispersondoesnotexist.com
These images are an interesting example as each presents a different problem in the realm of computer vision.
- Image 1 — As a photographer, I don't consider the image blurry, the background of the image out of focus however the subject is in sharp focus. You can observe this in images 2 as well.
- Image 2 — the subject of the image is sharp but there is a blurry background
- Image 3 — the overall image is slightly blurry (compared to image 2), however, the image is salvageable using basic processing.
- Image 4 — no part of this image is sharp
- Image 5 — This is a closeup picture of a blanket. is the image sharp? there are no defining edges on this image that can be used to determine if the image is sharp.
All of these images, apart from #2, present a problem to the Laplacian function due to depth of field and soft images. As such, some preprocessing should be done before the Laplacian function is used to reduce false positives.
Preprocessing the image
The first pre-processing step is simple — the image will have a sharpening kernel applied to it. this can be achieved with the following code:
cv2.filter2D(img, -1, np.array([[0,-1,0], [-1,5,-1], [0,-1,0]]))
Secondly, we need to identify the subject of the image — this is not really possible as computers cannot easily understand what the subject of an image is. We can however achieve this by making the assumption that the subject of the image is the sharpest thing in the image.
The canny edge detection method can be used to determine the sharpest part of the image, then use a function to get the return the bounds of these edges as follows:
def canny_segmentation(img, low_threshold=100, high_threshold=200):
edges = cv2.Canny(img, low_threshold, high_threshold)