Laravelでのぼやけた画像の検出

Susan Sarandon
リリース: 2024-10-06 14:10:29
オリジナル
328 人が閲覧しました

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


ログイン後にコピー

Install OpenCV using PIP


pip3 install opencv-python


ログイン後にコピー

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


<p>sudo mkdir /var/www/.local<br>
sudo mkdir /var/www/.cache<br>
sudo chown www-data.www-data /var/www/.local<br>
sudo chown www-data.www-data /var/www/.cache<br>
sudo -H -u www-data pip3 install opencv-python</p>

ログイン後にコピー




Create Python Script



<p>import sys<br>
import cv2</p>

<p>def get_image_laplacian_value(image_path):<br>
    image = cv2.imread(image_path)<br>
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)<br>
    return cv2.Laplacian(gray_image, cv2.CV_64F).var()</p>

<p>if <strong>name</strong> == "<strong>main</strong>":<br>
    if len(sys.argv) != 2:<br>
        sys.exit(1)<br>
    image_path = sys.argv[1]<br>
    laplacian_value = get_image_laplacian_value(image_path)<br>
    print(laplacian_value)</p>

ログイン後にコピー




Create Laravel Rule:



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

ログイン後にコピー




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.


このプロセスは高度にカスタマイズ可能です。開発者は、アプリケーションの特定のニーズに応じて、ぼやけのしきい値を調整できます。しきい値は観察に基づいていることに注意してください。事前に使用するには、しきい値を決定するために ML が必要になる場合があります。さらに、Laravel 内での Python の統合により、より高度な画像処理技術へのさらなる拡張が可能になり、画像品質を管理するための柔軟で堅牢なソリューションが提供されます。

実用化

この機能を Laravel アプリケーションに組み込むと、低品質の画像のアップロードが防止され、ユーザー エクスペリエンスが向上します。これは、オンライン ポートフォリオ、製品カタログ、ユーザー プロフィール写真など、画像の鮮明さが重要なシナリオで特に役立ちます。

カスタマイズと柔軟性

ぼやけのしきい値は、特定のニーズに応じて調整できます。さらに、Laravel 内での Python の統合により、必要に応じてより高度な画像処理技術を組み込むことができる柔軟性が得られます。

結論

ぼやけた画像を検出するための Laravel と Python の組み合わせは、強力なソリューションです。これにより、アプリケーションの視覚的な品質が保証されるだけでなく、全体的なユーザー エクスペリエンスも向上します。このアプローチにより、開発者はメディア コンテンツの高い基準を維持し、より洗練されたプロフェッショナルなオンライン プレゼンスに貢献できます。


このソリューションを Laravel プロジェクトに実装してみましたか?あなたの経験や得た洞察を以下のコメント欄で共有してください。これからも一緒に Web 開発の基準を高めていきましょう!

以上がLaravelでのぼやけた画像の検出の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!