Vehicletracking / app.py
sairamtelagamsetti's picture
Update app.py
9b5f83e verified
import cv2
import os
import pytesseract
import numpy as np
# Set the path to the Tesseract executable
pytesseract.pytesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" # Update this path if needed
# Haar cascade file path (absolute path)
haar_cascade_path = r"D:\seta new num board code\venv\cars.xml" # Corrected path to match the actual location
# Verify that the Haar cascade file exists
if not os.path.exists(haar_cascade_path):
print(f"Error: Haar cascade file not found at {haar_cascade_path}")
exit(1)
# Load the Haar cascade
car_cascade = cv2.CascadeClassifier(haar_cascade_path)
if car_cascade.empty():
print(f"Error: Failed to load Haar cascade from {haar_cascade_path}")
exit(1)
# Function to detect vehicles using Haar cascades
def detect_vehicles_haar(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
vehicles = car_cascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=3,
minSize=(30, 30)
)
print(f"Detected {len(vehicles)} vehicles.") # Debugging
return vehicles
# Function to extract and display number plate text
def extract_number_plate_text(vehicle_region):
# Convert the region to grayscale for better OCR accuracy
gray = cv2.cvtColor(vehicle_region, cv2.COLOR_BGR2GRAY)
# Apply thresholding to enhance the text region
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
# Debugging: Display the thresholded image
cv2.imshow("Thresholded Number Plate", thresh)
# Use Tesseract OCR to extract text
text = pytesseract.image_to_string(thresh, config='--psm 8') # PSM 8: Treat the image as a single word
text = text.strip().upper() # Clean and format the text
return text
# Main function
if __name__ == "__main__":
input_path = input("Enter the path to the image or video file: ").strip()
if not os.path.exists(input_path):
print(f"Error: The file {input_path} does not exist.")
exit(1)
try:
# Process the input file
if input_path.lower().endswith(('.png', '.jpg', '.jpeg')):
frame = cv2.imread(input_path)
if frame is None:
print(f"Error: Could not open image file {input_path}")
exit(1)
vehicles = detect_vehicles_haar(frame)
for (x, y, w, h) in vehicles:
vehicle_region = frame[y:y + h, x:x + w]
number_plate_text = extract_number_plate_text(vehicle_region)
print(f"Detected Number Plate: {number_plate_text}")
cv2.imshow("Vehicle Detection", frame)
cv2.waitKey(0)
else:
cap = cv2.VideoCapture(input_path)
if not cap.isOpened():
print(f"Error: Could not open video file {input_path}")
exit(1)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
vehicles = detect_vehicles_haar(frame)
for (x, y, w, h) in vehicles:
vehicle_region = frame[y:y + h, x:x + w]
number_plate_text = extract_number_plate_text(vehicle_region)
print(f"Detected Number Plate: {number_plate_text}")
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.imshow("Vehicle Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
except Exception as e:
print(f"An error occurred: {e}")
cv2.destroyAllWindows()