Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
import gradio as gr
|
5 |
+
from ultralytics import YOLO
|
6 |
+
import easyocr
|
7 |
+
|
8 |
+
# Load YOLOv8 model
|
9 |
+
model_path = "YOLOv8n.pt" # Local path in repo
|
10 |
+
yolo_model = YOLO(model_path)
|
11 |
+
|
12 |
+
# Initialize EasyOCR
|
13 |
+
easyocr_reader = easyocr.Reader(['en'], gpu=False)
|
14 |
+
|
15 |
+
def detect_and_read_plate(image_np):
|
16 |
+
results = yolo_model.predict(source=image_np, conf=0.25)
|
17 |
+
boxes = results[0].boxes.xyxy.cpu().numpy().astype(int)
|
18 |
+
|
19 |
+
annotated_image = image_np.copy()
|
20 |
+
detected_texts = []
|
21 |
+
|
22 |
+
for i, box in enumerate(boxes):
|
23 |
+
x1, y1, x2, y2 = box[:4]
|
24 |
+
cropped_plate = image_np[y1:y2, x1:x2]
|
25 |
+
text_results = easyocr_reader.readtext(cropped_plate)
|
26 |
+
|
27 |
+
plate_texts = []
|
28 |
+
for (bbox, text, conf) in text_results:
|
29 |
+
if conf > 0.3:
|
30 |
+
plate_texts.append(text)
|
31 |
+
|
32 |
+
plate_text = ' '.join(plate_texts)
|
33 |
+
detected_texts.append(f"Plate {i+1}: {plate_text}")
|
34 |
+
|
35 |
+
cv2.rectangle(annotated_image, (x1, y1), (x2, y2), (0, 255, 0), 2)
|
36 |
+
cv2.putText(annotated_image, plate_text, (x1, y1 - 10),
|
37 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2)
|
38 |
+
|
39 |
+
return annotated_image, '\n'.join(detected_texts)
|
40 |
+
|
41 |
+
demo = gr.Interface(
|
42 |
+
fn=detect_and_read_plate,
|
43 |
+
inputs=gr.Image(type="numpy", label="Upload Image"),
|
44 |
+
outputs=[
|
45 |
+
gr.Image(type="numpy", label="Detected Image with Plate Text"),
|
46 |
+
gr.Textbox(label="Detected Plate Texts")
|
47 |
+
],
|
48 |
+
title="Number Plate Detection and OCR",
|
49 |
+
description="YOLOv8 detects license plates and EasyOCR reads the number."
|
50 |
+
)
|
51 |
+
|
52 |
+
demo.launch()
|