File size: 1,741 Bytes
caff61e
bccf53b
dc80d48
0152e0c
 
4fa263e
caff61e
0152e0c
b5a364c
0152e0c
 
36e1064
0152e0c
 
 
 
 
 
 
 
e82b28e
8513c99
0152e0c
 
3e3644e
 
 
0152e0c
8513c99
3e3644e
 
 
0152e0c
3e3644e
0152e0c
3e3644e
0152e0c
 
 
 
 
 
 
 
 
 
 
 
8513c99
 
 
 
 
 
 
3e3644e
8513c99
 
 
0152e0c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import torch
import numpy as np
import gradio as gr
import cv2
import time
from PIL import Image

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Load YOLOv5 model
model = torch.hub.load("ultralytics/yolov5", "yolov5x", pretrained=True).to(device)

if device.type == "cuda":
    model.half()  # Use FP16 for performance boost

# Print available object classes
print(f"Model loaded with {len(model.names)} classes: {model.names}")

# Assign random colors to each class for bounding boxes
colors = {i: [int(c) for c in np.random.randint(0, 255, 3)] for i in range(len(model.names))}

def detect_objects(image):
    start_time = time.time()  # Start FPS measurement

   
    img_tensor = torch.from_numpy(image).permute(2, 0, 1).float().to(device) / 255.0
    img_tensor = img_tensor.unsqueeze(0)  

    with torch.no_grad():
        results = model(img_tensor)  
    
    detections = results.xyxy[0].cpu().numpy()  

    img_cv = image.copy() 

    for det in detections:
        x1, y1, x2, y2, conf, cls = map(int, det[:6])
        label = f"{model.names[cls]}: {conf:.2f}"

        cv2.rectangle(img_cv, (x1, y1), (x2, y2), colors[cls], 2)
        cv2.putText(img_cv, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, colors[cls], 2)

    # FPS Calculation
    end_time = time.time()
    fps = 1 / (end_time - start_time)
    print(f"FPS: {fps:.2f}")

    return img_cv

# Gradio interface
iface = gr.Interface(
    fn=detect_objects,
    inputs=gr.Image(type="numpy", label="Upload Image"),
    outputs=gr.Image(type="numpy", label="Detected Objects"),
    title="Object Detection with YOLOv5",
    description="Optimized for 30+ FPS real-time object detection!",
    allow_flagging="never",
)

iface.launch()