Spaces:
Sleeping
Sleeping
| """ | |
| YOLOv8 Object Detection | |
| Courses: 100 ch3, 320 ch7, 321 ch5, 360 ch4 | |
| """ | |
| import gradio as gr | |
| import numpy as np | |
| from ultralytics import YOLO | |
| # Load model once at startup (auto-downloads yolov8n.pt ~6MB) | |
| model = YOLO("yolov8n.pt") | |
| def detect(image: np.ndarray, conf_threshold: float, iou_threshold: float): | |
| if image is None: | |
| return None, [] | |
| results = model(image, conf=conf_threshold, iou=iou_threshold) | |
| annotated = results[0].plot() | |
| detections = [] | |
| for box in results[0].boxes: | |
| detections.append({ | |
| "class": model.names[int(box.cls)], | |
| "confidence": round(float(box.conf), 3), | |
| "bbox": [round(x, 1) for x in box.xyxy[0].tolist()], | |
| }) | |
| summary = f"Detected **{len(detections)}** objects" | |
| if detections: | |
| class_counts = {} | |
| for d in detections: | |
| class_counts[d["class"]] = class_counts.get(d["class"], 0) + 1 | |
| summary += ": " + ", ".join(f"{v}x {k}" for k, v in sorted(class_counts.items())) | |
| return annotated, summary | |
| with gr.Blocks(title="YOLOv8 Object Detection") as demo: | |
| gr.Markdown( | |
| "# YOLOv8 Object Detection\n" | |
| "Upload an image for real-time object detection. Adjust confidence and IoU thresholds.\n" | |
| "*Courses: 100 Deep Learning, 320 Vacuum Robot, 321 Robot Arm, 360 Autonomous Driving*" | |
| ) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| input_image = gr.Image(type="numpy", label="Upload Image") | |
| conf_slider = gr.Slider(0.1, 0.9, value=0.25, step=0.05, label="Confidence Threshold") | |
| iou_slider = gr.Slider(0.1, 0.9, value=0.45, step=0.05, label="IoU Threshold") | |
| run_btn = gr.Button("Detect Objects", variant="primary") | |
| with gr.Column(scale=2): | |
| output_image = gr.Image(label="Detection Results") | |
| output_text = gr.Markdown(label="Summary") | |
| run_btn.click( | |
| fn=detect, | |
| inputs=[input_image, conf_slider, iou_slider], | |
| outputs=[output_image, output_text], | |
| ) | |
| gr.Examples( | |
| examples=[ | |
| ["examples/street.jpg", 0.25, 0.45], | |
| ["examples/room.jpg", 0.25, 0.45], | |
| ["examples/traffic.jpg", 0.3, 0.45], | |
| ], | |
| inputs=[input_image, conf_slider, iou_slider], | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |