Manvikk commited on
Commit
b16a09b
·
verified ·
1 Parent(s): dd623ec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -54
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import os
2
  import uuid
3
  import threading
4
- import time
5
  import cv2
6
  import numpy as np
7
  import base64
@@ -75,6 +74,10 @@ 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):
79
  try:
80
  jobs[job_id]['progress'] = 10
@@ -106,10 +109,12 @@ def process_image(job_id, image_path, object_type):
106
  for prediction in predictions:
107
  try:
108
  x, y, width, height = prediction["x"], prediction["y"], prediction["width"], prediction["height"]
 
109
  x1 = int(round(x - width / 2))
110
  y1 = int(round(y - height / 2))
111
  x2 = int(round(x + width / 2))
112
  y2 = int(round(y + height / 2))
 
113
  x1 = max(0, min(x1, img_width - 1))
114
  y1 = max(0, min(y1, img_height - 1))
115
  x2 = max(0, min(x2, img_width - 1))
@@ -125,53 +130,92 @@ def process_image(job_id, image_path, object_type):
125
  box_detections = custom_nms(processed_preds, iou_threshold=0.3)
126
  jobs[job_id]['progress'] = 60
127
 
128
- # (Optional) Detect ArUco marker for measurement
129
- marker_real_width_cm = 10.0
 
 
 
 
 
130
  try:
131
  gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
132
  aruco_dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_6X6_250)
133
- aruco_params = cv2.aruco.DetectorParameters()
 
 
 
 
134
  corners, ids, _ = cv2.aruco.detectMarkers(gray, aruco_dict, parameters=aruco_params)
135
  if ids is not None and len(corners) > 0:
 
136
  marker_corners = corners[0].reshape((4, 2))
137
  cv2.aruco.drawDetectedMarkers(image, corners, ids)
138
- marker_width_pixels = np.linalg.norm(marker_corners[0] - marker_corners[1])
139
- marker_height_pixels = np.linalg.norm(marker_corners[1] - marker_corners[2])
140
- marker_pixel_size = (marker_width_pixels + marker_height_pixels) / 2.0
141
- conversion_factor = marker_real_width_cm / marker_pixel_size
 
 
 
 
 
 
 
142
  else:
 
143
  conversion_factor = None
144
  except Exception as e:
 
145
  conversion_factor = None
146
 
 
147
  for pred in box_detections:
148
  x1, y1, x2, y2 = pred["box"]
149
  label = pred["class"]
150
  confidence = pred["confidence"]
151
  cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
152
- if conversion_factor is not None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  box_width_pixels = x2 - x1
154
  box_height_pixels = y2 - y1
155
  box_width_cm = box_width_pixels * conversion_factor
156
  box_height_cm = box_height_pixels * conversion_factor
157
- size_text = f"{box_width_cm:.1f}x{box_height_cm:.1f} cm"
158
- detection_info.append({
159
- "class": label,
160
- "confidence": f"{confidence:.2f}",
161
- "width_cm": f"{box_width_cm:.1f}",
162
- "height_cm": f"{box_height_cm:.1f}"
163
- })
164
  else:
165
- detection_info.append({
166
- "class": label,
167
- "confidence": f"{confidence:.2f}",
168
- "width_cm": "N/A",
169
- "height_cm": "N/A"
170
- })
 
 
 
 
171
  text = f"{label} ({confidence:.2f})"
172
  (text_width, text_height), baseline = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
173
- cv2.rectangle(image, (x1, y1 - text_height - baseline - 5), (x1 + text_width, y1 - 5), (0, 255, 0), -1)
174
- cv2.putText(image, text, (x1, y1 - 5 - baseline), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
 
 
 
175
  elif object_type in {"person", "car"}:
176
  if yolov5_model is None:
177
  jobs[job_id]['progress'] = 100
@@ -192,8 +236,10 @@ def process_image(job_id, image_path, object_type):
192
  cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (255, 0, 0), 2)
193
  text = f"{label} ({conf:.2f})"
194
  (text_width, text_height), baseline = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
195
- cv2.rectangle(image, (xmin, ymin - text_height - baseline - 5), (xmin + text_width, ymin - 5), (255, 0, 0), -1)
196
- cv2.putText(image, text, (xmin, ymin - 5 - baseline), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
 
 
197
  detection_info.append({
198
  "class": label,
199
  "confidence": f"{conf:.2f}",
@@ -205,7 +251,7 @@ def process_image(job_id, image_path, object_type):
205
  jobs[job_id]['result'] = {"error": "Error during YOLOv5 inference."}
206
  return
207
 
208
- # Build summary text (drawn on image)
209
  detection_counts = Counter(det["class"] for det in detection_info)
210
  if detection_counts:
211
  top_text = ", ".join(f"{cls}: {count}" for cls, count in detection_counts.items())
@@ -222,7 +268,7 @@ def process_image(job_id, image_path, object_type):
222
  jobs[job_id]['result'] = {"error": "Unexpected error during processing."}
223
 
224
  #########################################
225
- # 3. HTML Templates
226
  #########################################
227
 
228
  landing_template = '''
@@ -318,7 +364,7 @@ upload_template = '''
318
  </div>
319
  </div>
320
  <div class="typing-effect" id="typing"></div>
321
- <!-- The file upload form (submission handled via AJAX) -->
322
  <form id="uploadForm">
323
  <input type="file" name="file" accept="image/*" required>
324
  <!-- Hidden field to pass the selected object type -->
@@ -356,7 +402,7 @@ upload_template = '''
356
  </div>
357
  <div class="footer">&copy; 2024 MathLens AI Detection App. All rights reserved.</div>
358
  <script>
359
- // Handle typing effect (unchanged)
360
  const textArray = ["MathLens", "Smart Counting with Maths"];
361
  let textIndex = 0, charIndex = 0, isDeleting = false;
362
  const typingElement = document.getElementById("typing");
@@ -380,15 +426,12 @@ upload_template = '''
380
  document.addEventListener("DOMContentLoaded", () => {
381
  setTimeout(typeEffect, 500);
382
  });
383
-
384
- // AJAX-based submission and progress polling
385
  const uploadForm = document.getElementById("uploadForm");
386
  uploadForm.addEventListener("submit", function(e) {
387
  e.preventDefault();
388
  const formData = new FormData(uploadForm);
389
- // Show progress overlay
390
  document.getElementById("progressOverlay").style.display = "flex";
391
- // Start the analysis job
392
  fetch("{{ url_for('analyze') }}", {
393
  method: "POST",
394
  body: formData
@@ -396,14 +439,12 @@ upload_template = '''
396
  .then(response => response.json())
397
  .then(data => {
398
  const jobId = data.job_id;
399
- // Start polling progress every 500ms
400
  const progressInterval = setInterval(() => {
401
  fetch("{{ url_for('progress') }}?job_id=" + jobId)
402
  .then(response => response.json())
403
  .then(progData => {
404
  const progress = progData.progress;
405
  document.getElementById("progressBar").style.width = progress + "%";
406
- // Update dynamic phrases based on progress
407
  if (progress < 10) {
408
  document.getElementById("progressText").textContent = "Starting up... 🛠️";
409
  } else if (progress < 30) {
@@ -419,12 +460,10 @@ upload_template = '''
419
  }
420
  if (progress >= 100) {
421
  clearInterval(progressInterval);
422
- // Once done, fetch the result and update the page
423
  fetch("{{ url_for('result') }}?job_id=" + jobId)
424
  .then(response => response.json())
425
  .then(resultData => {
426
  document.getElementById("progressOverlay").style.display = "none";
427
- // Replace the result container with the new result
428
  document.getElementById("resultContainer").innerHTML = `
429
  <div class="content-wrapper">
430
  <img src="data:image/jpeg;base64,${resultData.image_data}" alt="Processed Image" class="result-img">
@@ -436,7 +475,6 @@ upload_template = '''
436
  }, 500);
437
  });
438
  });
439
-
440
  function buildTableHTML(detectionInfo) {
441
  if (!detectionInfo || detectionInfo.length === 0) return "";
442
  let tableHTML = `<table>
@@ -468,28 +506,23 @@ upload_template = '''
468
  '''
469
 
470
  #########################################
471
- # 4. Flask Routes
472
  #########################################
473
 
474
- # Landing page (unchanged)
475
  @app.route('/')
476
  def landing():
477
  return render_template_string(landing_template)
478
 
479
- # Traditional upload page (in case you want to support non-AJAX)
480
  @app.route('/upload', methods=['GET'])
481
  def upload():
482
  object_type = request.args.get('object_type', '').lower()
483
  if object_type not in {"person", "car", "box"}:
484
  flash("Please select a valid object type.")
485
  return redirect(url_for('landing'))
486
- # In this version the AJAX version is preferred.
487
  return render_template_string(upload_template, object_type=object_type)
488
 
489
- # Endpoint to start analysis (called via AJAX)
490
  @app.route('/analyze', methods=['POST'])
491
  def analyze():
492
- # Save uploaded file
493
  if 'file' not in request.files:
494
  return jsonify({"error": "No file provided."}), 400
495
  file = request.files['file']
@@ -504,17 +537,12 @@ def analyze():
504
  except Exception as e:
505
  return jsonify({"error": "Error saving file."}), 500
506
 
507
- # Create a unique job id and initialize job progress
508
  job_id = str(uuid.uuid4())
509
  jobs[job_id] = {"progress": 0, "result": None}
510
- # Start background thread to process image
511
  thread = threading.Thread(target=process_image, args=(job_id, upload_path, object_type))
512
  thread.start()
513
- # Optionally remove the uploaded file after starting the thread
514
- # (In a real system, you might want to keep it until processing is done.)
515
  return jsonify({"job_id": job_id})
516
 
517
- # Endpoint for client to poll progress
518
  @app.route('/progress', methods=['GET'])
519
  def progress():
520
  job_id = request.args.get('job_id', '')
@@ -522,21 +550,18 @@ def progress():
522
  return jsonify({"progress": 0})
523
  return jsonify({"progress": jobs[job_id].get("progress", 0)})
524
 
525
- # Endpoint for client to fetch final result
526
  @app.route('/result', methods=['GET'])
527
  def result():
528
  job_id = request.args.get('job_id', '')
529
  if job_id not in jobs or jobs[job_id].get("result") is None:
530
  return jsonify({"error": "Result not available."}), 404
531
  result = jobs[job_id]["result"]
532
- # Clean up job if desired
533
  del jobs[job_id]
534
  return jsonify(result)
535
 
536
  #########################################
537
- # 5. Run the App
538
  #########################################
539
 
540
  if __name__ == '__main__':
541
- # Run in threaded mode so background threads can work
542
  app.run(host="0.0.0.0", port=7860, threaded=True)
 
1
  import os
2
  import uuid
3
  import threading
 
4
  import cv2
5
  import numpy as np
6
  import base64
 
74
  filtered_preds.append(pred)
75
  return filtered_preds
76
 
77
+ #########################################
78
+ # 3. Processing Function with Homography Measurement
79
+ #########################################
80
+
81
  def process_image(job_id, image_path, object_type):
82
  try:
83
  jobs[job_id]['progress'] = 10
 
109
  for prediction in predictions:
110
  try:
111
  x, y, width, height = prediction["x"], prediction["y"], prediction["width"], prediction["height"]
112
+ # Convert center x,y and width, height to top-left and bottom-right coordinates
113
  x1 = int(round(x - width / 2))
114
  y1 = int(round(y - height / 2))
115
  x2 = int(round(x + width / 2))
116
  y2 = int(round(y + height / 2))
117
+ # Clamp coordinates to the image dimensions
118
  x1 = max(0, min(x1, img_width - 1))
119
  y1 = max(0, min(y1, img_height - 1))
120
  x2 = max(0, min(x2, img_width - 1))
 
130
  box_detections = custom_nms(processed_preds, iou_threshold=0.3)
131
  jobs[job_id]['progress'] = 60
132
 
133
+ # -------------------------------
134
+ # Improved ArUco marker detection and homography computation
135
+ # -------------------------------
136
+ # Since your marker is 10 cm, we set:
137
+ marker_real_width_cm = 10.0
138
+ homography = None
139
+ conversion_factor = None
140
  try:
141
  gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
142
  aruco_dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_6X6_250)
143
+ # Use DetectorParameters_create if available (for newer OpenCV versions)
144
+ if hasattr(cv2.aruco, 'DetectorParameters_create'):
145
+ aruco_params = cv2.aruco.DetectorParameters_create()
146
+ else:
147
+ aruco_params = cv2.aruco.DetectorParameters()
148
  corners, ids, _ = cv2.aruco.detectMarkers(gray, aruco_dict, parameters=aruco_params)
149
  if ids is not None and len(corners) > 0:
150
+ # Use the first detected marker as reference
151
  marker_corners = corners[0].reshape((4, 2))
152
  cv2.aruco.drawDetectedMarkers(image, corners, ids)
153
+ # Define destination points for a perfect square (e.g., 1000 x 1000 pixels)
154
+ dest_size = 1000.0
155
+ dst_pts = np.array([[0, 0],
156
+ [dest_size, 0],
157
+ [dest_size, dest_size],
158
+ [0, dest_size]], dtype=np.float32)
159
+ src_pts = marker_corners.astype(np.float32)
160
+ homography = cv2.getPerspectiveTransform(src_pts, dst_pts)
161
+ # In the warped image, the marker side is dest_size pixels,
162
+ # which corresponds to 10 cm in real life.
163
+ conversion_factor = marker_real_width_cm / dest_size # 10 cm / 1000 pixels = 0.01 cm per pixel
164
  else:
165
+ homography = None
166
  conversion_factor = None
167
  except Exception as e:
168
+ homography = None
169
  conversion_factor = None
170
 
171
+ # Process each detected box
172
  for pred in box_detections:
173
  x1, y1, x2, y2 = pred["box"]
174
  label = pred["class"]
175
  confidence = pred["confidence"]
176
  cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
177
+
178
+ if homography is not None and conversion_factor is not None:
179
+ # Warp the four corners of the bounding box using the homography
180
+ pts = np.array([[x1, y1],
181
+ [x2, y1],
182
+ [x2, y2],
183
+ [x1, y2]], dtype=np.float32).reshape(-1, 1, 2)
184
+ warped_pts = cv2.perspectiveTransform(pts, homography).reshape(-1, 2)
185
+ new_x1, new_y1 = np.min(warped_pts, axis=0)
186
+ new_x2, new_y2 = np.max(warped_pts, axis=0)
187
+ box_width_pixels = new_x2 - new_x1
188
+ box_height_pixels = new_y2 - new_y1
189
+ box_width_cm = box_width_pixels * conversion_factor
190
+ box_height_cm = box_height_pixels * conversion_factor
191
+ width_str = f"{box_width_cm:.1f}"
192
+ height_str = f"{box_height_cm:.1f}"
193
+ elif conversion_factor is not None:
194
+ # Fallback: use direct pixel measurements
195
  box_width_pixels = x2 - x1
196
  box_height_pixels = y2 - y1
197
  box_width_cm = box_width_pixels * conversion_factor
198
  box_height_cm = box_height_pixels * conversion_factor
199
+ width_str = f"{box_width_cm:.1f}"
200
+ height_str = f"{box_height_cm:.1f}"
 
 
 
 
 
201
  else:
202
+ width_str = "N/A"
203
+ height_str = "N/A"
204
+
205
+ detection_info.append({
206
+ "class": label,
207
+ "confidence": f"{confidence:.2f}",
208
+ "width_cm": width_str,
209
+ "height_cm": height_str
210
+ })
211
+
212
  text = f"{label} ({confidence:.2f})"
213
  (text_width, text_height), baseline = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
214
+ cv2.rectangle(image, (x1, y1 - text_height - baseline - 5),
215
+ (x1 + text_width, y1 - 5), (0, 255, 0), -1)
216
+ cv2.putText(image, text, (x1, y1 - 5 - baseline),
217
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
218
+
219
  elif object_type in {"person", "car"}:
220
  if yolov5_model is None:
221
  jobs[job_id]['progress'] = 100
 
236
  cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (255, 0, 0), 2)
237
  text = f"{label} ({conf:.2f})"
238
  (text_width, text_height), baseline = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
239
+ cv2.rectangle(image, (xmin, ymin - text_height - baseline - 5),
240
+ (xmin + text_width, ymin - 5), (255, 0, 0), -1)
241
+ cv2.putText(image, text, (xmin, ymin - 5 - baseline),
242
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
243
  detection_info.append({
244
  "class": label,
245
  "confidence": f"{conf:.2f}",
 
251
  jobs[job_id]['result'] = {"error": "Error during YOLOv5 inference."}
252
  return
253
 
254
+ # Draw a summary of detection counts on the image
255
  detection_counts = Counter(det["class"] for det in detection_info)
256
  if detection_counts:
257
  top_text = ", ".join(f"{cls}: {count}" for cls, count in detection_counts.items())
 
268
  jobs[job_id]['result'] = {"error": "Unexpected error during processing."}
269
 
270
  #########################################
271
+ # 4. HTML Templates
272
  #########################################
273
 
274
  landing_template = '''
 
364
  </div>
365
  </div>
366
  <div class="typing-effect" id="typing"></div>
367
+ <!-- File upload form (submission via AJAX) -->
368
  <form id="uploadForm">
369
  <input type="file" name="file" accept="image/*" required>
370
  <!-- Hidden field to pass the selected object type -->
 
402
  </div>
403
  <div class="footer">&copy; 2024 MathLens AI Detection App. All rights reserved.</div>
404
  <script>
405
+ // Typing effect
406
  const textArray = ["MathLens", "Smart Counting with Maths"];
407
  let textIndex = 0, charIndex = 0, isDeleting = false;
408
  const typingElement = document.getElementById("typing");
 
426
  document.addEventListener("DOMContentLoaded", () => {
427
  setTimeout(typeEffect, 500);
428
  });
429
+ // AJAX submission and progress polling
 
430
  const uploadForm = document.getElementById("uploadForm");
431
  uploadForm.addEventListener("submit", function(e) {
432
  e.preventDefault();
433
  const formData = new FormData(uploadForm);
 
434
  document.getElementById("progressOverlay").style.display = "flex";
 
435
  fetch("{{ url_for('analyze') }}", {
436
  method: "POST",
437
  body: formData
 
439
  .then(response => response.json())
440
  .then(data => {
441
  const jobId = data.job_id;
 
442
  const progressInterval = setInterval(() => {
443
  fetch("{{ url_for('progress') }}?job_id=" + jobId)
444
  .then(response => response.json())
445
  .then(progData => {
446
  const progress = progData.progress;
447
  document.getElementById("progressBar").style.width = progress + "%";
 
448
  if (progress < 10) {
449
  document.getElementById("progressText").textContent = "Starting up... 🛠️";
450
  } else if (progress < 30) {
 
460
  }
461
  if (progress >= 100) {
462
  clearInterval(progressInterval);
 
463
  fetch("{{ url_for('result') }}?job_id=" + jobId)
464
  .then(response => response.json())
465
  .then(resultData => {
466
  document.getElementById("progressOverlay").style.display = "none";
 
467
  document.getElementById("resultContainer").innerHTML = `
468
  <div class="content-wrapper">
469
  <img src="data:image/jpeg;base64,${resultData.image_data}" alt="Processed Image" class="result-img">
 
475
  }, 500);
476
  });
477
  });
 
478
  function buildTableHTML(detectionInfo) {
479
  if (!detectionInfo || detectionInfo.length === 0) return "";
480
  let tableHTML = `<table>
 
506
  '''
507
 
508
  #########################################
509
+ # 5. Flask Routes
510
  #########################################
511
 
 
512
  @app.route('/')
513
  def landing():
514
  return render_template_string(landing_template)
515
 
 
516
  @app.route('/upload', methods=['GET'])
517
  def upload():
518
  object_type = request.args.get('object_type', '').lower()
519
  if object_type not in {"person", "car", "box"}:
520
  flash("Please select a valid object type.")
521
  return redirect(url_for('landing'))
 
522
  return render_template_string(upload_template, object_type=object_type)
523
 
 
524
  @app.route('/analyze', methods=['POST'])
525
  def analyze():
 
526
  if 'file' not in request.files:
527
  return jsonify({"error": "No file provided."}), 400
528
  file = request.files['file']
 
537
  except Exception as e:
538
  return jsonify({"error": "Error saving file."}), 500
539
 
 
540
  job_id = str(uuid.uuid4())
541
  jobs[job_id] = {"progress": 0, "result": None}
 
542
  thread = threading.Thread(target=process_image, args=(job_id, upload_path, object_type))
543
  thread.start()
 
 
544
  return jsonify({"job_id": job_id})
545
 
 
546
  @app.route('/progress', methods=['GET'])
547
  def progress():
548
  job_id = request.args.get('job_id', '')
 
550
  return jsonify({"progress": 0})
551
  return jsonify({"progress": jobs[job_id].get("progress", 0)})
552
 
 
553
  @app.route('/result', methods=['GET'])
554
  def result():
555
  job_id = request.args.get('job_id', '')
556
  if job_id not in jobs or jobs[job_id].get("result") is None:
557
  return jsonify({"error": "Result not available."}), 404
558
  result = jobs[job_id]["result"]
 
559
  del jobs[job_id]
560
  return jsonify(result)
561
 
562
  #########################################
563
+ # 6. Run the App
564
  #########################################
565
 
566
  if __name__ == '__main__':
 
567
  app.run(host="0.0.0.0", port=7860, threaded=True)