Spaces:
Runtime error
Runtime error
| 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!") | |