Simrandhiman commited on
Commit
5f810af
·
verified ·
1 Parent(s): f4ac993

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -0
app.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import urllib.request
3
+ import cv2
4
+ import numpy as np
5
+ from ultralytics import YOLO
6
+ import gradio as gr
7
+
8
+ # --- Setup writable paths for YOLO ---
9
+ os.environ["YOLO_CONFIG_DIR"] = "/tmp"
10
+ os.environ["HOME"] = "/tmp"
11
+
12
+ # --- Download YOLOv8s weights if not already present ---
13
+ MODEL_PATH = "/tmp/yolov8s.pt"
14
+ if not os.path.exists(MODEL_PATH):
15
+ print("Downloading YOLOv8s weights...")
16
+ urllib.request.urlretrieve(
17
+ "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolov8s.pt",
18
+ MODEL_PATH
19
+ )
20
+
21
+ # --- Load the YOLOv8 model ---
22
+ model = YOLO(MODEL_PATH)
23
+
24
+ # --- Detection function ---
25
+ def detect_objects(image):
26
+ """
27
+ Input: image (BGR)
28
+ Output: annotated image, detected object names
29
+ """
30
+ # Convert BGR (OpenCV) to RGB
31
+ image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
32
+
33
+ # Resize for consistent detection
34
+ image_resized = cv2.resize(image_rgb, (640, 640))
35
+
36
+ # Run YOLO inference with confidence threshold 0.2
37
+ results = model(image_resized, conf=0.2)
38
+
39
+ # Annotated image
40
+ annotated_image = results[0].plot()
41
+
42
+ # Extract detected class names
43
+ if results[0].boxes is not None:
44
+ detected_classes = [model.names[int(c)] for c in results[0].boxes.cls]
45
+ detected_text = ", ".join(detected_classes) if detected_classes else "No objects detected"
46
+ else:
47
+ detected_text = "No objects detected"
48
+
49
+ return annotated_image, detected_text
50
+
51
+ # --- Gradio Interface ---
52
+ demo = gr.Interface(
53
+ fn=detect_objects,
54
+ inputs=gr.Image(type="numpy", label="Upload Image"),
55
+ outputs=[
56
+ gr.Image(type="numpy", label="Detected Objects"),
57
+ gr.Textbox(label="Objects Detected")
58
+ ],
59
+ title="🧠 Object Detection App",
60
+ description="Upload an image — YOLOv8s detects all objects and lists their names!"
61
+ )
62
+
63
+ # --- Launch the app ---
64
+ if __name__ == "__main__":
65
+ demo.launch(server_name="0.0.0.0", server_port=7860)