Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,164 +1,222 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
import
|
4 |
-
import
|
5 |
-
import
|
6 |
-
import
|
7 |
-
from
|
8 |
-
from
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
import base64
|
5 |
+
import io
|
6 |
+
from collections import Counter
|
7 |
+
from PIL import Image
|
8 |
+
from ultralytics import YOLO
|
9 |
+
import os
|
10 |
+
|
11 |
+
# Set page config
|
12 |
+
st.set_page_config(page_title="Object Detection App", layout="wide")
|
13 |
+
|
14 |
+
# Model paths
|
15 |
+
MODELS = {
|
16 |
+
'yolov8s.pt': './model/yolov8s.pt',
|
17 |
+
'yolov9m.pt': './model/yolov9m.pt'
|
18 |
+
}
|
19 |
+
|
20 |
+
# Load models on demand
|
21 |
+
@st.cache_resource
|
22 |
+
def get_model(model_name):
|
23 |
+
"""Load model if not already loaded"""
|
24 |
+
if model_name in MODELS and os.path.exists(MODELS[model_name]):
|
25 |
+
return YOLO(MODELS[model_name])
|
26 |
+
else:
|
27 |
+
raise ValueError(f"Model {model_name} not found")
|
28 |
+
|
29 |
+
def decode_base64_image(base64_string):
|
30 |
+
"""Base64 image string ko decode karna"""
|
31 |
+
# Remove data URL prefix if present
|
32 |
+
if ',' in base64_string:
|
33 |
+
base64_string = base64_string.split(',')[1]
|
34 |
+
|
35 |
+
image_data = base64.b64decode(base64_string)
|
36 |
+
image = Image.open(io.BytesIO(image_data))
|
37 |
+
return np.array(image)
|
38 |
+
|
39 |
+
def process_detections(results, model):
|
40 |
+
"""Process detection results into standard format"""
|
41 |
+
detections = []
|
42 |
+
for result in results:
|
43 |
+
boxes = result.boxes
|
44 |
+
for box in boxes:
|
45 |
+
# Bounding box coordinates
|
46 |
+
x1, y1, x2, y2 = box.xyxy[0]
|
47 |
+
|
48 |
+
# Confidence aur class
|
49 |
+
conf = box.conf[0]
|
50 |
+
cls = int(box.cls[0])
|
51 |
+
class_name = model.names[cls]
|
52 |
+
|
53 |
+
# Detection object banana
|
54 |
+
detection = {
|
55 |
+
'bbox': [float(x1), float(y1), float(x2-x1), float(y2-y1)],
|
56 |
+
'class': class_name,
|
57 |
+
'confidence': float(conf)
|
58 |
+
}
|
59 |
+
detections.append(detection)
|
60 |
+
return detections
|
61 |
+
|
62 |
+
# App title
|
63 |
+
st.title("Object Detection App")
|
64 |
+
|
65 |
+
# Sidebar for settings
|
66 |
+
st.sidebar.title("Settings")
|
67 |
+
|
68 |
+
# Available models info
|
69 |
+
available_models = [
|
70 |
+
{'name': 'yolov8s.pt', 'type': 'Object Detection', 'description': 'YOLOv8s (Fastest)'},
|
71 |
+
{'name': 'yolov9m.pt', 'type': 'Object Detection', 'description': 'YOLOv9m (Highest Accuracy)'},
|
72 |
+
]
|
73 |
+
|
74 |
+
# Model selection
|
75 |
+
model_options = {m['name']: f"{m['name']} - {m['description']}" for m in available_models}
|
76 |
+
model_name = st.sidebar.selectbox("Select Model", options=list(model_options.keys()), format_func=lambda x: model_options[x])
|
77 |
+
|
78 |
+
# Confidence threshold
|
79 |
+
confidence = st.sidebar.slider("Confidence Threshold", min_value=0.1, max_value=1.0, value=0.25, step=0.05)
|
80 |
+
|
81 |
+
# Tab selection
|
82 |
+
tab1, tab2 = st.tabs(["Single Image", "Multiple Images"])
|
83 |
+
|
84 |
+
with tab1:
|
85 |
+
st.header("Single Image Detection")
|
86 |
+
|
87 |
+
# Image upload
|
88 |
+
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
|
89 |
+
|
90 |
+
if uploaded_file is not None:
|
91 |
+
# Display uploaded image
|
92 |
+
image = Image.open(uploaded_file)
|
93 |
+
st.image(image, caption="Uploaded Image", use_column_width=True)
|
94 |
+
|
95 |
+
# Process button
|
96 |
+
if st.button("Detect Objects"):
|
97 |
+
try:
|
98 |
+
with st.spinner("Detecting objects..."):
|
99 |
+
# Load model
|
100 |
+
model = get_model(model_name)
|
101 |
+
|
102 |
+
# Convert to numpy array
|
103 |
+
image_np = np.array(image)
|
104 |
+
|
105 |
+
# Object detection
|
106 |
+
results = model(image_np, conf=confidence)
|
107 |
+
|
108 |
+
# Process results
|
109 |
+
detections = process_detections(results, model)
|
110 |
+
|
111 |
+
# Object grouping
|
112 |
+
object_counts = Counter(det['class'] for det in detections)
|
113 |
+
grouped_objects = [
|
114 |
+
{'class': obj, 'count': count}
|
115 |
+
for obj, count in object_counts.items()
|
116 |
+
]
|
117 |
+
|
118 |
+
# Display results if any detections found
|
119 |
+
if detections:
|
120 |
+
# Draw bounding boxes on image
|
121 |
+
result_image = image_np.copy()
|
122 |
+
for det in detections:
|
123 |
+
x, y, w, h = [int(val) for val in det['bbox']]
|
124 |
+
cv2.rectangle(result_image, (x, y), (x+w, y+h), (0, 255, 0), 2)
|
125 |
+
cv2.putText(result_image, f"{det['class']} {det['confidence']:.2f}",
|
126 |
+
(x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
|
127 |
+
|
128 |
+
# Show image with detections
|
129 |
+
st.image(result_image, caption="Detection Results", use_column_width=True)
|
130 |
+
|
131 |
+
# Display summary
|
132 |
+
st.subheader("Detection Summary")
|
133 |
+
for obj in grouped_objects:
|
134 |
+
st.write(f"- {obj['class']}: {obj['count']}")
|
135 |
+
|
136 |
+
# Display detection details
|
137 |
+
st.subheader("Detection Details")
|
138 |
+
for i, det in enumerate(detections, 1):
|
139 |
+
st.write(f"#{i}: {det['class']} (Confidence: {det['confidence']:.2f})")
|
140 |
+
else:
|
141 |
+
st.info("No objects detected in the image.")
|
142 |
+
|
143 |
+
except Exception as e:
|
144 |
+
st.error(f"Error processing image: {str(e)}")
|
145 |
+
|
146 |
+
with tab2:
|
147 |
+
st.header("Multiple Images Detection")
|
148 |
+
|
149 |
+
uploaded_files = st.file_uploader("Upload multiple images", type=["jpg", "jpeg", "png"], accept_multiple_files=True)
|
150 |
+
|
151 |
+
if uploaded_files:
|
152 |
+
st.write(f"{len(uploaded_files)} images uploaded")
|
153 |
+
|
154 |
+
# Process button
|
155 |
+
if st.button("Detect Objects in All Images"):
|
156 |
+
try:
|
157 |
+
with st.spinner("Detecting objects in multiple images..."):
|
158 |
+
# Load model
|
159 |
+
model = get_model(model_name)
|
160 |
+
|
161 |
+
# Process each image
|
162 |
+
all_detections = []
|
163 |
+
|
164 |
+
for i, file in enumerate(uploaded_files):
|
165 |
+
# Read image
|
166 |
+
image = Image.open(file)
|
167 |
+
image_np = np.array(image)
|
168 |
+
|
169 |
+
# Object detection
|
170 |
+
results = model(image_np, conf=confidence)
|
171 |
+
|
172 |
+
# Process results
|
173 |
+
detections = process_detections(results, model)
|
174 |
+
all_detections.append(detections)
|
175 |
+
|
176 |
+
# Create columns for image display
|
177 |
+
col1, col2 = st.columns(2)
|
178 |
+
|
179 |
+
with col1:
|
180 |
+
st.write(f"Image {i+1}: {file.name}")
|
181 |
+
st.image(image, caption=f"Original - {file.name}", use_column_width=True)
|
182 |
+
|
183 |
+
with col2:
|
184 |
+
# Draw bounding boxes
|
185 |
+
result_image = image_np.copy()
|
186 |
+
for det in detections:
|
187 |
+
x, y, w, h = [int(val) for val in det['bbox']]
|
188 |
+
cv2.rectangle(result_image, (x, y), (x+w, y+h), (0, 255, 0), 2)
|
189 |
+
cv2.putText(result_image, f"{det['class']} {det['confidence']:.2f}",
|
190 |
+
(x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
|
191 |
+
|
192 |
+
st.image(result_image, caption=f"Detections - {file.name}", use_column_width=True)
|
193 |
+
|
194 |
+
# Display detections for this image
|
195 |
+
object_counts = Counter(det['class'] for det in detections)
|
196 |
+
st.write("Detected objects:")
|
197 |
+
for obj, count in object_counts.items():
|
198 |
+
st.write(f"- {obj}: {count}")
|
199 |
+
|
200 |
+
st.divider()
|
201 |
+
|
202 |
+
# Overall summary
|
203 |
+
st.subheader("Overall Detection Summary")
|
204 |
+
all_objects = []
|
205 |
+
for detections in all_detections:
|
206 |
+
all_objects.extend([det['class'] for det in detections])
|
207 |
+
|
208 |
+
total_counts = Counter(all_objects)
|
209 |
+
for obj, count in total_counts.items():
|
210 |
+
st.write(f"- {obj}: {count} (across all images)")
|
211 |
+
|
212 |
+
except Exception as e:
|
213 |
+
st.error(f"Error processing images: {str(e)}")
|
214 |
+
|
215 |
+
# About section
|
216 |
+
st.sidebar.markdown("---")
|
217 |
+
st.sidebar.header("About")
|
218 |
+
st.sidebar.info("""
|
219 |
+
This app uses YOLO models for object detection.
|
220 |
+
- YOLOv8s: Faster detection
|
221 |
+
- YOLOv9m: Higher accuracy
|
222 |
+
""")
|