Spaces:
Runtime error
Runtime error
File size: 1,927 Bytes
10bcc8b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
import cv2
import imghdr
import pytesseract
def extract_number_plate(image_path):
# Load the image
image = cv2.imread(image_path)
# Check if the image is valid
if image is None:
print("Invalid image file!")
return
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply Gaussian blur to reduce noise
blurred = cv2.GaussianBlur(gray, (7, 7), 0)
# Perform edge detection using Canny algorithm
edges = cv2.Canny(blurred, 30, 150)
# Find contours in the edge-detected image
contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Filter contours based on area to select potential number plates
number_plate_contours = []
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
area = cv2.contourArea(contour)
if area > 1000 and w > h:
number_plate_contours.append(contour)
# Draw bounding rectangles around the number plates
for contour in number_plate_contours:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Extract the region of interest (number plate)
plate = gray[y:y+h, x:x+w]
# Apply OCR to the number plate region
plate_text = pytesseract.image_to_string(plate, config='--psm 7')
# Print the extracted text
print("Number Plate Text:", plate_text)
# Display the image with bounding rectangles
cv2.imshow("Number Plates", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Path to the input image
image_path = "cars/car2.jpg"
# Check if the file is an image
if imghdr.what(image_path) is not None:
# Extract the number plates and print the text
extract_number_plate(image_path)
else:
print("Invalid image file format!")
|