|
import gradio as gr |
|
import cv2 |
|
import numpy as np |
|
from ultralytics import YOLO |
|
import easyocr |
|
import torch |
|
import os |
|
|
|
|
|
model = YOLO("best.pt") |
|
|
|
|
|
reader = easyocr.Reader(['en'], gpu=torch.cuda.is_available()) |
|
|
|
def anpr(image): |
|
""" |
|
Process the input image to detect and read license plates. |
|
Args: |
|
image: Input image (numpy array or file path) |
|
Returns: |
|
output_image: Image with bounding boxes and text |
|
license_plate_text: Extracted license plate text |
|
""" |
|
try: |
|
|
|
image_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) |
|
|
|
|
|
results = model(image_cv) |
|
|
|
license_plate_text = "" |
|
for result in results: |
|
boxes = result.boxes |
|
for box in boxes: |
|
|
|
x1, y1, x2, y2 = map(int, box.xyxy[0]) |
|
confidence = box.conf[0] |
|
|
|
if confidence > 0.5: |
|
|
|
plate_region = image_cv[y1:y2, x1:x2] |
|
|
|
|
|
ocr_results = reader.readtext(plate_region) |
|
for (bbox, text, prob) in ocr_results: |
|
if prob > 0.5: |
|
license_plate_text += text + " " |
|
|
|
|
|
cv2.rectangle(image_cv, (x1, y1), (x2, y2), (0, 255, 0), 2) |
|
cv2.putText(image_cv, license_plate_text.strip(), (x1, y1 - 10), |
|
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) |
|
|
|
|
|
output_image = cv2.cvtColor(image_cv, cv2.COLOR_BGR2RGB) |
|
return output_image, license_plate_text.strip() |
|
except Exception as e: |
|
return None, f"Error: {str(e)}" |
|
|
|
|
|
iface = gr.Interface( |
|
fn=anpr, |
|
inputs=gr.Image(type="pil", label="Upload an image"), |
|
outputs=[ |
|
gr.Image(type="numpy", label="Processed Image"), |
|
gr.Textbox(label="License Plate Text") |
|
], |
|
title="Automatic Number Plate Recognition (ANPR) with YOLOv8", |
|
description="Upload an image to detect and read license plates using YOLOv8 and EasyOCR." |
|
) |
|
|
|
|
|
def anpr_api(image): |
|
""" |
|
API endpoint for ANPR. |
|
Args: |
|
image: Input image file (uploaded via API) |
|
Returns: |
|
dict: Dictionary containing license plate text and processed image path |
|
""" |
|
output_image, license_plate_text = anpr(image) |
|
if output_image is not None: |
|
|
|
output_path = "output_image.jpg" |
|
cv2.imwrite(output_path, cv2.cvtColor(output_image, cv2.COLOR_RGB2BGR)) |
|
return { |
|
"license_plate_text": license_plate_text, |
|
"processed_image": output_path |
|
} |
|
else: |
|
return {"error": license_plate_text} |
|
|
|
|
|
if __name__ == "__main__": |
|
iface.launch(server_name="0.0.0.0", server_port=7860, share=False) |