Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,19 +1,49 @@
|
|
| 1 |
import torch
|
| 2 |
from ultralytics import YOLO
|
|
|
|
|
|
|
|
|
|
| 3 |
import gradio as gr
|
|
|
|
| 4 |
|
| 5 |
-
#
|
| 6 |
-
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
|
| 10 |
|
| 11 |
-
|
|
|
|
| 12 |
|
| 13 |
-
def
|
| 14 |
results = model(image)
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
import torch
|
| 2 |
from ultralytics import YOLO
|
| 3 |
+
import easyocr
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy as np
|
| 6 |
import gradio as gr
|
| 7 |
+
import os
|
| 8 |
|
| 9 |
+
# Download pretrained ANPR model (trained to detect license plates)
|
| 10 |
+
ANPR_WEIGHTS = "anpr_yolov8.pt"
|
| 11 |
+
if not os.path.exists(ANPR_WEIGHTS):
|
| 12 |
+
os.system(f"wget -O {ANPR_WEIGHTS} https://github.com/madalinabuzatu/yolov8-license-plate-detection/releases/download/v1.0/best.pt")
|
| 13 |
|
| 14 |
+
# Load YOLO ANPR model
|
| 15 |
+
model = YOLO(ANPR_WEIGHTS)
|
| 16 |
|
| 17 |
+
# Load OCR reader
|
| 18 |
+
reader = easyocr.Reader(['en'])
|
| 19 |
|
| 20 |
+
def detect_and_read_plate(image):
|
| 21 |
results = model(image)
|
| 22 |
+
for result in results:
|
| 23 |
+
boxes = result.boxes.xyxy.cpu().numpy() # [x1, y1, x2, y2]
|
| 24 |
+
for box in boxes:
|
| 25 |
+
x1, y1, x2, y2 = map(int, box)
|
| 26 |
+
# Crop the detected license plate
|
| 27 |
+
plate_img = image[y1:y2, x1:x2]
|
| 28 |
+
if plate_img.size == 0:
|
| 29 |
+
continue
|
| 30 |
+
# OCR to read text
|
| 31 |
+
ocr_result = reader.readtext(plate_img)
|
| 32 |
+
if ocr_result:
|
| 33 |
+
text = " ".join([res[1] for res in ocr_result])
|
| 34 |
+
print(f"Detected Plate: {text}")
|
| 35 |
+
# Draw bounding box + text
|
| 36 |
+
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
|
| 37 |
+
cv2.putText(image, text, (x1, y1 - 10),
|
| 38 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
|
| 39 |
|
| 40 |
+
return image
|
| 41 |
+
|
| 42 |
+
demo = gr.Interface(
|
| 43 |
+
fn=detect_and_read_plate,
|
| 44 |
+
inputs="image",
|
| 45 |
+
outputs="image",
|
| 46 |
+
title="Automatic Number Plate Recognition (ANPR)",
|
| 47 |
+
description="Upload an image of a car to detect and read its license plate."
|
| 48 |
+
)
|
| 49 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|