DEV Community

Cover image for Integrating YOLO AI Predictions into a Laravel Project
Martin Tonev
Martin Tonev

Posted on • Edited on

3

Integrating YOLO AI Predictions into a Laravel Project

Integrating YOLO Predictions into a Laravel Project

Incorporating YOLO (You Only Look Once) into a Laravel project can be a powerful way to handle object detection tasks such as image analysis, counting, and classification. YOLO, a state-of-the-art object detection algorithm, works seamlessly with Python, and integrating it into a PHP-based framework like Laravel requires bridging the gap between the two languages.

This article will guide you through setting up YOLO predictions in a Laravel project, complete with code examples. We’ll build a simple system where users upload an image, YOLO processes the image to detect objects, and Laravel displays the predictions.

Contact me if you need help https://x.com/microDesignn


Prerequisites

  1. YOLO Model Setup: Ensure you have a YOLOv5/YOLOv8/YOLOv11 model trained and ready for inference.
  2. Laravel Environment: Laravel 11 installed and configured.
  3. Python Environment: Python installed with dependencies for YOLO (e.g., ultralytics for YOLOv8).
  4. Server Setup: Ensure the server can execute Python scripts using Laravel's PHP.

Workflow Overview

  1. User uploads an image through Laravel.
  2. Laravel processes the request and sends the image to a Python YOLO script.
  3. YOLO predicts the objects and returns the results to Laravel.
  4. Laravel displays the predictions.

Step 1: Setting Up Laravel

Install Laravel Project

Start by creating a new Laravel project or using an existing one:

composer create-project laravel/laravel yolo-integration
Enter fullscreen mode Exit fullscreen mode

Set up your environment variables in .env for database and file storage:

APP_NAME="YOLO Integration"
APP_ENV=local
APP_KEY=base64:...
APP_DEBUG=true
APP_URL=http://localhost

FILESYSTEM_DISK=public
Enter fullscreen mode Exit fullscreen mode

Create Routes and Controller

Define routes in routes/web.php:

use App\Http\Controllers\YOLOController;

Route::get('/', [YOLOController::class, 'index'])->name('home');
Route::post('/predict', [YOLOController::class, 'predict'])->name('predict');
Enter fullscreen mode Exit fullscreen mode

Create a YOLOController:

php artisan make:controller YOLOController
Enter fullscreen mode Exit fullscreen mode

YOLOController Implementation

Edit YOLOController.php:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class YOLOController extends Controller
{
    public function index()
    {
        return view('upload'); // Show the upload form
    }

    public function predict(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        // Store the uploaded image
        $imagePath = $request->file('image')->store('uploads', 'public');

        // Execute Python script
        $pythonScript = base_path('scripts/yolo_predict.py');
        $imageFullPath = storage_path('app/public/' . $imagePath);
        $command = escapeshellcmd("python3 $pythonScript $imageFullPath");
        $output = shell_exec($command);

        if (!$output) {
            return back()->with('error', 'Error processing image.');
        }

        // Decode the JSON response from the Python script
        $predictions = json_decode($output, true);

        return view('results', compact('predictions', 'imagePath'));
    }
}
Enter fullscreen mode Exit fullscreen mode

Create Views

  1. Upload Form (resources/views/upload.blade.php):
<!DOCTYPE html>
<html>
<head>
    <title>YOLO Object Detection</title>
</head>
<body>
    <h1>Upload an Image for YOLO Prediction</h1>
    @if(session('error'))
        <p style="color: red;">{{ session('error') }}</p>
    @endif
    <form action="{{ route('predict') }}" method="POST" enctype="multipart/form-data">
        @csrf
        <input type="file" name="image" required>
        <button type="submit">Upload and Predict</button>
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  1. Results Page (resources/views/results.blade.php):
<!DOCTYPE html>
<html>
<head>
    <title>YOLO Prediction Results</title>
</head>
<body>
    <h1>Prediction Results</h1>
    <img src="{{ asset('storage/' . $imagePath) }}" alt="Uploaded Image" width="400">
    <ul>
        @foreach($predictions as $prediction)
            <li>{{ $prediction['label'] }}: {{ $prediction['confidence'] * 100 }}%</li>
        @endforeach
    </ul>
    <a href="{{ route('home') }}">Upload Another Image</a>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 2: Setting Up YOLO Python Script

Create a Python script scripts/yolo_predict.py in your Laravel project root:

import sys
import json
from ultralytics import YOLO

def main(image_path):
    # Load YOLO model
    model = YOLO("yolov8n.pt")  # Use the appropriate model

    # Perform prediction
    results = model(image_path)

    # Parse results
    predictions = []
    for box in results[0].boxes:
        predictions.append({
            "label": box.cls,
            "confidence": box.conf.item()
        })

    # Output predictions as JSON
    print(json.dumps(predictions))

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python yolo_predict.py <image_path>")
        sys.exit(1)

    image_path = sys.argv[1]
    main(image_path)
Enter fullscreen mode Exit fullscreen mode

Install YOLO dependencies:

pip install ultralytics
Enter fullscreen mode Exit fullscreen mode

Step 3: Test the System

  1. Start Laravel:
php artisan serve
Enter fullscreen mode Exit fullscreen mode
  1. Upload an image via the form.
  2. View the prediction results.

Additional Notes

  • Security: Ensure Python scripts are sanitized and cannot execute arbitrary commands.
  • Performance: If prediction times are high, consider running YOLO in a dedicated Python server (e.g., Flask API).
  • Model Customization: Train YOLO on your dataset to improve prediction accuracy for domain-specific tasks.

This setup provides a robust framework to integrate YOLO predictions into a Laravel project, enabling real-time image analysis for web applications.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →