Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
from ultralytics import YOLO
|
| 5 |
+
import easyocr
|
| 6 |
+
|
| 7 |
+
# Load YOLOv8 model for license plate detection
|
| 8 |
+
model = YOLO("yolov8_weights.pt") # Replace with your trained YOLOv8 weights
|
| 9 |
+
|
| 10 |
+
# Initialize EasyOCR reader
|
| 11 |
+
reader = easyocr.Reader(['en'])
|
| 12 |
+
|
| 13 |
+
def detect_and_recognize_license_plate(image):
|
| 14 |
+
"""
|
| 15 |
+
Detects and recognizes license plates in an image.
|
| 16 |
+
"""
|
| 17 |
+
# Convert Gradio image input to OpenCV format
|
| 18 |
+
image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
| 19 |
+
|
| 20 |
+
# Detect license plates using YOLOv8
|
| 21 |
+
results = model(image)
|
| 22 |
+
license_plates = []
|
| 23 |
+
|
| 24 |
+
# Iterate through detected objects
|
| 25 |
+
for result in results:
|
| 26 |
+
for box in result.boxes:
|
| 27 |
+
# Get bounding box coordinates
|
| 28 |
+
x1, y1, x2, y2 = map(int, box.xyxy[0].tolist())
|
| 29 |
+
|
| 30 |
+
# Crop the license plate region
|
| 31 |
+
cropped_plate = image[y1:y2, x1:x2]
|
| 32 |
+
|
| 33 |
+
# Use EasyOCR to extract text from the cropped plate
|
| 34 |
+
ocr_results = reader.readtext(cropped_plate)
|
| 35 |
+
plate_text = " ".join([res[1] for res in ocr_results]) # Combine all detected text
|
| 36 |
+
|
| 37 |
+
# Draw bounding box and text on the original image
|
| 38 |
+
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
|
| 39 |
+
cv2.putText(image, plate_text, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
|
| 40 |
+
|
| 41 |
+
# Append detected text to the list
|
| 42 |
+
license_plates.append(plate_text)
|
| 43 |
+
|
| 44 |
+
# Convert the image back to RGB for Gradio display
|
| 45 |
+
output_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 46 |
+
|
| 47 |
+
# Return the output image and detected license plate text
|
| 48 |
+
return output_image, ", ".join(license_plates)
|
| 49 |
+
|
| 50 |
+
# Gradio interface
|
| 51 |
+
interface = gr.Interface(
|
| 52 |
+
fn=detect_and_recognize_license_plate,
|
| 53 |
+
inputs=gr.Image(label="Upload Image"),
|
| 54 |
+
outputs=[gr.Image(label="Detected License Plate"), gr.Textbox(label="Extracted Text")],
|
| 55 |
+
title="License Plate Detection and Recognition",
|
| 56 |
+
description="Upload an image to detect and recognize license plates."
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
# Launch the app
|
| 60 |
+
interface.launch()
|