Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,51 +1,45 @@
|
|
1 |
-
import
|
2 |
import torch
|
3 |
import cv2
|
4 |
import numpy as np
|
|
|
5 |
from PIL import Image
|
6 |
-
from torchvision.transforms import functional as F
|
7 |
-
from ultralytics.yolo.utils.ops import non_max_suppression
|
8 |
-
from ultralytics.yolo.engine.model import Model
|
9 |
-
|
10 |
|
11 |
# Load YOLOv5 model
|
12 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
13 |
-
model =
|
|
|
14 |
model.eval()
|
15 |
|
16 |
def preprocess_image(image):
|
17 |
image = Image.fromarray(image)
|
18 |
-
|
19 |
-
return
|
20 |
|
21 |
-
def
|
22 |
-
image =
|
23 |
-
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
cv2.putText(image, text, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
|
32 |
|
33 |
-
|
|
|
|
|
|
|
34 |
|
35 |
-
|
36 |
-
image_tensor = preprocess_image(image)
|
37 |
-
outputs = model(image_tensor)
|
38 |
-
outputs = non_max_suppression(outputs)[0]
|
39 |
-
result_image = draw_boxes(image, outputs.cpu().numpy())
|
40 |
-
return result_image
|
41 |
|
|
|
42 |
iface = gr.Interface(
|
43 |
fn=detect_objects,
|
44 |
inputs=gr.Image(type="numpy"),
|
45 |
outputs=gr.Image(type="numpy"),
|
46 |
-
|
47 |
-
description="Upload an image to detect objects using the YOLOv5 model."
|
48 |
)
|
49 |
|
50 |
-
|
51 |
-
iface.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
1 |
+
from ultralytics import YOLO # Use Ultralytics' YOLO module
|
2 |
import torch
|
3 |
import cv2
|
4 |
import numpy as np
|
5 |
+
import gradio as gr
|
6 |
from PIL import Image
|
|
|
|
|
|
|
|
|
7 |
|
8 |
# Load YOLOv5 model
|
9 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
10 |
+
model = YOLO("yolov5s.pt") # Load pre-trained YOLOv5s model
|
11 |
+
model.to(device)
|
12 |
model.eval()
|
13 |
|
14 |
def preprocess_image(image):
|
15 |
image = Image.fromarray(image)
|
16 |
+
image = image.convert("RGB")
|
17 |
+
return image
|
18 |
|
19 |
+
def detect_objects(image):
|
20 |
+
image = preprocess_image(image)
|
21 |
+
results = model.predict(image) # Run YOLOv5 inference
|
22 |
|
23 |
+
# Convert results to bounding box format
|
24 |
+
detections = []
|
25 |
+
for result in results:
|
26 |
+
for box in result.boxes.xyxy:
|
27 |
+
x1, y1, x2, y2 = map(int, box[:4])
|
28 |
+
detections.append([x1, y1, x2, y2])
|
|
|
29 |
|
30 |
+
# Draw bounding boxes
|
31 |
+
image = np.array(image)
|
32 |
+
for x1, y1, x2, y2 in detections:
|
33 |
+
cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
|
34 |
|
35 |
+
return image
|
|
|
|
|
|
|
|
|
|
|
36 |
|
37 |
+
# Gradio UI
|
38 |
iface = gr.Interface(
|
39 |
fn=detect_objects,
|
40 |
inputs=gr.Image(type="numpy"),
|
41 |
outputs=gr.Image(type="numpy"),
|
42 |
+
live=True,
|
|
|
43 |
)
|
44 |
|
45 |
+
iface.launch()
|
|