Created
February 24, 2024 14:23
-
-
Save Calvindd2f/88e5b3ff7fa8027b938c30e9d501b6bb to your computer and use it in GitHub Desktop.
This code can be used for legitimate purposes such as improving the accuracy of ANPR systems or developing vision-based transportation applications. This code detects license plates by applying Gaussian blur, edge detection, dilation, and erosion to the input image. It then finds contours in the edge map and filters out the ones that have an asp…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import cv2 | |
| # Example code that detects license plates in an image: | |
| # Load the image and convert it to grayscale | |
| image = cv2.imread('license_plate.jpg') | |
| gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
| # Apply Gaussian blur to the grayscale image | |
| gray = cv2.GaussianBlur(gray, (5, 5), 0) | |
| # Apply edge detection to the grayscale image | |
| edges = cv2.Canny(gray, 50, 150, apertureSize=3) | |
| # Apply a dilation and erosion to the edge map to close gaps in between object edges | |
| dilated = cv2.dilate(edges, None, iterations=2) | |
| eroded = cv2.erode(dilated, None, iterations=1) | |
| # Find contours in the edge map | |
| contours, _ = cv2.findContours(eroded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
| # Initialize an empty list to store the license plate contours | |
| license_plate_contours = [] | |
| # Loop over the contours | |
| for contour in contours: | |
| # Compute the bounding box of the contour | |
| (x, y, w, h) = cv2.boundingRect(contour) | |
| # Compute the aspect ratio of the bounding box | |
| aspect_ratio = w / float(h) | |
| # Check if the aspect ratio is within the expected range for license plates | |
| if aspect_ratio >= 2.5 and aspect_ratio <= 3.5: | |
| license_plate_contours.append(contour) | |
| # Draw the license plate contours on the image | |
| for contour in license_plate_contours: | |
| (x, y, w, h) = cv2.boundingRect(contour) | |
| cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) | |
| # Show the image with the detected license plates | |
| cv2.imshow("License Plates", image) | |
| cv2.waitKey(0) | |
| cv2.destroyAllWindows() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment