-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindplate.py
More file actions
71 lines (54 loc) · 2.27 KB
/
Copy pathfindplate.py
File metadata and controls
71 lines (54 loc) · 2.27 KB
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
63
64
65
66
67
68
69
70
71
import cv2
import numpy as np
def find_and_crop_plate(image):
# Convert image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply bilateral filtering to reduce noise while preserving edges
gray = cv2.bilateralFilter(gray, 11, 17, 17)
cv2.imshow("Original Image", gray)
cv2.waitKey(0)
# Apply adaptive thresholding to isolate plate characters
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 2)
# Find contours in the thresholded image
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Find the largest contour (assuming it's the license plate)
largest_contour = None
largest_area = 0
for cnt in contours:
area = cv2.contourArea(cnt)
if area > largest_area:
largest_contour = cnt
largest_area = area
# Check if a contour is found
if largest_contour is None:
return image, None # No plate detected
# Approximate the contour to a rectangle
peri = cv2.arcLength(largest_contour, True)
approx = cv2.approxPolyDP(largest_contour, 0.02 * peri, True)
# Ensure the contour has 4 corners (rectangle)
if len(approx) != 4:
return image, None # Not a rectangular plate
# Extract corner points from the approximated polygon
corners = approx.reshape(4, 2)
# Sort the corners based on their y-coordinates
top_left, bottom_left, bottom_right, top_right = corners[corners[:, 1].argsort()]
# Calculate the width and height of the plate based on sorted corners
w = int(np.sqrt((bottom_right[0] - bottom_left[0])**2 + (bottom_right[1] - bottom_left[1])**2))
h = int(np.sqrt((top_right[0] - top_left[0])**2 + (top_right[1] - top_left[1])**2))
# Define the ROI (region of interest) for the cropped plate
x = int(bottom_left[0])
y = int(top_left[1])
cropped_plate = image[y:y+h, x:x+w]
return image, cropped_plate
# Load the car image
image = cv2.imread("carplate.jpg")
# Attempt to find and crop the license plate
original_image, cropped_plate = find_and_crop_plate(image.copy())
if cropped_plate is None:
print("No license plate detected.")
else:
# Display the original image and cropped plate
cv2.imshow("Original Image", original_image)
cv2.imshow("Cropped License Plate", cropped_plate)
cv2.waitKey(0)
cv2.destroyAllWindows()