|
import gradio as gr |
|
import cv2 |
|
import numpy as np |
|
from ultralytics import YOLO |
|
import pytesseract |
|
import subprocess |
|
|
|
def load_model(model_path): |
|
""" |
|
Loads the YOLO model from the specified path. |
|
|
|
Parameters: |
|
model_path (str): Path to the YOLO model file. |
|
|
|
Returns: |
|
YOLO: Loaded YOLO model. |
|
""" |
|
return YOLO(model_path) |
|
|
|
def predict_and_plot(image, model): |
|
""" |
|
Predicts and plots the bounding boxes on the given image using the trained YOLO model. |
|
Also performs OCR on the detected bounding boxes to extract text. |
|
|
|
Parameters: |
|
image (numpy.ndarray): Input image. |
|
model (YOLO): The trained YOLO model. |
|
|
|
Returns: |
|
numpy.ndarray: Image with bounding boxes drawn. |
|
str: Detected text from the bounding boxes. |
|
""" |
|
if image is None: |
|
return None, "Error: No image provided." |
|
|
|
|
|
results = model.predict(image, device='cpu') |
|
|
|
detected_texts = [] |
|
|
|
|
|
for result in results: |
|
for box in result.boxes: |
|
|
|
x1, y1, x2, y2 = map(int, box.xyxy[0]) |
|
|
|
confidence = box.conf[0] |
|
|
|
|
|
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2) |
|
|
|
cv2.putText(image, f'{confidence*100:.2f}%', (x1, y1 - 10), |
|
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 0), 2) |
|
|
|
return image |
|
|
|
def main(image): |
|
""" |
|
Main function to handle the prediction and plotting. |
|
|
|
Parameters: |
|
image (numpy.ndarray): Input image. |
|
|
|
Returns: |
|
numpy.ndarray: Image with bounding boxes drawn. |
|
str: Detected text from the bounding boxes. |
|
""" |
|
|
|
model = load_model('best.pt') |
|
return predict_and_plot(image, model) |
|
|
|
|
|
iface = gr.Interface( |
|
fn=main, |
|
inputs=gr.Image(type="numpy", value="Cars418.png"), |
|
outputs=[ |
|
gr.Image(type="numpy", label="Output Image with Bounding Boxes") |
|
], |
|
title="License Plate Detection", |
|
description="Click 'Submit' to dodetection on current image or click 'Clear' and then Upload an image to detect license plates.", |
|
allow_flagging="never" |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
iface.launch() |
|
|