Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,11 +9,13 @@ from pathlib import Path
|
|
| 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 |
-
# Use YOLOv5 Nano for
|
| 16 |
model_path = Path("models/yolov5n.pt")
|
|
|
|
| 17 |
if model_path.exists():
|
| 18 |
print(f"Loading model from cache: {model_path}")
|
| 19 |
model = torch.hub.load("ultralytics/yolov5", "custom", path=str(model_path), source="local").to(device)
|
|
@@ -23,31 +25,36 @@ else:
|
|
| 23 |
torch.save(model.state_dict(), model_path)
|
| 24 |
|
| 25 |
# Optimize model for speed
|
| 26 |
-
model.conf = 0.3 #
|
| 27 |
-
model.iou = 0.3 # Non-Maximum Suppression
|
| 28 |
model.classes = None # Detect all classes
|
|
|
|
| 29 |
|
| 30 |
if device.type == "cuda":
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
torch.set_num_threads(os.cpu_count())
|
| 34 |
|
| 35 |
-
|
| 36 |
|
| 37 |
# Pre-generate colors for bounding boxes
|
| 38 |
np.random.seed(42)
|
| 39 |
colors = np.random.uniform(0, 255, size=(len(model.names), 3))
|
| 40 |
|
| 41 |
-
#
|
| 42 |
total_inference_time = 0
|
| 43 |
inference_count = 0
|
| 44 |
|
| 45 |
def preprocess_image(image):
|
| 46 |
-
"""
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
def detect_objects(image):
|
| 53 |
global total_inference_time, inference_count
|
|
@@ -68,7 +75,7 @@ def detect_objects(image):
|
|
| 68 |
inference_count += 1
|
| 69 |
avg_inference_time = total_inference_time / inference_count
|
| 70 |
|
| 71 |
-
detections = results.
|
| 72 |
|
| 73 |
output_image = image.copy()
|
| 74 |
|
|
@@ -77,6 +84,9 @@ def detect_objects(image):
|
|
| 77 |
class_id = int(cls)
|
| 78 |
color = colors[class_id].tolist()
|
| 79 |
|
|
|
|
|
|
|
|
|
|
| 80 |
# Draw bounding box
|
| 81 |
cv2.rectangle(output_image, (x1, y1), (x2, y2), color, 3, lineType=cv2.LINE_AA)
|
| 82 |
|
|
@@ -108,7 +118,7 @@ os.makedirs("examples", exist_ok=True)
|
|
| 108 |
|
| 109 |
with gr.Blocks(title="Optimized YOLOv5 Object Detection") as demo:
|
| 110 |
gr.Markdown("""
|
| 111 |
-
# Optimized YOLOv5 Object Detection
|
| 112 |
Detects objects using YOLOv5 with enhanced visualization and FPS tracking.
|
| 113 |
""")
|
| 114 |
|
|
|
|
| 9 |
# Create cache directory for models
|
| 10 |
os.makedirs("models", exist_ok=True)
|
| 11 |
|
| 12 |
+
# Select device
|
| 13 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 14 |
print(f"Using device: {device}")
|
| 15 |
|
| 16 |
+
# Use YOLOv5 Nano for speed
|
| 17 |
model_path = Path("models/yolov5n.pt")
|
| 18 |
+
|
| 19 |
if model_path.exists():
|
| 20 |
print(f"Loading model from cache: {model_path}")
|
| 21 |
model = torch.hub.load("ultralytics/yolov5", "custom", path=str(model_path), source="local").to(device)
|
|
|
|
| 25 |
torch.save(model.state_dict(), model_path)
|
| 26 |
|
| 27 |
# Optimize model for speed
|
| 28 |
+
model.conf = 0.3 # Confidence threshold
|
| 29 |
+
model.iou = 0.3 # IoU threshold for Non-Maximum Suppression (NMS)
|
| 30 |
model.classes = None # Detect all classes
|
| 31 |
+
model.eval()
|
| 32 |
|
| 33 |
if device.type == "cuda":
|
| 34 |
+
print("Using FP16 precision for inference (high speed, lower accuracy)")
|
| 35 |
+
model.half() # Enable FP16 for faster inference
|
|
|
|
| 36 |
|
| 37 |
+
torch.set_num_threads(os.cpu_count()) # Optimize CPU threading
|
| 38 |
|
| 39 |
# Pre-generate colors for bounding boxes
|
| 40 |
np.random.seed(42)
|
| 41 |
colors = np.random.uniform(0, 255, size=(len(model.names), 3))
|
| 42 |
|
| 43 |
+
# FPS tracking
|
| 44 |
total_inference_time = 0
|
| 45 |
inference_count = 0
|
| 46 |
|
| 47 |
def preprocess_image(image):
|
| 48 |
+
"""Prepares image for YOLOv5 detection while maintaining aspect ratio."""
|
| 49 |
+
h, w, _ = image.shape
|
| 50 |
+
scale = 640 / max(h, w)
|
| 51 |
+
new_w, new_h = int(w * scale), int(h * scale)
|
| 52 |
+
|
| 53 |
+
resized_image = cv2.resize(image, (new_w, new_h))
|
| 54 |
+
padded_image = np.full((640, 640, 3), 114, dtype=np.uint8) # Gray padding
|
| 55 |
+
padded_image[:new_h, :new_w] = resized_image
|
| 56 |
+
|
| 57 |
+
return cv2.cvtColor(padded_image, cv2.COLOR_RGB2BGR) # Convert to BGR for OpenCV
|
| 58 |
|
| 59 |
def detect_objects(image):
|
| 60 |
global total_inference_time, inference_count
|
|
|
|
| 75 |
inference_count += 1
|
| 76 |
avg_inference_time = total_inference_time / inference_count
|
| 77 |
|
| 78 |
+
detections = results.xyxy[0].cpu().numpy() # Use xyxy format
|
| 79 |
|
| 80 |
output_image = image.copy()
|
| 81 |
|
|
|
|
| 84 |
class_id = int(cls)
|
| 85 |
color = colors[class_id].tolist()
|
| 86 |
|
| 87 |
+
# Keep bounding boxes within image bounds
|
| 88 |
+
x1, y1, x2, y2 = max(0, x1), max(0, y1), min(640, x2), min(640, y2)
|
| 89 |
+
|
| 90 |
# Draw bounding box
|
| 91 |
cv2.rectangle(output_image, (x1, y1), (x2, y2), color, 3, lineType=cv2.LINE_AA)
|
| 92 |
|
|
|
|
| 118 |
|
| 119 |
with gr.Blocks(title="Optimized YOLOv5 Object Detection") as demo:
|
| 120 |
gr.Markdown("""
|
| 121 |
+
# Optimized YOLOv5 Object Detection
|
| 122 |
Detects objects using YOLOv5 with enhanced visualization and FPS tracking.
|
| 123 |
""")
|
| 124 |
|