Lesson 5 of 12
Licence Plate Reader
Combine edge detection, contour analysis, and OCR to build a licence plate reader.
Licence Plate Detection and OCR
Licence Plate Detection and OCR
import cv2
import numpy as np
import pytesseract
class LicensePlateReader:
"""
Detects and reads licence plates using edge detection, contour
analysis, and Tesseract OCR.
"""
def preprocess_for_plate_detection(self, image):
"""Prepare image to highlight the licence plate region."""
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.bilateralFilter(gray, 11, 17, 17)
edges = cv2.Canny(blurred, 30, 200)
return edges, gray
def find_plate_contour(self, edges, image):
"""Find the contour most likely to be a licence plate."""
contours, _ = cv2.findContours(
edges.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
)
# Sort by area — licence plate is large
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:15]
plate_contour = None
for contour in contours:
peri = cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, 0.018 * peri, True)
# Licence plates are approximately rectangular (4 corners)
if len(approx) == 4:
x, y, w, h = cv2.boundingRect(approx)
aspect_ratio = w / float(h)
# Typical licence plate: 2:1 to 5:1 aspect ratio
if 2 < aspect_ratio < 6:
plate_contour = approx
break
return plate_contour
def extract_and_read_plate(self, image_path):
"""Full pipeline: detect plate → extract → OCR → return text."""
image = cv2.imread(image_path)
if image is None:
return None, "Could not load image"
edges, gray = self.preprocess_for_plate_detection(image)
plate_contour = self.find_plate_contour(edges, image)
if plate_contour is None:
return None, "No plate found"
# Draw plate outline
result = image.copy()
cv2.drawContours(result, [plate_contour], -1, (0, 255, 0), 3)
# Crop the plate region
x, y, w, h = cv2.boundingRect(plate_contour)
plate_img = gray[y:y+h, x:x+w]
# Enhance for OCR
plate_img = cv2.resize(plate_img, None, fx=3, fy=3,
interpolation=cv2.INTER_CUBIC)
_, plate_binary = cv2.threshold(
plate_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU
)
# OCR with plate-specific config
text = pytesseract.image_to_string(
plate_binary,
config="--psm 7 --oem 1 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
).strip()
# Clean text
cleaned = "".join(c for c in text if c.isalnum())
print(f"=== Licence Plate Reader ===")
print(f"Plate region: ({x},{y}) size {w}x{h}")
print(f"Raw OCR text: '{text}'")
print(f"Cleaned text: '{cleaned}'")
cv2.imwrite("plate_detected.jpg", result)
cv2.imwrite("plate_crop.jpg", plate_binary)
return cleaned, result
reader = LicensePlateReader()
plate_text, annotated = reader.extract_and_read_plate("car_photo.jpg")
if plate_text:
print(f"\nDetected plate: {plate_text}")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment
Finished this lesson?
0 of 12 in Module 12