upadhyaysuraj's picture
Update app.py
b79123e verified
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."
# Perform prediction on the input image using the model
results = model.predict(image, device='cpu')
detected_texts = []
# Extract the bounding boxes and labels from the results
for result in results:
for box in result.boxes:
# Get the coordinates of the bounding box
x1, y1, x2, y2 = map(int, box.xyxy[0])
# Get the confidence score of the prediction
confidence = box.conf[0]
# Draw the bounding box on the image
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
# Draw the confidence score near the bounding box
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.
"""
# Load the model
model = load_model('best.pt')
return predict_and_plot(image, model)
# Create the Gradio interface
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" # Disable flagging
)
# Launch the Gradio app
if __name__ == "__main__":
iface.launch()