Automatic Number Plate Recognition (ANPR) is a computer vision application that detects and reads vehicle license plates. Using OpenCV, we can identify plates with techniques such as edge detection, contour detection, and character segmentation.
Convert the image to grayscale, reduce noise, and apply edge detection to highlight potential number plate regions.
import cv2
# Load image
img = cv2.imread("car.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Noise reduction
blur = cv2.bilateralFilter(gray, 11, 17, 17)
# Edge detection
edges = cv2.Canny(blur, 30, 200)
cv2.imshow("Edges", edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
Detect contours and filter by shape to locate rectangular areas that could be number plates.
contours, _ = cv2.findContours(edges.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:10]
for c in contours:
approx = cv2.approxPolyDP(c, 0.018 * cv2.arcLength(c, True), True)
if len(approx) == 4: # Plate is usually rectangular
x, y, w, h = cv2.boundingRect(approx)
plate = img[y:y+h, x:x+w]
cv2.imshow("Number Plate", plate)
break
cv2.waitKey(0)
cv2.destroyAllWindows()
Once the plate is detected, Optical Character Recognition (OCR) tools like Tesseract can extract characters. This step goes beyond OpenCV and integrates OCR.
import pytesseract
# Convert plate to grayscale & threshold
plate_gray = cv2.cvtColor(plate, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(plate_gray, 150, 255, cv2.THRESH_BINARY)
# OCR
text = pytesseract.image_to_string(thresh, config="--psm 8")
print("Detected Number Plate:", text)
✅ In this lesson, you learned the basics of Automatic Number Plate Recognition (ANPR) using OpenCV.
We applied preprocessing, contour detection, and OCR to detect and read vehicle license plates.
👉 Next, we will explore Face Mask Detection using Deep Learning & OpenCV.
