Sitemap

Python Project: License Plate Detection Using YOLOv8

4 min readMar 22, 2025

--

🚀 Introduction

License plate detection is an essential technology in traffic monitoring, toll collection, and security systems. In this blog, we will walk through how to use YOLOv8 (You Only Look Once) to detect license plates in images and videos. This guide is designed for beginners, so you can follow along even if you’re new to deep learning! 🔥

Press enter or click to view image in full size

Dataset: https://www.kaggle.com/datasets/ronakgohil/license-plate-dataset

🛠️ Step 1: Install Required Libraries

Before we start, let’s install the necessary Python libraries:

pip install ultralytics opencv-python matplotlib requests numpy

These libraries will help us work with YOLO, process images and videos, and visualize results. 🎯

📌 Step 2: Training YOLOv8 on License Plate Dataset

First, we need to train the YOLOv8 model on a dataset containing images of license plates.

from ultralytics import YOLO

# Load YOLOv8 model
model = YOLO("yolov8n.pt") # Using the small YOLOv8 model

# Train model on your dataset
model.train(data="license-plate-dataset/dataset.yaml", epochs=50, imgsz=640)

Here’s what this code does:

  • Loads a pretrained YOLOv8 model.
  • Trains it on a custom dataset for 50 epochs.
  • Uses an image size of 640x640 pixels for better accuracy.

Once the training is complete, YOLO will save the best model weights in “runs/detect/train/weights/best.pt”. 🎯

📷 Step 3: License Plate Detection from an Image URL

Let’s build a system where you can paste an image URL, and the model will detect the license plate!

import cv2
import matplotlib.pyplot as plt
import requests
import numpy as np
from ultralytics import YOLO
# Load trained model
model = YOLO("runs/detect/train/weights/best.pt") # Path to best trained model
# Function to download image from URL
def download_image(image_url):
response = requests.get(image_url)
if response.status_code == 200:
image_array = np.asarray(bytearray(response.content), dtype=np.uint8)
return cv2.imdecode(image_array, cv2.IMREAD_COLOR) # Convert to OpenCV image
else:
print("❌ Failed to download image.")
return None
# Function to detect license plate in an image
def detect_license_plate(image):
results = model(image) # Run YOLOv8 detection
for box in results[0].boxes: # Process first (and only) result
x1, y1, x2, y2 = map(int, box.xyxy[0]) # Bounding box coordinates
plate_image = image[y1:y2, x1:x2] # Crop the plate region
# Display the detected license plate
plt.imshow(cv2.cvtColor(plate_image, cv2.COLOR_BGR2RGB))
plt.axis("off")
plt.show()
return plate_image # Return cropped plate image
return None # If no plate is found
# 🔹 Get Image URL from User
image_url = input("🔗 Enter image URL: ")
# 🔹 Process Image
image = download_image(image_url)
if image is not None:
detected_plate = detect_license_plate(image)
if detected_plate is not None:
print("✅ License plate detected!")
else:
print("❌ No plate detected.")
else:
print("❌ Could not process image.")

🔥 How it Works:

  1. The program downloads an image from the provided URL.
  2. It runs the YOLOv8 model to detect license plates.
  3. If a plate is detected, it crops and displays the detected license plate.
  4. The program prints a success or failure message.

🎥 Step 4: License Plate Detection in Videos

What if we want to detect license plates frame-by-frame in a video? Let’s modify our code for that! 📹

import cv2
import time
from ultralytics import YOLO
# Load trained YOLO model
model = YOLO("runs/detect/train/weights/best.pt") # Path to best trained model
# Load video
video_path = "test_video.mp4" # Change to your video file
cap = cv2.VideoCapture(video_path)
# Check if video opened successfully
if not cap.isOpened():
print("❌ Error: Could not open video.")
exit()
# Get video frame rate for FPS calculation
fps = cap.get(cv2.CAP_PROP_FPS)
print(f"🎥 Video FPS: {fps:.2f}")
# Process video frame-by-frame
while cap.isOpened():
start_time = time.time() # Track processing time
ret, frame = cap.read()
if not ret:
print("🔴 End of video or error reading frame.")
break
# Run YOLOv8 detection
results = model(frame)
# Draw bounding boxes for detected license plates
for result in results:
for box in result.boxes:
x1, y1, x2, y2 = map(int, box.xyxy[0]) # Bounding box coordinates
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 3) # Green box
cv2.putText(frame, "License Plate", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
# Show the output frame
cv2.imshow("🚗 License Plate Detection", frame)
# Press 'q' to exit
if cv2.waitKey(1) & 0xFF == ord("q"):
break
# Release resources
cap.release()
cv2.destroyAllWindows()
print("✅ Video processing complete!")

🎬 How it Works:

  1. Loads the trained YOLOv8 model.
  2. Reads the video file frame by frame.
  3. Detects license plates and draws bounding boxes.
  4. Displays the video in real time with detections.
  5. Press ‘q’ to exit the video.

🔥 Conclusion

By following this guide, you’ve learned how to:

Get Abhishek Shaw’s stories in your inbox

Join Medium for free to get updates from this writer.

✅ Train a YOLOv8 model for license plate detection.

✅ Detect license plates from image URLs.

✅ Process and detect plates in videos.

Now, you can build automated traffic monitoring systems, smart parking solutions, or law enforcement tools using this model! 🚗💨

Want more features like OCR for reading plate numbers? Let me know in the comments! 👇

--

--

Abhishek Shaw
Abhishek Shaw

Written by Abhishek Shaw

Hello, I'm Abhishek Shaw. - Pursuing MBA in Business Analytics and Data Science(2023-25) 🔍 Key Skills: - MS Office , Power BI, Python, SQL, Tableau, UI Path