Manvikk commited on
Commit
dece34c
·
verified ·
1 Parent(s): 5515589

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -106
app.py CHANGED
@@ -14,7 +14,7 @@ app = Flask(__name__)
14
  app.secret_key = 'your_secret_key' # Replace with a secure secret key
15
 
16
  # Global dictionary to hold job progress and results
17
- jobs = {} # jobs[job_id] = {"progress": int, "result": {...}}
18
 
19
  #########################################
20
  # 1. Initialize the Models
@@ -75,10 +75,11 @@ def custom_nms(preds, iou_threshold=0.3):
75
  filtered_preds.append(pred)
76
  return filtered_preds
77
 
 
78
  def process_image(job_id, image_path, object_type, multiplier):
79
  try:
80
  jobs[job_id]['progress'] = 10
81
- # Load a fresh copy of the original image
82
  image = cv2.imread(image_path)
83
  if image is None:
84
  jobs[job_id]['progress'] = 100
@@ -96,35 +97,18 @@ def process_image(job_id, image_path, object_type, multiplier):
96
  jobs[job_id]['progress'] = 100
97
  jobs[job_id]['result'] = {"error": "Roboflow model not available."}
98
  return
 
 
 
 
 
 
 
99
 
100
- # Upscale the image if it is small to help detect small boxes.
101
- scale_factor = 1
102
- if img_width < 1000 or img_height < 1000:
103
- scale_factor = 2
104
-
105
- if scale_factor > 1:
106
- upscaled_image = cv2.resize(image, None, fx=scale_factor, fy=scale_factor, interpolation=cv2.INTER_LINEAR)
107
- temp_path = "upscaled.jpg"
108
- cv2.imwrite(temp_path, upscaled_image)
109
- results = box_model.predict(temp_path, confidence=30, overlap=20).json()
110
- else:
111
- results = box_model.predict(image_path, confidence=30, overlap=20).json()
112
-
113
- predictions = results.get("predictions", [])
114
  processed_preds = []
115
  for prediction in predictions:
116
  try:
117
- if scale_factor > 1:
118
- x = prediction["x"] / scale_factor
119
- y = prediction["y"] / scale_factor
120
- width = prediction["width"] / scale_factor
121
- height = prediction["height"] / scale_factor
122
- else:
123
- x = prediction["x"]
124
- y = prediction["y"]
125
- width = prediction["width"]
126
- height = prediction["height"]
127
-
128
  x1 = int(round(x - width / 2))
129
  y1 = int(round(y - height / 2))
130
  x2 = int(round(x + width / 2))
@@ -141,54 +125,22 @@ def process_image(job_id, image_path, object_type, multiplier):
141
  except Exception as e:
142
  continue
143
 
144
- # Use a higher NMS IoU threshold to avoid merging valid nearby detections.
145
- box_detections = custom_nms(processed_preds, iou_threshold=0.7)
146
  jobs[job_id]['progress'] = 60
147
 
148
- # --- ArUco Marker Detection for Measurement ---
149
- # We assume the printed marker is 5 cm x 5 cm.
150
- marker_real_width_cm = 5.0
151
- conversion_factor = None
152
- marker_bbox = None
153
  try:
154
- # Convert to grayscale
155
  gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
156
- # Try with histogram equalization
157
- equalized = cv2.equalizeHist(gray)
158
-
159
- # Use the DICT_6X6_250 dictionary; ensure your marker is generated with this dictionary.
160
- aruco_dict = cv2.aruco.Dictionary_get(cv2.aruco.DICT_6X6_50)
161
- parameters = cv2.aruco.DetectorParameters_create()
162
- # Optionally tweak parameters if needed:
163
- parameters.adaptiveThreshWinSizeMax = 400
164
- parameters.minDistanceToBorder = 0
165
- parameters.minMarkerPerimeterRate = 0.02
166
- parameters.cornerRefinementMethod = cv2.aruco.CORNER_REFINE_SUBPIX
167
-
168
- # First attempt detection on the equalized image
169
- corners, ids, rejected = cv2.aruco.detectMarkers(equalized, aruco_dict, parameters=parameters)
170
- print("DEBUG: Detected marker IDs (equalized):", ids)
171
- # If no markers found, try the original grayscale image
172
- if ids is None or len(ids) == 0:
173
- print("DEBUG: No markers detected on equalized image. Trying original grayscale.")
174
- corners, ids, rejected = cv2.aruco.detectMarkers(gray, aruco_dict, parameters=parameters)
175
- print("DEBUG: Detected marker IDs (original):", ids)
176
-
177
- if ids is not None and len(ids) > 0:
178
- selected_index = None
179
- # Try to select marker with ID 42 first
180
- for i, marker_id in enumerate(ids):
181
- if marker_id[0] == 42:
182
- selected_index = i
183
- break
184
- # If marker 42 is not found, use the first detected marker.
185
- if selected_index is None:
186
- print("DEBUG: Marker with ID 42 not found. Using first detected marker.")
187
- selected_index = 0
188
-
189
- marker_corners = corners[selected_index].reshape((4, 2))
190
- # Draw the detected marker on the image.
191
- cv2.aruco.drawDetectedMarkers(image, [corners[selected_index]], [ids[selected_index]])
192
  side_lengths = []
193
  for i in range(4):
194
  pt1 = marker_corners[i]
@@ -196,41 +148,11 @@ def process_image(job_id, image_path, object_type, multiplier):
196
  side_lengths.append(np.linalg.norm(pt1 - pt2))
197
  avg_side_length = np.mean(side_lengths)
198
  conversion_factor = marker_real_width_cm / avg_side_length
199
- print("DEBUG: Detected marker with ID", ids[selected_index][0],
200
- "Average side length (px):", avg_side_length,
201
- "Conversion factor:", conversion_factor)
202
- # Compute marker bounding box from the detected corners
203
- marker_bbox = (int(np.min(marker_corners[:, 0])),
204
- int(np.min(marker_corners[:, 1])),
205
- int(np.max(marker_corners[:, 0])),
206
- int(np.max(marker_corners[:, 1])))
207
- print("DEBUG: Marker bounding box:", marker_bbox)
208
  else:
209
- print("DEBUG: No markers detected in ArUco detection.")
210
  except Exception as e:
211
- print("DEBUG: Exception during ArUco detection:", e)
212
  conversion_factor = None
213
 
214
- # --- Filter out the marker from box detections ---
215
- if marker_bbox is not None:
216
- print("DEBUG: Filtering out aruco marker detection from box detections.")
217
- filtered_box_detections = []
218
- for detection in box_detections:
219
- x1, y1, x2, y2 = detection["box"]
220
- # Compute the center of the detection
221
- cx, cy = (x1 + x2) / 2, (y1 + y2) / 2
222
- # Compute IoU between detection and marker bounding box
223
- iou_val = compute_iou(detection["box"], marker_bbox)
224
- print("DEBUG: Detection box:", detection["box"], "Center:", (cx, cy), "IoU with marker:", iou_val)
225
- # If the center falls inside the marker's bbox or if IoU is above threshold, skip this detection.
226
- mx1, my1, mx2, my2 = marker_bbox
227
- if (mx1 <= cx <= mx2 and my1 <= cy <= my2) or iou_val > 0.3:
228
- print("DEBUG: Removing detection as marker.")
229
- continue
230
- filtered_box_detections.append(detection)
231
- box_detections = filtered_box_detections
232
-
233
- # --- Draw remaining box detections and compute measurements ---
234
  for pred in box_detections:
235
  x1, y1, x2, y2 = pred["box"]
236
  label = pred["class"]
@@ -295,11 +217,9 @@ def process_image(job_id, image_path, object_type, multiplier):
295
  detection_counts = Counter(det["class"] for det in detection_info)
296
  if detection_counts:
297
  top_text = ", ".join(f"{cls}: {count}" for cls, count in detection_counts.items())
298
- summary_font_scale = 1 * multiplier
299
- summary_thickness = 2 * multiplier
300
- (info_width, info_height), info_baseline = cv2.getTextSize(top_text, cv2.FONT_HERSHEY_SIMPLEX, summary_font_scale, summary_thickness)
301
  cv2.rectangle(image, (5, 5), (5 + info_width, 5 + info_height + info_baseline), (0, 255, 0), -1)
302
- cv2.putText(image, top_text, (5, 5 + info_height), cv2.FONT_HERSHEY_SIMPLEX, summary_font_scale, (0, 0, 0), summary_thickness)
303
 
304
  jobs[job_id]['progress'] = 100
305
  retval, buffer = cv2.imencode('.jpg', image)
@@ -580,6 +500,7 @@ def analyze():
580
  object_type = request.form.get('object_type', '').lower()
581
  if object_type not in {"person", "car", "box"}:
582
  return jsonify({"error": "Invalid object type."}), 400
 
583
  try:
584
  multiplier = int(request.form.get('multiplier', 1))
585
  except ValueError:
 
14
  app.secret_key = 'your_secret_key' # Replace with a secure secret key
15
 
16
  # Global dictionary to hold job progress and results
17
+ jobs = {} # jobs[job_id] = {"progress": int, "result": {}}
18
 
19
  #########################################
20
  # 1. Initialize the Models
 
75
  filtered_preds.append(pred)
76
  return filtered_preds
77
 
78
+ # Note the added multiplier parameter.
79
  def process_image(job_id, image_path, object_type, multiplier):
80
  try:
81
  jobs[job_id]['progress'] = 10
82
+ # Load image
83
  image = cv2.imread(image_path)
84
  if image is None:
85
  jobs[job_id]['progress'] = 100
 
97
  jobs[job_id]['progress'] = 100
98
  jobs[job_id]['result'] = {"error": "Roboflow model not available."}
99
  return
100
+ try:
101
+ results = box_model.predict(image_path, confidence=50, overlap=30).json()
102
+ predictions = results.get("predictions", [])
103
+ except Exception as e:
104
+ jobs[job_id]['progress'] = 100
105
+ jobs[job_id]['result'] = {"error": "Error during Roboflow prediction."}
106
+ return
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  processed_preds = []
109
  for prediction in predictions:
110
  try:
111
+ x, y, width, height = prediction["x"], prediction["y"], prediction["width"], prediction["height"]
 
 
 
 
 
 
 
 
 
 
112
  x1 = int(round(x - width / 2))
113
  y1 = int(round(y - height / 2))
114
  x2 = int(round(x + width / 2))
 
125
  except Exception as e:
126
  continue
127
 
128
+ box_detections = custom_nms(processed_preds, iou_threshold=0.3)
 
129
  jobs[job_id]['progress'] = 60
130
 
131
+ # (Optional) Detect ArUco marker for measurement
132
+ marker_real_width_cm = 10.0
 
 
 
133
  try:
 
134
  gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
135
+ aruco_dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_6X6_250)
136
+ if hasattr(cv2.aruco, 'DetectorParameters_create'):
137
+ aruco_params = cv2.aruco.DetectorParameters_create()
138
+ else:
139
+ aruco_params = cv2.aruco.DetectorParameters()
140
+ corners, ids, _ = cv2.aruco.detectMarkers(gray, aruco_dict, parameters=aruco_params)
141
+ if ids is not None and len(corners) > 0:
142
+ marker_corners = corners[0].reshape((4, 2))
143
+ cv2.aruco.drawDetectedMarkers(image, corners, ids)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  side_lengths = []
145
  for i in range(4):
146
  pt1 = marker_corners[i]
 
148
  side_lengths.append(np.linalg.norm(pt1 - pt2))
149
  avg_side_length = np.mean(side_lengths)
150
  conversion_factor = marker_real_width_cm / avg_side_length
 
 
 
 
 
 
 
 
 
151
  else:
152
+ conversion_factor = None
153
  except Exception as e:
 
154
  conversion_factor = None
155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  for pred in box_detections:
157
  x1, y1, x2, y2 = pred["box"]
158
  label = pred["class"]
 
217
  detection_counts = Counter(det["class"] for det in detection_info)
218
  if detection_counts:
219
  top_text = ", ".join(f"{cls}: {count}" for cls, count in detection_counts.items())
220
+ (info_width, info_height), info_baseline = cv2.getTextSize(top_text, cv2.FONT_HERSHEY_SIMPLEX, 1, 2)
 
 
221
  cv2.rectangle(image, (5, 5), (5 + info_width, 5 + info_height + info_baseline), (0, 255, 0), -1)
222
+ cv2.putText(image, top_text, (5, 5 + info_height), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2)
223
 
224
  jobs[job_id]['progress'] = 100
225
  retval, buffer = cv2.imencode('.jpg', image)
 
500
  object_type = request.form.get('object_type', '').lower()
501
  if object_type not in {"person", "car", "box"}:
502
  return jsonify({"error": "Invalid object type."}), 400
503
+ # Retrieve the multiplier sent from the client
504
  try:
505
  multiplier = int(request.form.get('multiplier', 1))
506
  except ValueError: