Here is a very basic python script I have been playing with to get you started. It saves the license plate numbers to a csv file. I'm using a Raspberry Pi 5 to run this but to run properly, a more powerful Linux machine will be required.
Install these libraries first:
pip install opencv-python-headless pytesseract imutils
sudo apt-get install tesseract-ocr
pip install openalpr
The script:
import cv2
import pytesseract
import csv
import time
# Initialize the CSV file
csv_filename = "license_plates.csv"
with open(csv_filename, mode='w') as file:
writer = csv.writer(file)
writer.writerow(["Date", "Time", "License Plate"])
# RTSP Stream URL
rtsp_url = "rtsp:/your_rtsp_stream"
# Start capturing from the RTSP stream
cap = cv2.VideoCapture(rtsp_url)
if not cap.isOpened():
print("Error: Could not open RTSP stream.")
exit()
# Function to detect and extract license plates
def detect_license_plate(frame):
# Convert frame to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Use pytesseract to detect text
license_plate_text = pytesseract.image_to_string(gray, config='--psm 8')
return license_plate_text.strip()
while True:
ret, frame = cap.read()
if not ret:
print("Failed to grab frame")
break
# Detect license plate
license_plate = detect_license_plate(frame)
# If a license plate is detected, write it to the CSV
if license_plate:
date = time.strftime("%Y-%m-%d")
current_time = time.strftime("%H:%M:%S")
with open(csv_filename, mode='a') as file:
writer = csv.writer(file)
writer.writerow([date, current_time, license_plate])
print(f"License Plate Detected: {license_plate} on {date} at {current_time}")
# Show the frame (optional)
cv2.imshow('RTSP Stream', frame)
# Exit on 'q' key
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release the video capture and close all OpenCV windows
cap.release()
cv2.destroyAllWindows()