DEV Community

Cover image for Blurry Image Detection in Laravel
Hafiq Iqmal
Hafiq Iqmal

Posted on

Blurry Image Detection in Laravel

Article originated from https://medium.com/@hafiqiqmal93/blurry-image-detection-in-laravel-4c91168e00f1

Crucial aspect of user experience, storing blurry images is significantly detract from the quality of a website or application. This article delves into how you can detect and manage blurry images using Laravel with help of Python and OpenCV, ensuring the application’s media remains sharp and engaging.

The Challenge of Blurry Images

Blurry images are more than just a visual nuisance; they can undermine the professionalism of your website or app. In e-commerce, real estate listings, online galleries or any platform where image quality is paramount, ensuring clarity is essential. The challenge lies in detecting blurriness programmatically.

Laravel to the Rescue

Laravel can be paired with Python to create an effective solution for this problem. By leveraging Laravel’s file validation alongside a Python script utilizing OpenCV, developers can seamlessly integrate blur detection into their file upload processes.

Blurriness Detection Concept

The detection of blurry images involves analyzing the image’s sharpness. This is typically done using the Laplacian operator, a mathematical tool used in image processing. The Laplacian operator measures the rate at which pixel intensity changes, and a lower variance of the Laplacian indicates a blurrier image.

Implementing in Laravel

In Laravel, we can create a custom validation rule to check for image blurriness. This rule executes a Python script that uses the Laplacian operator to determine the sharpness of the image. Let’s break down the process:

Installation OpenCV Python:

Install PIP (Ubuntu) :

sudo apt install python3-pip
Enter fullscreen mode Exit fullscreen mode

Install OpenCV using PIP

pip3 install opencv-python
Enter fullscreen mode Exit fullscreen mode

You might want to consider to install under **www-data** user if your application runs under **www-data**. If Yes, follow below commands to install

sudo mkdir /var/www/.local
sudo mkdir /var/www/.cache
sudo chown www-data.www-data /var/www/.local
sudo chown www-data.www-data /var/www/.cache
sudo -H -u www-data pip3 install opencv-python
Enter fullscreen mode Exit fullscreen mode

Create Python Script

import sys
import cv2

def get_image_laplacian_value(image_path):
    image = cv2.imread(image_path)
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    return cv2.Laplacian(gray_image, cv2.CV_64F).var()

if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit(1)
    image_path = sys.argv[1]
    laplacian_value = get_image_laplacian_value(image_path)
    print(laplacian_value)

Enter fullscreen mode Exit fullscreen mode

Create Laravel Rule:

class ImageBlurDetectionRule implements ValidationRule
{
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if ( ! $value instanceof UploadedFile) {
            return;
        }
        // ignore if not image
        if ('' !== $value->getPath() && ! in_array($value->guessExtension(), ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp'])) {
            return;
        }
        // get real path for the file
        $path = $value->getRealPath();
        $command = escapeshellcmd(config('image.python_path') . " blur_detection.py '{$path}'");
        $result = Process::path(base_path('scripts'))->run($command);
        if ( ! $result->successful()) {
            return;
        }
        if (trim($result->output()) < 100) {
            $fail(__('Blur image are not accepted. Please make sure your :attribute image is clearly visible.'));
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

How It Works

The integration of Laravel with a Python script for blur detection works in a seamless manner, offering a sophisticated yet straightforward approach to ensuring image quality. Here’s how the process unfolds:

Image Upload

When a user uploads an image to the Laravel application, the custom validation rule (ImageBlurDetectionRule) is triggered.

Validation Rule Execution

This rule first checks if the uploaded file is indeed an image by verifying its extension. If the file is not an image, the process stops here.

Python Script Invocation

If the file is an image, the rule then calls a Python script, blur_detection.py. The image's path is passed to this script as a command-line argument.

Image Processing in Python:

  • The Python script uses OpenCV to handle the image analysis.
  • The script reads the image and converts it into grayscale. This simplification allows for more straightforward analysis without the complexity of color.
  • It then applies the Laplacian operator to the grayscale image. The Laplacian operator is a mathematical tool that highlights areas of rapid intensity change, which are typically edges in an image. Blurry images have fewer and less defined edges, resulting in a lower variance of the Laplacian.

Blurriness Measurement

The script calculates the variance of the Laplacian, which serves as a measure of the image’s sharpness. A lower variance indicates a blurrier image.

Result Evaluation:

  • The script outputs the Laplacian variance as a numerical value.
  • Back in Laravel, the validation rule captures this output and checks if the value falls below a predefined threshold. This threshold determines whether an image is considered sharp enough.

Validation Feedback

If the image is too blurry (ex: the Laplacian variance is below the threshold), the validation rule fails and the user receives a message indicating that the image is blurry and should be checked.

User Experience Enhancement

By preventing the upload of low-quality, blurry images, this solution enhances the overall user experience. Users are prompted to only upload clear, high-quality images, which maintains the visual standard of the application.


This process is highly customizable. Developers can adjust the threshold for blurriness according to the specific needs of their application. Note that, the threshold is based on your observation. For advance usage, may need ML to determine the threshold. Moreover, the integration of Python within Laravel allows for further expansion into more advanced image processing techniques, offering a flexible and robust solution for managing image quality.

Practical Application

Incorporating this functionality in your Laravel application enhances the user experience by preventing the upload of low-quality images. This is particularly useful in scenarios where image clarity is critical, such as online portfolios, product catalogs, or user profile pictures.

Customization and Flexibility

The threshold for blurriness can be adjusted according to specific needs. Additionally, the integration of Python within Laravel offers flexibility to incorporate more advanced image processing techniques if required.

Conclusion

The combination of Laravel and Python for detecting blurry images is a powerful solution. It not only ensures the visual quality of your application but also enhances the overall user experience. With this approach, developers can maintain high standards for media content, contributing to a more polished and professional online presence.


Have you tried implementing this solution in your Laravel project? Share your experiences and any insights you’ve gained in the comments below. Let’s continue to elevate the standards of web development together!

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.