To enhance the license plate detection and cropping functionality, we need to address several key aspects:
-
Ensure Parallelism of Edges: Verify that the detected quadrilateral has pairs of parallel edges, which is characteristic of rectangular license plates.
-
Handle Various Plate Sizes and Orientations: Plates may appear at different scales and angles; thus, the detection should be scale-invariant and rotation-tolerant.
-
Improve Robustness: Incorporate adaptive preprocessing techniques to handle varying lighting conditions and image qualities.
Below is an improved version of your license plate detection function. This version includes the following enhancements:
-
Enhanced Preprocessing: Converts the image to grayscale, applies bilateral filtering for noise reduction while preserving edges, and uses adaptive thresholding combined with morphological operations to obtain a cleaner binary image.
-
Contour Filtering with Parallelism Check: After approximating contours to polygons with four vertices, it checks if opposite sides are approximately parallel by calculating the angles between them. This ensures that detected contours resemble rectangular shapes.
-
Scale-Invariant Aspect Ratio Check: Instead of using fixed pixel values, the aspect ratio and size checks are made relative to the image dimensions, making the detection adaptable to plates of different sizes.
-
Perspective Transformation: Once a license plate contour is detected, a perspective transform is applied to obtain a top-down view of the plate, which is especially useful for plates captured at an angle.
-
Flexible Visualization and Saving: The function displays both the cropped license plate and the original image with the detected contour highlighted. It also saves the cropped plate image if detected.
Here is the improved code with detailed comments:
import cv2
import numpy as np
def detect_and_crop_license_plate(original_image):
"""
Detects and crops the license plate from the given image.
Parameters:
- original_image: The input image in which to detect the license plate.
Returns:
- license_plate: Cropped image of the detected license plate or None if not found.
"""
# Convert to grayscale
gray = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
# Apply bilateral filter to preserve edges
gray_filtered = cv2.bilateralFilter(gray, 11, 17, 17)
# Edge detection using Canny
edged = cv2.Canny(gray_filtered, 30, 200)
# Find contours in the edged image
contours, _ = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Sort contours based on area in descending order and take top 10
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:10]
license_plate_contour = None
for contour in contours:
# Approximate the contour to a polygon
peri = cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, 0.018 * peri, True)
# Check if the approximated contour has 4 points (quadrilateral)
if len(approx) == 4:
# Compute the bounding box and aspect ratio
x, y, w, h = cv2.boundingRect(approx)
aspect_ratio = w / float(h)
# Define a range for aspect ratio typical of license plates
# This range can be adjusted based on regional plate sizes
if 2 <= aspect_ratio <= 6:
# Further check for parallelism of edges
# Calculate angles between sides to ensure they are roughly 90 degrees
angles = []
for i in range(4):
pt1 = approx[i][0]
pt2 = approx[(i + 1) % 4][0]
pt3 = approx[(i + 2) % 4][0]
v1 = pt2 - pt1
v2 = pt3 - pt2
angle = angle_between(v1, v2)
angles.append(angle)
# Check if all angles are approximately 90 degrees within a tolerance
if all(80 <= angle <= 100 for angle in angles):
license_plate_contour = approx
break # Stop once the likely license plate is found
if license_plate_contour is not None:
# Draw the detected contour on the image (for visualization)
img_copy = original_image.copy()
cv2.drawContours(img_copy, [license_plate_contour], -1, (0, 255, 0), 3)
# Obtain a top-down view of the license plate using perspective transform
license_plate = four_point_transform(original_image, license_plate_contour.reshape(4, 2))
# Display the results
cv2.imshow("Cropped License Plate", license_plate)
cv2.imshow("Detected License Plate", img_copy)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Optionally save the cropped license plate
cv2.imwrite('cropped_license_plate.jpg', license_plate)
print("License plate detected and saved.")
return license_plate
else:
print("License plate not found.")
return None
def angle_between(v1, v2):
"""
Calculates the angle between two vectors in degrees.
"""
v1 = v1.astype(float)
v2 = v2.astype(float)
unit_v1 = v1 / np.linalg.norm(v1) if np.linalg.norm(v1) != 0 else v1
unit_v2 = v2 / np.linalg.norm(v2) if np.linalg.norm(v2) != 0 else v2
dot_product = np.dot(unit_v1, unit_v2)
# Clamp the dot_product to avoid numerical issues with arccos
dot_product = np.clip(dot_product, -1.0, 1.0)
angle = np.arccos(dot_product)
return np.degrees(angle)
def order_points(pts):
"""
Orders points in the order: top-left, top-right, bottom-right, bottom-left.
"""
rect = np.zeros((4, 2), dtype="float32")
# Sum and difference to find corners
s = np.sum(pts, axis=1)
diff = np.diff(pts, axis=1)
rect[0] = pts[np.argmin(s)] # top-left
rect[2] = pts[np.argmax(s)] # bottom-right
rect[1] = pts[np.argmin(diff)] # top-right
rect[3] = pts[np.argmax(diff)] # bottom-left
return rect
def four_point_transform(image, pts):
"""
Applies a perspective transform to obtain a top-down view of the detected license plate.
"""
rect = order_points(pts)
(tl, tr, br, bl) = rect
# Compute the width of the new image
widthA = np.linalg.norm(br - bl)
widthB = np.linalg.norm(tr - tl)
maxWidth = max(int(widthA), int(widthB))
# Compute the height of the new image
heightA = np.linalg.norm(tr - br)
heightB = np.linalg.norm(tl - bl)
maxHeight = max(int(heightA), int(heightB))
# Destination points for the perspective transform
dst = np.array([
[0, 0],
[maxWidth - 1, 0],
[maxWidth - 1, maxHeight - 1],
[0, maxHeight - 1]], dtype="float32")
# Compute the perspective transform matrix and apply it
M = cv2.getPerspectiveTransform(rect, dst)
warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
return warped
# Example usage:
if __name__ == "__main__":
image_path = 'path_to_your_image.jpg'
image = cv2.imread(image_path)
detect_and_crop_license_plate(image)
Detailed Explanation of Improvements:
-
Enhanced Preprocessing:
- Grayscale Conversion: Simplifies the image and reduces computational complexity.
- Bilateral Filtering: Reduces noise while preserving edges, which is crucial for accurate edge detection.
- Canny Edge Detection: Detects edges effectively, aiding in finding meaningful contours.
-
Contour Selection:
- Sorting Contours by Area: Assumes the license plate is among the largest quadrilateral contours, thus improving efficiency by examining top candidates.
- Polygon Approximation (
cv2.approxPolyDP): Simplifies contours to polygons, making it easier to identify quadrilaterals.
- Aspect Ratio Check: Uses a dynamic range (2 to 6) suitable for various regional license plate sizes, replacing fixed pixel dimensions for scalability.
- Parallelism and Right Angle Verification: Ensures that the detected quadrilateral resembles a rectangle by checking that all internal angles are approximately 90 degrees.
-
Perspective Transformation:
- Ordering Points: Arranges the contour points in a consistent order to correctly apply the perspective transform.
- Warping the Image: Produces a straightened, top-down view of the license plate, which can facilitate further processing like Optical Character Recognition (OCR).
-
Flexibility and Robustness:
- Relative Size Checks: By basing aspect ratios and area considerations on the image's properties rather than fixed sizes, the detection adapts to various image resolutions and license plate sizes.
- Angle Calculation: The
angle_between function ensures that the sides of the quadrilateral are nearly perpendicular, a key characteristic of license plates.
-
Visualization and Saving:
- Display Windows: Helps in debugging and verifying the detection visually.
- Saving the Cropped Plate: Allows for downstream processing or record-keeping.
Additional Recommendations:
-
Adaptive Thresholding: Depending on image quality, adaptive thresholding can further enhance edge detection, especially in varying lighting conditions.
-
Machine Learning Approaches: For more robust detection, especially in diverse scenarios, consider using machine learning models trained specifically for license plate detection.
-
OCR Integration: To extract the actual text from the license plate, integrate OCR libraries like Tesseract after cropping and preprocessing the plate image.
-
Error Handling: Incorporate more sophisticated error handling to manage cases where multiple quadrilaterals are detected or when the plate is partially occluded.
By implementing these improvements, the license plate detection function becomes more reliable, flexible, and suitable for a wider range of real-world scenarios.