top of page

Lane Detection Web Application Using Django: Step-by-Step Tutorial

In this tutorial, I will guide you through the process of creating a Lane Detection web application using Django. This application will allow users to upload videos or images, process them using a pre-trained machine learning model for lane detection, and return the processed results.


This project combines the power of Django, OpenCV, PyTorch, and pre-trained deep learning models. It is beginner-friendly and suitable for students who want to learn how to integrate a machine learning model into a Django web app.


Prerequisites

  • Python 3.x installed on your system.

  • Basic understanding of Python and Django.

  • Basic understanding of machine learning concepts and how models work.

  • Familiarity with HTML and CSS.


Steps Overview:

  1. Set up the Django environment.

  2. Create a new Django project.

  3. Create a new Django app within the project.

  4. Set up templates and static files for the frontend.

  5. Implement lane detection logic using OpenCV and PyTorch.

  6. Handle media files (images or videos).

  7. Integrate the lane detection model into Django views.

  8. Run the server and test the web application.


Let’s dive into each step in detail.


Step 1: Set Up the Django Environment

Before starting the project, we need to set up a working environment for our Django project. Follow the steps below:


1 Create a project directory and set the path:

mkdir lane_detection_project
cd lane_detection_project

2. Create a virtual environment using the following command:

python -m venv env

Activate the virtual environment:

  • On Windows:

env\Scripts\activate
  • On macOS/Linux:

source env/bin/activate

4. Install Django using pip:

pip install django

Step 2: Create a New Django Project

Once the environment is set up, we can start a new Django project. Use the following command to create a new project:

django-admin startproject lane_detection

This will create a lane_detection folder with essential files such as settings.py, urls.py, and others. Let’s move to the next step.


Step 3: Create a Django App for Lane Detection

Within our Django project, we will create a Django app that will handle all the lane detection functionalities. Run the following command to create the app:

python manage.py startapp lane_detection_app

Now, we will link the app to the Django project.

  1. Open the settings.py file inside the lane_detection folder and add lane_detection_app to the INSTALLED_APPS list:

INSTALLED_APPS = [
    'lane_detection_app',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

2. Ensure you also set the correct paths for the STATIC and TEMPLATES directories in settings.py:

STATIC_URL = 'lane_detection_app/static/'
STATIC_ROOT = f'{BASE_DIR}/lane_detection_app/static'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [f"{BASE_DIR}/lane_detection_app/templates/"],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Step 4: Set Up Frontend Templates (HTML Files)

Django uses templates to render the HTML content. Let’s create two HTML templates: one for the homepage and one for displaying the lane detection results.

  1. Inside the lane_detection_app folder, create a templates folder.

  2. Inside the templates folder, create index.html and predict.html.

Here’s the code for index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lane Detection</title>
    {% load static %}
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h1 class="text-center mt-5 mb-4">Welcome to the Lane Detection App</h1>
        <div class="d-flex justify-content-center">
            <form method="post" action="/predict" enctype="multipart/form-data" class="text-center">
                {% csrf_token %}
                <div class="mb-3">
                    <input type="file" class="form-control" name="media" accept="image/*,video/*" id="media">
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div>
    </div>
</body>
</html>

The index.html allows users to upload an image or video for lane detection.

Here’s the code for predict.html (this page will show the processed results):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lane Detection Result</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f8f9fa;
        }
        h1 {
            text-align: center;
            margin-top: 50px;
            color: #4a4a4a;
        }
        .download-container {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }
        .download-btn {
            background-color: #007bff;
            color: white;
            padding: 12px 20px;
            font-size: 18px;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Your lane detection result is ready!</h1>
    <div class="download-container">
        <a href="{{ file_url }}" class="download-btn" download>Download Result</a>
    </div>
</body>
</html>

This predict.html page displays a link to download the processed image or video.


Step 5: Implement Lane Detection Logic

For lane detection, we will use a machine learning model built with PyTorch. This section involves handling the uploaded media (images or videos) and performing lane detection.

Here’s the structure of the lane_detection_app folder:


  • lane_handling.py: Handles the media files (videos or images) and performs lane detection.

  • ml_utils.py: Contains utilities for the machine learning model.

  • views.py: Handles the user requests and integrates the lane detection logic.


lane_handling.py

This file will handle the media uploaded by users and process it using the model.

import cv2
import numpy as np
import torch
import os
from django.conf import settings
from .ml_utils import GrayToRGBModel, process_frame

def handle_uploaded_video(uploaded_file):
    video_name = uploaded_file.name
    video_path = os.path.join(settings.STATIC_ROOT, video_name)

    with open(video_path, 'wb') as video_file:
        for chunk in uploaded_file.chunks():
            video_file.write(chunk)

    return video_path

def lane_detection(uploaded_file, file_type):
    model = GrayToRGBModel(num_classes=2).cuda()
    model.load_state_dict(torch.load(os.path.join(settings.STATIC_ROOT, "deeplabv3_tusimple.pth")))
    model.eval()
    
    if file_type == 'video':
        video_path = handle_uploaded_video(uploaded_file)
        video = cv2.VideoCapture(video_path)
        width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
        fps = int(video.get(cv2.CAP_PROP_FPS)) 

        video_name, ext = os.path.splitext(video_path)
        output_video_path = os.path.join(settings.STATIC_ROOT, f"{video_name}_solution{ext}")
        fourcc = cv2.VideoWriter_fourcc(*"mp4v")
        out = cv2.VideoWriter(output_video_path, fourcc, fps, (width, height))

        while video.isOpened():
            ret, frame = video.read()
            if not ret:
                break
            processed_frame = process_frame(frame, model)
            out.write(processed_frame)

        video.release()
        out.release()
        cv2.destroyAllWindows()

        return output_video_path
    
    elif file_type == 'image':
        image_name = uploaded_file.name
        image_path = os.path.join(settings.STATIC_ROOT, image_name)

        file_data = uploaded_file.read()
        nparr = np.frombuffer(file_data, np.uint8)
        image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

        processed_image = process_frame(image, model)
        output_image_path = os.path.join(settings.STATIC_ROOT, f"{image_name}_solution.png")
        cv2.imwrite(output_image_path, processed_image)

        return output_image_path

ml_utils.py

This file defines the lane detection model using PyTorch.

import torch
import torch.nn as nn
from torchvision.models.segmentation import deeplabv3_resnet50
import cv2
import numpy as np

class GrayToRGBModel(nn.Module):
    def __init__(self, pretrained=True, num_classes=2):
        super(GrayToRGBModel, self).__init__()
        self.gray_to_rgb = nn.Conv2d(1, 3, kernel_size=1, stride=1, padding=0)
        self.deeplab = deeplabv3_resnet50(pretrained=True)
        self.deeplab.classifier[4] = nn.Conv2d(256, num_classes, kernel_size=1)

    def forward(self, x):
        x = self.gray_to_rgb(x)
        return self.deeplab(x)

def process_frame(frame, model, size=(512, 256)):
    image_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    image_gray_resized = cv2.resize(image_gray, size)
    image_tensor = torch.from_numpy(image_gray_resized).unsqueeze(0).unsqueeze(0).float().cuda()

    with torch.no_grad():
        output = model(image_tensor)["out"]
        segmentation = output.argmax(1).cpu().numpy()[0]

    mask = segmentation > 0
    frame[mask] = [0, 255, 0]  # Color the lanes in green

    return frame

Step 6: Set Up Django Views and URL Routing

We will now create the necessary views to handle user requests.

  1. views.py: Handles the file uploads and processes the lane detection.

from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings
from .lane_handling import lane_detection
import os

def index(request):
    return render(request, "index.html")

def predict(request):
    if request.method == 'POST':
        uploaded_file = request.FILES['media']
        if uploaded_file.content_type.startswith('image/'):
            output_path = lane_detection(uploaded_file, "image")
        elif uploaded_file.content_type.startswith('video/'):
            output_path = lane_detection(uploaded_file, "video")
        else:
            return HttpResponse("Invalid file format. Please upload an image or video.")
        
        file_url = os.path.relpath(output_path, settings.STATIC_ROOT)
        return render(request, 'predict.html', {'file_url': os.path.join(settings.STATIC_URL, file_url)})
    return HttpResponse("Error: Please upload a valid file.")

2. urls.py: Routes the URLs to the corresponding views.

from django.urls import path
from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("predict", views.predict, name="predict")
]

Step 7: Run the Server

Now, all the setup is done! To run the server, first apply the migrations:

python manage.py migrate

Then, run the Django development server:

python manage.py runserver

Visit http://127.0.0.1:8000/ in your browser, and you should see the Lane Detection web app. You can now upload images or videos, and the application will process the file and return the lane detection result.


Project Demo Video




If you require any assistance with this project or Machine Learning projects, please do not hesitate to contact us. We have a team of experienced developers who specialize in Machine Learning and can provide you with the necessary support and expertise to ensure the success of your project. You can reach us through our website or by contacting us directly via email or phone.



Comments


bottom of page