Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -2,63 +2,59 @@ import torch
|
|
2 |
import cv2
|
3 |
import numpy as np
|
4 |
import gradio as gr
|
|
|
5 |
import random
|
6 |
|
7 |
# Load YOLOv5 model
|
8 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
9 |
-
model = torch.hub.load('ultralytics/yolov5', 'yolov5x', pretrained=True).to(device)
|
10 |
-
model.eval()
|
11 |
|
12 |
-
#
|
13 |
-
if device.type == 'cuda':
|
14 |
-
model.half()
|
15 |
-
|
16 |
-
# Get class names
|
17 |
CLASS_NAMES = model.names
|
18 |
|
19 |
-
#
|
|
|
20 |
CLASS_COLORS = {cls: (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for cls in CLASS_NAMES}
|
21 |
|
22 |
-
def
|
23 |
-
"""
|
24 |
-
image =
|
25 |
-
|
26 |
-
|
27 |
-
img_tensor = img_tensor.permute(2, 0, 1).unsqueeze(0) # Convert to batch format
|
28 |
-
|
29 |
-
if device.type == 'cuda':
|
30 |
-
img_tensor = img_tensor.half() # Use half precision for speed
|
31 |
|
32 |
-
|
33 |
-
with
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
|
38 |
-
for
|
39 |
-
x1, y1, x2, y2 =
|
40 |
-
class_name = CLASS_NAMES[int(cls)]
|
41 |
-
confidence = conf * 100
|
42 |
|
43 |
-
color = CLASS_COLORS[class_name]
|
44 |
|
45 |
# Draw bounding box
|
46 |
-
cv2.rectangle(image, (x1, y1), (x2, y2), color,
|
47 |
|
48 |
-
#
|
49 |
label = f"{class_name} ({confidence:.1f}%)"
|
50 |
-
cv2.putText(image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX,
|
|
|
|
|
|
|
51 |
|
52 |
-
return cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert back to RGB for Gradio
|
53 |
|
54 |
-
# Gradio Interface
|
55 |
iface = gr.Interface(
|
56 |
fn=detect_objects,
|
57 |
inputs=gr.Image(type="numpy", label="Upload Image"),
|
58 |
outputs=gr.Image(type="numpy", label="Detected Objects"),
|
59 |
-
title="
|
60 |
-
description="Use webcam or upload an image
|
61 |
-
allow_flagging="never"
|
|
|
62 |
)
|
63 |
|
64 |
# Launch the app
|
|
|
2 |
import cv2
|
3 |
import numpy as np
|
4 |
import gradio as gr
|
5 |
+
from PIL import Image
|
6 |
import random
|
7 |
|
8 |
# Load YOLOv5 model
|
9 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
10 |
+
model = torch.hub.load('ultralytics/yolov5', 'yolov5x', pretrained=True).to(device)
|
|
|
11 |
|
12 |
+
# Get class names from the model
|
|
|
|
|
|
|
|
|
13 |
CLASS_NAMES = model.names
|
14 |
|
15 |
+
# Generate consistent colors for each class
|
16 |
+
random.seed(42) # Fix the seed for consistent colors
|
17 |
CLASS_COLORS = {cls: (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for cls in CLASS_NAMES}
|
18 |
|
19 |
+
def preprocess_image(image):
|
20 |
+
"""Convert numpy image to PIL format for YOLOv5 processing."""
|
21 |
+
image = Image.fromarray(image)
|
22 |
+
image = image.convert("RGB")
|
23 |
+
return image
|
|
|
|
|
|
|
|
|
24 |
|
25 |
+
def detect_objects(image):
|
26 |
+
"""Detect objects in the image and draw bounding boxes with consistent colors."""
|
27 |
+
image = preprocess_image(image)
|
28 |
+
results = model([image]) # YOLOv5 inference
|
29 |
+
image = np.array(image) # Convert PIL image back to numpy for OpenCV
|
30 |
|
31 |
+
for *box, conf, cls in results.xyxy[0]:
|
32 |
+
x1, y1, x2, y2 = map(int, box)
|
33 |
+
class_name = CLASS_NAMES[int(cls)]
|
34 |
+
confidence = conf.item() * 100
|
35 |
|
36 |
+
color = CLASS_COLORS[class_name] # Use pre-generated consistent color
|
37 |
|
38 |
# Draw bounding box
|
39 |
+
cv2.rectangle(image, (x1, y1), (x2, y2), color, 4)
|
40 |
|
41 |
+
# Display class label with confidence score
|
42 |
label = f"{class_name} ({confidence:.1f}%)"
|
43 |
+
cv2.putText(image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX,
|
44 |
+
1, color, 3, cv2.LINE_AA)
|
45 |
+
|
46 |
+
return image
|
47 |
|
|
|
48 |
|
49 |
+
# Create Gradio Interface
|
50 |
iface = gr.Interface(
|
51 |
fn=detect_objects,
|
52 |
inputs=gr.Image(type="numpy", label="Upload Image"),
|
53 |
outputs=gr.Image(type="numpy", label="Detected Objects"),
|
54 |
+
title="Object Detection with YOLOv5",
|
55 |
+
description="Use webcam or upload an image to detect objects.",
|
56 |
+
allow_flagging="never",
|
57 |
+
examples=["spring_street_after.jpg", "pexels-hikaique-109919.jpg"]
|
58 |
)
|
59 |
|
60 |
# Launch the app
|