0% found this document useful (0 votes)
46 views2 pages

Image To Text1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views2 pages

Image To Text1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import cv2

import imutils
import pytesseract

# Initialize camera
camera = cv2.VideoCapture(0) # Use 0 for default camera, change if you have
multiple cameras

# Function to process frame


def process_frame(frame):
# Resize frame to improve processing speed (optional)
frame = imutils.resize(frame, width=500)

# Convert frame to grayscale


gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# Apply Gaussian blur to reduce noise


blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# Perform edge detection using Canny


edged = cv2.Canny(blurred, 100, 200)

# Find contours in the edged image


contours = cv2.findContours(edged.copy(), cv2.RETR_LIST,
cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(contours)

# Sort contours by area and keep the largest one


contours = sorted(contours, key=cv2.contourArea, reverse=True)[:5]

# Loop over the contours


for contour in contours:
# Approximate the contour
perimeter = cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, 0.02 * perimeter, True)

# If the contour has 4 vertices, it may be a license plate


if len(approx) == 4:
license_plate = approx
break

# Draw the license plate contour on the frame


cv2.drawContours(frame, [license_plate], -1, (0, 255, 0), 2)

# Extract the license plate region using the contours


x, y, w, h = cv2.boundingRect(license_plate)
plate_region = gray[y:y + h, x:x + w]

# Use Tesseract OCR to extract text from the license plate region
plate_text = pytesseract.image_to_string(plate_region, config='--psm 8')

# Print the extracted license plate text


print("Detected License Plate:", plate_text.strip())

# Display the frame with detected license plate contour


cv2.imshow("License Plate Detection", frame)

# Loop to continuously capture frames from the camera


while True:
# Capture frame-by-frame
ret, frame = camera.read()

# Check if frame is captured successfully


if not ret:
print("Failed to capture frame")
break

# Process the captured frame


process_frame(frame)

# Break the loop if 'q' is pressed


if cv2.waitKey(1) & 0xFF == ord('q'):
break

# Release the camera and close all OpenCV windows


camera.release()
cv2.destroyAllWindows()

Python (3.5+)
OpenCV (pip install opencv-python)
imutils (pip install imutils)
pytesseract (pip install pytesseract)

You might also like