Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,109 +4,99 @@ import gradio as gr
|
|
| 4 |
import cv2
|
| 5 |
import time
|
| 6 |
import os
|
|
|
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
-
# Create cache directory for models
|
| 10 |
os.makedirs("models", exist_ok=True)
|
| 11 |
|
| 12 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 13 |
print(f"Using device: {device}")
|
| 14 |
|
| 15 |
-
|
| 16 |
-
model_path = Path("models/yolov5x.pt")
|
| 17 |
-
if model_path.exists():
|
| 18 |
-
print(f"Loading model from cache: {model_path}")
|
| 19 |
-
model = torch.hub.load("ultralytics/yolov5", "yolov5x", pretrained=True, source="local", path=str(model_path)).to(device)
|
| 20 |
-
else:
|
| 21 |
-
print("Downloading YOLOv5x model and caching...")
|
| 22 |
-
model = torch.hub.load("ultralytics/yolov5", "yolov5x", pretrained=True).to(device)
|
| 23 |
-
torch.save(model.state_dict(), model_path)
|
| 24 |
|
| 25 |
-
|
| 26 |
-
model
|
| 27 |
-
model
|
| 28 |
-
model.
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
model.
|
| 32 |
-
|
| 33 |
-
|
| 34 |
|
| 35 |
-
model
|
|
|
|
| 36 |
|
|
|
|
| 37 |
np.random.seed(42)
|
| 38 |
-
colors = np.random.uniform(0, 255, size=(
|
| 39 |
|
| 40 |
total_inference_time = 0
|
| 41 |
inference_count = 0
|
| 42 |
|
| 43 |
def detect_objects(image):
|
| 44 |
global total_inference_time, inference_count
|
| 45 |
-
|
| 46 |
if image is None:
|
| 47 |
return None
|
| 48 |
-
|
| 49 |
start_time = time.time()
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
inference_time = time.time() - start_time
|
| 57 |
total_inference_time += inference_time
|
| 58 |
inference_count += 1
|
| 59 |
avg_inference_time = total_inference_time / inference_count
|
| 60 |
-
|
| 61 |
-
detections = results.pred[0].cpu().numpy()
|
| 62 |
-
|
| 63 |
-
for *xyxy, conf, cls in detections:
|
| 64 |
-
x1, y1, x2, y2 = map(int, xyxy)
|
| 65 |
-
class_id = int(cls)
|
| 66 |
-
color = colors[class_id].tolist()
|
| 67 |
-
|
| 68 |
-
# Thicker bounding boxes
|
| 69 |
-
cv2.rectangle(output_image, (x1, y1), (x2, y2), color, 3, lineType=cv2.LINE_AA)
|
| 70 |
-
|
| 71 |
-
label = f"{model.names[class_id]} {conf:.2f}"
|
| 72 |
-
font_scale, font_thickness = 0.9, 2 # Increased for better readability
|
| 73 |
-
(w, h), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, font_scale, font_thickness)
|
| 74 |
-
|
| 75 |
-
cv2.rectangle(output_image, (x1, y1 - h - 10), (x1 + w + 10, y1), color, -1)
|
| 76 |
-
cv2.putText(output_image, label, (x1 + 5, y1 - 5),
|
| 77 |
-
cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), font_thickness, lineType=cv2.LINE_AA)
|
| 78 |
-
|
| 79 |
fps = 1 / inference_time
|
| 80 |
-
|
| 81 |
-
#
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
cv2.putText(output_image, f"FPS: {fps:.2f}", (20, 40),
|
| 86 |
-
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2
|
| 87 |
cv2.putText(output_image, f"Avg FPS: {1/avg_inference_time:.2f}", (20, 70),
|
| 88 |
-
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2
|
| 89 |
-
|
| 90 |
return output_image
|
| 91 |
|
|
|
|
| 92 |
example_images = ["spring_street_after.jpg", "pexels-hikaique-109919.jpg"]
|
| 93 |
os.makedirs("examples", exist_ok=True)
|
| 94 |
|
| 95 |
with gr.Blocks(title="Optimized YOLOv5 Object Detection") as demo:
|
| 96 |
-
gr.Markdown(""
|
| 97 |
-
# Optimized YOLOv5 Object Detection
|
| 98 |
-
Detects objects using YOLOv5 with enhanced visualization and FPS tracking.
|
| 99 |
-
""")
|
| 100 |
|
| 101 |
with gr.Row():
|
| 102 |
with gr.Column(scale=1):
|
| 103 |
input_image = gr.Image(label="Input Image", type="numpy")
|
| 104 |
-
submit_button = gr.Button("
|
| 105 |
clear_button = gr.Button("Clear")
|
| 106 |
-
|
| 107 |
with gr.Column(scale=1):
|
| 108 |
output_image = gr.Image(label="Detected Objects", type="numpy")
|
| 109 |
-
|
| 110 |
gr.Examples(
|
| 111 |
examples=example_images,
|
| 112 |
inputs=input_image,
|
|
@@ -114,7 +104,7 @@ with gr.Blocks(title="Optimized YOLOv5 Object Detection") as demo:
|
|
| 114 |
fn=detect_objects,
|
| 115 |
cache_examples=True
|
| 116 |
)
|
| 117 |
-
|
| 118 |
submit_button.click(fn=detect_objects, inputs=input_image, outputs=output_image)
|
| 119 |
clear_button.click(lambda: (None, None), None, [input_image, output_image])
|
| 120 |
|
|
|
|
| 4 |
import cv2
|
| 5 |
import time
|
| 6 |
import os
|
| 7 |
+
import onnxruntime
|
| 8 |
from pathlib import Path
|
| 9 |
|
|
|
|
| 10 |
os.makedirs("models", exist_ok=True)
|
| 11 |
|
| 12 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 13 |
print(f"Using device: {device}")
|
| 14 |
|
| 15 |
+
model_path = Path("models/yolov5n.onnx")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
if not model_path.exists():
|
| 18 |
+
print("Downloading YOLOv5n model and converting to ONNX...")
|
| 19 |
+
model = torch.hub.load("ultralytics/yolov5", "yolov5n", pretrained=True).to(device)
|
| 20 |
+
model.eval()
|
| 21 |
+
|
| 22 |
+
# Exporting to ONNX
|
| 23 |
+
model.export(format="onnx", dynamic=True)
|
| 24 |
+
os.rename("yolov5n.onnx", model_path)
|
| 25 |
+
del model # Free memory
|
| 26 |
|
| 27 |
+
# Loading ONNX model for ultra-fast inference
|
| 28 |
+
session = onnxruntime.InferenceSession(str(model_path), providers=['CUDAExecutionProvider'])
|
| 29 |
|
| 30 |
+
# Generate random colors for each class
|
| 31 |
np.random.seed(42)
|
| 32 |
+
colors = np.random.uniform(0, 255, size=(80, 3)) # COCO dataset has 80 classes
|
| 33 |
|
| 34 |
total_inference_time = 0
|
| 35 |
inference_count = 0
|
| 36 |
|
| 37 |
def detect_objects(image):
|
| 38 |
global total_inference_time, inference_count
|
| 39 |
+
|
| 40 |
if image is None:
|
| 41 |
return None
|
| 42 |
+
|
| 43 |
start_time = time.time()
|
| 44 |
+
|
| 45 |
+
image = cv2.resize(image, (416, 416))
|
| 46 |
+
image = image.astype(np.float32) / 255.0 e
|
| 47 |
+
image = np.transpose(image, (2, 0, 1))
|
| 48 |
+
image = np.expand_dims(image, axis=0)
|
| 49 |
+
|
| 50 |
+
# Run inference
|
| 51 |
+
inputs = {session.get_inputs()[0].name: image}
|
| 52 |
+
output = session.run(None, inputs)
|
| 53 |
+
detections = output[0][0]
|
| 54 |
+
|
| 55 |
inference_time = time.time() - start_time
|
| 56 |
total_inference_time += inference_time
|
| 57 |
inference_count += 1
|
| 58 |
avg_inference_time = total_inference_time / inference_count
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
fps = 1 / inference_time
|
| 60 |
+
|
| 61 |
+
# Draw bounding boxes
|
| 62 |
+
output_image = image[0].transpose(1, 2, 0) * 255
|
| 63 |
+
output_image = output_image.astype(np.uint8)
|
| 64 |
+
|
| 65 |
+
for det in detections:
|
| 66 |
+
x1, y1, x2, y2, conf, class_id = map(int, det[:6])
|
| 67 |
+
if conf < 0.3: # Confidence threshold
|
| 68 |
+
continue
|
| 69 |
+
|
| 70 |
+
color = colors[class_id].tolist()
|
| 71 |
+
cv2.rectangle(output_image, (x1, y1), (x2, y2), color, 3)
|
| 72 |
+
label = f"Class {class_id} {conf:.2f}"
|
| 73 |
+
cv2.putText(output_image, label, (x1, y1 - 10),
|
| 74 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)
|
| 75 |
+
|
| 76 |
+
# Display FPS
|
| 77 |
cv2.putText(output_image, f"FPS: {fps:.2f}", (20, 40),
|
| 78 |
+
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
|
| 79 |
cv2.putText(output_image, f"Avg FPS: {1/avg_inference_time:.2f}", (20, 70),
|
| 80 |
+
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
|
| 81 |
+
|
| 82 |
return output_image
|
| 83 |
|
| 84 |
+
# Gradio Interface
|
| 85 |
example_images = ["spring_street_after.jpg", "pexels-hikaique-109919.jpg"]
|
| 86 |
os.makedirs("examples", exist_ok=True)
|
| 87 |
|
| 88 |
with gr.Blocks(title="Optimized YOLOv5 Object Detection") as demo:
|
| 89 |
+
gr.Markdown("# **Optimized YOLOv5 Object Detection** 🚀")
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
with gr.Row():
|
| 92 |
with gr.Column(scale=1):
|
| 93 |
input_image = gr.Image(label="Input Image", type="numpy")
|
| 94 |
+
submit_button = gr.Button("Detect Objects", variant="primary")
|
| 95 |
clear_button = gr.Button("Clear")
|
| 96 |
+
|
| 97 |
with gr.Column(scale=1):
|
| 98 |
output_image = gr.Image(label="Detected Objects", type="numpy")
|
| 99 |
+
|
| 100 |
gr.Examples(
|
| 101 |
examples=example_images,
|
| 102 |
inputs=input_image,
|
|
|
|
| 104 |
fn=detect_objects,
|
| 105 |
cache_examples=True
|
| 106 |
)
|
| 107 |
+
|
| 108 |
submit_button.click(fn=detect_objects, inputs=input_image, outputs=output_image)
|
| 109 |
clear_button.click(lambda: (None, None), None, [input_image, output_image])
|
| 110 |
|