maliahson's picture
Create app.py
52b4404 verified
import gradio as gr
import cv2
import numpy as np
from ultralytics import YOLO
import easyocr
import torch
import os
# Initialize the YOLOv8 model
model = YOLO("best.pt")
# Initialize EasyOCR reader
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:
# Convert Gradio image input (PIL) to OpenCV format
image_cv = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
# Run YOLOv8 inference
results = model(image_cv)
license_plate_text = ""
for result in results:
boxes = result.boxes
for box in boxes:
# Extract bounding box coordinates
x1, y1, x2, y2 = map(int, box.xyxy[0])
confidence = box.conf[0]
if confidence > 0.5: # Confidence threshold
# Crop the license plate region
plate_region = image_cv[y1:y2, x1:x2]
# Run EasyOCR on the cropped region
ocr_results = reader.readtext(plate_region)
for (bbox, text, prob) in ocr_results:
if prob > 0.5: # OCR confidence threshold
license_plate_text += text + " "
# Draw bounding box and text on the image
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)
# Convert back to RGB for Gradio
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)}"
# Define the Gradio interface
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."
)
# API endpoint for programmatic access
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:
# Save the output image temporarily
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}
# Launch the Gradio app with API enabled
if __name__ == "__main__":
iface.launch(server_name="0.0.0.0", server_port=7860, share=False)