|
import gradio as gr |
|
import cv2 |
|
import numpy as np |
|
from PIL import Image |
|
from ultralytics import YOLO |
|
|
|
|
|
model_all = YOLO('best.pt') |
|
model_np = YOLO('best_1.pt') |
|
|
|
def predict(image): |
|
|
|
img_array = np.array(image) |
|
|
|
|
|
results_all = model_all(img_array) |
|
results_np = model_np(img_array) |
|
|
|
|
|
|
|
combined_image = None |
|
for r in results_all: |
|
im_array = r.plot() |
|
combined_image = im_array |
|
|
|
|
|
for r in results_np: |
|
np_array = r.plot() |
|
if combined_image is not None: |
|
combined_image = np.maximum(combined_image, np_array) |
|
|
|
im = Image.fromarray(combined_image[..., ::-1]) |
|
|
|
|
|
class_counts_all = {i: 0 for i in range(len(model_all.names))} |
|
class_confidences_all = {i: [] for i in range(len(model_all.names))} |
|
np_count = 0 |
|
np_confidences = [] |
|
|
|
|
|
for box in results_all[0].boxes: |
|
cls = int(box.cls[0]) |
|
conf = float(box.conf[0]) |
|
class_counts_all[cls] += 1 |
|
class_confidences_all[cls].append(conf) |
|
|
|
|
|
for box in results_np[0].boxes: |
|
np_count += 1 |
|
np_confidences.append(float(box.conf[0])) |
|
|
|
|
|
output = "Detection Results:\n" |
|
for i in range(len(model_all.names)): |
|
count = class_counts_all[i] |
|
avg_conf = np.mean(class_confidences_all[i]) if class_confidences_all[i] else 0 |
|
if count > 0: |
|
output += f"{model_all.names[i]}: {count} detections (Avg. Confidence: {avg_conf:.2f})\n" |
|
|
|
|
|
if np_count > 0: |
|
avg_np_conf = np.mean(np_confidences) if np_confidences else 0 |
|
output += f"Number Plates: {np_count} detections (Avg. Confidence: {avg_np_conf:.2f})\n" |
|
|
|
return im, output |
|
|
|
|
|
iface = gr.Interface( |
|
fn=predict, |
|
inputs=gr.Image(type="pil"), |
|
outputs=[ |
|
gr.Image(type="pil", label="Detected Image"), |
|
gr.Textbox(label="Detection Results") |
|
], |
|
title="Helmet, License Plate, and Motorcyclist Detection", |
|
description="Upload an image to detect helmets, license plates, and motorcyclists using two specialized models." |
|
) |
|
|
|
|
|
iface.launch(share=True) |
|
|