| import gradio as gr |
| from ultralytics import YOLO |
| from PIL import Image |
|
|
| |
| model = YOLO("yolov8s.pt") |
|
|
| |
| def detect_objects(image, conf_threshold): |
| results = model(image, conf=conf_threshold) |
| result_image = results[0].plot() |
|
|
| detections = results[0].boxes |
| if detections is not None and len(detections) > 0: |
| labels = [] |
| for box in detections: |
| cls = int(box.cls) |
| conf = float(box.conf) |
| if conf >= conf_threshold: |
| name = model.names[cls] |
| labels.append(f"{name} ({conf*100:.2f}%)") |
| confidence_text = "\n".join(labels) if labels else "No objects above threshold." |
| else: |
| confidence_text = "No objects detected." |
|
|
| return Image.fromarray(result_image), confidence_text |
|
|
|
|
| |
| def detect_webcam(frame, conf_threshold): |
| results = model(frame, conf=conf_threshold) |
| result_frame = results[0].plot() |
| return Image.fromarray(result_frame) |
|
|
|
|
| |
| title = "YOLOv8s Object Detection BY ATUL ๐" |
| description = """ |
| Detect objects using YOLOv8s. |
| Adjust the **confidence threshold** in real time to control detection sensitivity. |
| You can upload an image or use your webcam. |
| Built with โค๏ธ using Ultralytics YOLO + Gradio. |
| """ |
|
|
| with gr.Blocks(title=title) as app: |
| gr.Markdown(f"# {title}") |
| gr.Markdown(description) |
|
|
| with gr.Tab("๐ธ Image Upload"): |
| conf_slider = gr.Slider(0.1, 1.0, value=0.5, step=0.05, label="Confidence Threshold") |
| image_input = gr.Image(type="pil", label="Upload Image") |
| image_output = gr.Image(label="Detected Objects") |
| conf_output = gr.Textbox(label="Detected Objects (with Confidence)", interactive=False) |
|
|
| gr.Button("Detect").click( |
| fn=detect_objects, |
| inputs=[image_input, conf_slider], |
| outputs=[image_output, conf_output] |
| ) |
|
|
| with gr.Tab("๐ฅ Live Camera"): |
| conf_slider_live = gr.Slider(0.1, 1.0, value=0.5, step=0.05, label="Confidence Threshold") |
| webcam_input = gr.Image(label="Webcam Feed", sources=["webcam"], streaming=True) |
| webcam_output = gr.Image(label="Live Detection") |
|
|
| webcam_input.stream( |
| fn=detect_webcam, |
| inputs=[webcam_input, conf_slider_live], |
| outputs=webcam_output |
| ) |
|
|
| if __name__ == "__main__": |
| app.launch() |
|
|