aleehassan commited on
Commit
be9bc95
·
verified ·
1 Parent(s): e2b8364

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +222 -164
app.py CHANGED
@@ -1,164 +1,222 @@
1
- from flask import Flask, request, jsonify
2
- from flask_cors import CORS
3
- import cv2
4
- import numpy as np
5
- import base64
6
- import io
7
- from collections import Counter
8
- from PIL import Image
9
- from ultralytics import YOLO
10
- import os
11
-
12
- # App Configuration
13
- app = Flask(__name__)
14
- CORS(app)
15
-
16
- # Model paths
17
- MODELS = {
18
- 'yolov8s.pt': './model/yolov8s.pt',
19
- 'yolov9m.pt': './model/yolov9m.pt'
20
- }
21
-
22
- # Load models on demand
23
- loaded_models = {}
24
-
25
- def get_model(model_name):
26
- """Load model if not already loaded"""
27
- if model_name not in loaded_models:
28
- if model_name in MODELS and os.path.exists(MODELS[model_name]):
29
- loaded_models[model_name] = YOLO(MODELS[model_name])
30
- else:
31
- raise ValueError(f"Model {model_name} not found")
32
- return loaded_models[model_name]
33
-
34
- def decode_base64_image(base64_string):
35
- """Base64 image string ko decode karna"""
36
- # Remove data URL prefix if present
37
- if ',' in base64_string:
38
- base64_string = base64_string.split(',')[1]
39
-
40
- image_data = base64.b64decode(base64_string)
41
- image = Image.open(io.BytesIO(image_data))
42
- return np.array(image)
43
-
44
- @app.route('/detect', methods=['POST'])
45
- def detect_objects():
46
- try:
47
- # Image receive karna
48
- image_base64 = request.json.get('image', '')
49
-
50
- # Get selected model
51
- model_name = request.json.get('model', 'yolov9m.pt')
52
- model = get_model(model_name)
53
-
54
- # Get confidence threshold
55
- confidence = request.json.get('confidence', 0.25)
56
-
57
- # Image decode karna
58
- image = decode_base64_image(image_base64)
59
-
60
- # Object detection
61
- results = model(image, conf=confidence)
62
-
63
- # Detected objects ko process karna
64
- detections = []
65
- for result in results:
66
- boxes = result.boxes
67
- for box in boxes:
68
- # Bounding box coordinates
69
- x1, y1, x2, y2 = box.xyxy[0]
70
-
71
- # Confidence aur class
72
- conf = box.conf[0]
73
- cls = int(box.cls[0])
74
- class_name = model.names[cls]
75
-
76
- # Detection object banana
77
- detection = {
78
- 'bbox': [float(x1), float(y1), float(x2-x1), float(y2-y1)],
79
- 'class': class_name,
80
- 'confidence': float(conf)
81
- }
82
- detections.append(detection)
83
-
84
- # Object grouping
85
- object_counts = Counter(det['class'] for det in detections)
86
- grouped_objects = [
87
- {'class': obj, 'count': count}
88
- for obj, count in object_counts.items()
89
- ]
90
-
91
- return jsonify({
92
- 'detections': detections,
93
- 'grouped_objects': grouped_objects,
94
- 'model_used': model_name
95
- })
96
-
97
- except Exception as e:
98
- return jsonify({'error': str(e)}), 500
99
-
100
- @app.route('/available-models', methods=['GET'])
101
- def get_available_models():
102
- """Available object detection models"""
103
- return jsonify({
104
- 'models': [
105
- {'name': 'yolov8s.pt', 'type': 'Object Detection', 'description': 'YOLOv8s (Fastest)'},
106
- {'name': 'yolov9m.pt', 'type': 'Object Detection', 'description': 'YOLOv9m (Highest Accuracy)'},
107
- ]
108
- })
109
-
110
- @app.route('/detect-multiple', methods=['POST'])
111
- def detect_multiple_objects():
112
- """Multiple images ke liye detection support"""
113
- try:
114
- images_base64 = request.json.get('images', [])
115
-
116
- # Get selected model
117
- model_name = request.json.get('model', 'yolov9m.pt')
118
- model = get_model(model_name)
119
-
120
- # Get confidence threshold
121
- confidence = request.json.get('confidence', 0.25)
122
-
123
- all_detections = []
124
-
125
- for image_base64 in images_base64:
126
- # Image decode karna
127
- image = decode_base64_image(image_base64)
128
-
129
- # Object detection
130
- results = model(image, conf=confidence)
131
-
132
- # Detected objects ko process karna
133
- image_detections = []
134
- for result in results:
135
- boxes = result.boxes
136
- for box in boxes:
137
- # Bounding box coordinates
138
- x1, y1, x2, y2 = box.xyxy[0]
139
-
140
- # Confidence aur class
141
- conf = box.conf[0]
142
- cls = int(box.cls[0])
143
- class_name = model.names[cls]
144
-
145
- # Detection object banana
146
- detection = {
147
- 'bbox': [float(x1), float(y1), float(x2-x1), float(y2-y1)],
148
- 'class': class_name,
149
- 'confidence': float(conf)
150
- }
151
- image_detections.append(detection)
152
-
153
- all_detections.append(image_detections)
154
-
155
- return jsonify({
156
- 'detections': all_detections,
157
- 'model_used': model_name
158
- })
159
-
160
- except Exception as e:
161
- return jsonify({'error': str(e)}), 500
162
-
163
- if __name__ == '__main__':
164
- app.run(debug=True, port=5000)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """)