Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -12,6 +12,7 @@ from torchvision.transforms import functional as F
|
|
12 |
from PIL import Image
|
13 |
import cv2
|
14 |
import gradio as gr
|
|
|
15 |
|
16 |
from yolov5.models.yolo import Model
|
17 |
from yolov5.utils.general import non_max_suppression
|
@@ -22,6 +23,7 @@ model.eval()
|
|
22 |
|
23 |
def preprocess_image(image):
|
24 |
try:
|
|
|
25 |
image_tensor = F.to_tensor(image)
|
26 |
return image_tensor.unsqueeze(0).to(device)
|
27 |
except Exception as e:
|
@@ -34,12 +36,13 @@ def draw_boxes(image, outputs, threshold=0.3):
|
|
34 |
h, w, _ = image.shape
|
35 |
|
36 |
for box in outputs:
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
|
|
43 |
|
44 |
return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
45 |
except Exception as e:
|
@@ -51,8 +54,8 @@ def detect_objects(image):
|
|
51 |
if image_tensor is None:
|
52 |
return image
|
53 |
try:
|
54 |
-
outputs = model(image_tensor)
|
55 |
-
outputs = non_max_suppression(outputs)[0]
|
56 |
result_image = draw_boxes(image, outputs)
|
57 |
return result_image
|
58 |
except Exception as e:
|
|
|
12 |
from PIL import Image
|
13 |
import cv2
|
14 |
import gradio as gr
|
15 |
+
import numpy as np # Add this import
|
16 |
|
17 |
from yolov5.models.yolo import Model
|
18 |
from yolov5.utils.general import non_max_suppression
|
|
|
23 |
|
24 |
def preprocess_image(image):
|
25 |
try:
|
26 |
+
image = image.convert("RGB") # Ensure image is in RGB mode
|
27 |
image_tensor = F.to_tensor(image)
|
28 |
return image_tensor.unsqueeze(0).to(device)
|
29 |
except Exception as e:
|
|
|
36 |
h, w, _ = image.shape
|
37 |
|
38 |
for box in outputs:
|
39 |
+
if box is not None:
|
40 |
+
x1, y1, x2, y2, score, label = box[:6]
|
41 |
+
if score > threshold:
|
42 |
+
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
|
43 |
+
cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
|
44 |
+
text = f"{model.names[int(label)]:s}: {score:.2f}"
|
45 |
+
cv2.putText(image, text, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
|
46 |
|
47 |
return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
48 |
except Exception as e:
|
|
|
54 |
if image_tensor is None:
|
55 |
return image
|
56 |
try:
|
57 |
+
outputs = model(image_tensor)[0] # Get the first element of the output
|
58 |
+
outputs = non_max_suppression(outputs, conf_thres=0.25, iou_thres=0.45)[0] # Apply NMS
|
59 |
result_image = draw_boxes(image, outputs)
|
60 |
return result_image
|
61 |
except Exception as e:
|