MVPavanKumar commited on
Commit
60c88b5
·
verified ·
1 Parent(s): 154d670

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -44
app.py CHANGED
@@ -269,7 +269,7 @@ def handle_file_upload(uploaded_file):
269
  Handles file upload by converting the .pts file to .npy for faster processing.
270
  """
271
  if uploaded_file is None:
272
- return "No file uploaded.", None, None
273
 
274
  temp_root = os.path.join(tempfile.gettempdir(), f"temp_pts_{uuid.uuid4().hex}")
275
  os.makedirs(temp_root, exist_ok=True)
@@ -279,35 +279,31 @@ def handle_file_upload(uploaded_file):
279
 
280
  pts_to_npy(uploaded_file.name, pts_npy_path, cols_npy_path)
281
 
282
- # Return the paths to the .npy files and a success message
283
  return (f"File loaded successfully. Click 'Start Analysis' to continue.",
284
- None,
285
- None,
286
- pts_npy_path,
287
- cols_npy_path)
288
 
289
- def start_analysis(pts_npy_path, cols_npy_path):
290
  """
291
  Performs the full analysis on the pre-loaded .npy files.
292
  Uses 'yield' to provide progressive updates to the UI.
293
  """
 
 
294
  if not (pts_npy_path and cols_npy_path and os.path.exists(pts_npy_path)):
295
- return "Please upload a file first.", None, None, None, None
296
 
297
- # Load data from the session state
298
- yield "Loading data from file...", None, None
299
  points = np.load(pts_npy_path, mmap_mode='r')
300
  colors = np.load(cols_npy_path, mmap_mode='r')
301
  n_points = points.shape[0]
302
-
303
  output_text = f"Total points: {n_points:,}\n"
304
 
305
- yield f"{output_text}\nIdentifying green points...", None, None
306
-
307
- # compute green mask in chunks
308
  chunk = 1_000_000
309
  green_mask = np.zeros(n_points, dtype=bool)
310
- for i in range(0, n_points, chunk):
311
  j = min(n_points, i + chunk)
312
  green_mask[i:j] = is_green_mask_from_rgb(colors[i:j])
313
  green_indices = np.nonzero(green_mask)[0]
@@ -315,11 +311,9 @@ def start_analysis(pts_npy_path, cols_npy_path):
315
  output_text += f"Green-colored points: {green_count:,}\n"
316
 
317
  if green_count == 0:
318
- yield "No green points detected.", None, None
319
-
320
- yield f"{output_text}\nClustering green points...", None, None
321
 
322
- # ---- Auto-adjust max dbscan points based on green_count ----
323
  if green_count <= 1000:
324
  max_dbscan_points = green_count
325
  elif green_count <= 5000:
@@ -329,7 +323,6 @@ def start_analysis(pts_npy_path, cols_npy_path):
329
  else:
330
  max_dbscan_points = 5000
331
 
332
- # ---- Saturation prioritized sampling (if we must sample) ----
333
  hsv_all = rgb_to_hsv_array(colors[green_indices])
334
  saturation = hsv_all[:, 1]
335
  order_by_sat = np.argsort(-saturation)
@@ -352,7 +345,6 @@ def start_analysis(pts_npy_path, cols_npy_path):
352
  dbscan_pts = points[green_indices]
353
  dbscan_map = green_indices
354
 
355
- # ---- Estimate eps adaptively and run multi-scale DBSCAN ----
356
  est_eps = estimate_eps(dbscan_pts, sample_size=3000, k=8)
357
  eps1 = max(0.15, min(0.45, est_eps))
358
  eps2 = min(0.9, eps1 * 1.6)
@@ -360,15 +352,11 @@ def start_analysis(pts_npy_path, cols_npy_path):
360
 
361
  output_text += f"Estimated base eps: {eps1:.3f} (second-pass eps: {eps2:.3f}), min_samples: {min_samples}\n"
362
 
363
- # First pass
364
  clust1 = DBSCAN(eps=eps1, min_samples=min_samples).fit(dbscan_pts)
365
  labels1 = clust1.labels_
366
-
367
- # Second pass (coarser)
368
  clust2 = DBSCAN(eps=eps2, min_samples=max(6, int(min_samples / 2))).fit(dbscan_pts)
369
  labels2 = clust2.labels_
370
 
371
- # Combine clusters
372
  combined_labels = labels1.copy()
373
  noise_mask = combined_labels == -1
374
  combined_labels[noise_mask] = labels2[noise_mask]
@@ -380,9 +368,7 @@ def start_analysis(pts_npy_path, cols_npy_path):
380
  continue
381
  norm_labels[combined_labels == lab] = nid
382
 
383
- yield f"{output_text}\nRefining clusters with region growing...", None, None
384
-
385
- # ---- Merge neighboring clusters that overlap after mapping back to full green set ----
386
  sampled_map = dbscan_map
387
  valid_labels = [lab for lab in np.unique(norm_labels) if lab != -1]
388
  green_pts_full = points[green_indices]
@@ -406,14 +392,12 @@ def start_analysis(pts_npy_path, cols_npy_path):
406
  for gp in neigh:
407
  full_label_assignment[int(gp)] = int(lab)
408
 
409
- # After region grow, group final labels by scanning full_label_assignment
410
  final_label_positions = {}
411
  for pos, lab in enumerate(full_label_assignment):
412
  if lab == -1:
413
  continue
414
  final_label_positions.setdefault(int(lab), []).append(int(pos))
415
 
416
- # Build clusters_info
417
  clusters_info = []
418
  for lab, green_positions in final_label_positions.items():
419
  abs_indices = green_indices[green_positions]
@@ -421,7 +405,6 @@ def start_analysis(pts_npy_path, cols_npy_path):
421
  cluster_cols = np.asarray(colors[abs_indices])
422
  corners, centroid, length, width, height, zmin, zmax = get_bbox_and_metrics(cluster_pts)
423
  volume = length * width * height
424
- # Apply relaxed filters
425
  if height < MIN_HEIGHT or length > MAX_LENGTH or width > MAX_WIDTH:
426
  continue
427
  if volume < MIN_VOLUME:
@@ -430,7 +413,6 @@ def start_analysis(pts_npy_path, cols_npy_path):
430
  if density < MIN_DENSITY:
431
  continue
432
 
433
- # Use the same temporary directory for previews
434
  temp_root = os.path.dirname(pts_npy_path)
435
  preview_fn = os.path.join(temp_root, f"obj_preview_lab{lab}_{uuid.uuid4().hex}.png")
436
  save_cluster_preview_png(cluster_pts, cluster_cols, preview_fn)
@@ -447,9 +429,7 @@ def start_analysis(pts_npy_path, cols_npy_path):
447
 
448
  output_text += f"Detected {len(clusters_info)} object-shaped clusters after filtering\n"
449
 
450
- yield f"{output_text}\nGenerating 3D plot and Excel report...", None, None
451
-
452
- # ---- Interactive preview (downsampled) ----
453
  if n_points > PREVIEW_MAX_POINTS:
454
  rng = np.random.default_rng(1)
455
  idx_preview = rng.choice(n_points, size=PREVIEW_MAX_POINTS, replace=False)
@@ -481,21 +461,20 @@ def start_analysis(pts_npy_path, cols_npy_path):
481
  add_bbox_to_fig(fig, info["corners"], color='red', width=4)
482
  fig.update_layout(scene=dict(aspectmode='data'), height=800, margin=dict(l=0, r=0, t=0, b=0))
483
 
484
- # ---- Excel export ----
485
  out_xlsx = None
486
  if clusters_info:
487
  out_xlsx = os.path.join(temp_root, "detected_objects_styled.xlsx")
488
  create_styled_excel(clusters_info, out_xlsx)
489
 
490
- yield "Analysis complete.", fig, out_xlsx
491
-
492
 
493
  # Gradio Interface
494
  with gr.Blocks(title="Detection") as demo:
495
  gr.Markdown("# Green Dustbin & AIS Box Detection")
496
  gr.Markdown("Upload a `.pts` file to analyze the point cloud data.")
497
 
498
- file_state = gr.State(value=None)
499
 
500
  with gr.Row():
501
  file_input = gr.File(label="Upload .pts (X Y Z R G B)")
@@ -516,11 +495,7 @@ with gr.Blocks(title="Detection") as demo:
516
  analysis_button.click(
517
  fn=start_analysis,
518
  inputs=[file_state],
519
- outputs=[output_text, output_plot, download_button],
520
- queue=True
521
- ).then(
522
- fn=lambda: gr.update(visible=True),
523
- outputs=[download_button]
524
  )
525
 
526
  demo.launch()
 
269
  Handles file upload by converting the .pts file to .npy for faster processing.
270
  """
271
  if uploaded_file is None:
272
+ return "No file uploaded.", gr.update(interactive=False), gr.update(visible=False), [None, None]
273
 
274
  temp_root = os.path.join(tempfile.gettempdir(), f"temp_pts_{uuid.uuid4().hex}")
275
  os.makedirs(temp_root, exist_ok=True)
 
279
 
280
  pts_to_npy(uploaded_file.name, pts_npy_path, cols_npy_path)
281
 
 
282
  return (f"File loaded successfully. Click 'Start Analysis' to continue.",
283
+ gr.update(interactive=True),
284
+ gr.update(visible=False),
285
+ [pts_npy_path, cols_npy_path])
 
286
 
287
+ def start_analysis(file_state, progress=gr.Progress(track_tqdm=True)):
288
  """
289
  Performs the full analysis on the pre-loaded .npy files.
290
  Uses 'yield' to provide progressive updates to the UI.
291
  """
292
+ pts_npy_path, cols_npy_path = file_state
293
+
294
  if not (pts_npy_path and cols_npy_path and os.path.exists(pts_npy_path)):
295
+ return "Please upload a file first.", None, None, gr.update(interactive=False)
296
 
297
+ progress(0.1, desc="Loading point cloud data...")
 
298
  points = np.load(pts_npy_path, mmap_mode='r')
299
  colors = np.load(cols_npy_path, mmap_mode='r')
300
  n_points = points.shape[0]
 
301
  output_text = f"Total points: {n_points:,}\n"
302
 
303
+ progress(0.25, desc="Identifying green points...")
 
 
304
  chunk = 1_000_000
305
  green_mask = np.zeros(n_points, dtype=bool)
306
+ for i in progress.tqdm(range(0, n_points, chunk), desc="Processing chunks..."):
307
  j = min(n_points, i + chunk)
308
  green_mask[i:j] = is_green_mask_from_rgb(colors[i:j])
309
  green_indices = np.nonzero(green_mask)[0]
 
311
  output_text += f"Green-colored points: {green_count:,}\n"
312
 
313
  if green_count == 0:
314
+ return "No green points detected.", None, None, gr.update(interactive=True)
 
 
315
 
316
+ progress(0.5, desc="Clustering green points...")
317
  if green_count <= 1000:
318
  max_dbscan_points = green_count
319
  elif green_count <= 5000:
 
323
  else:
324
  max_dbscan_points = 5000
325
 
 
326
  hsv_all = rgb_to_hsv_array(colors[green_indices])
327
  saturation = hsv_all[:, 1]
328
  order_by_sat = np.argsort(-saturation)
 
345
  dbscan_pts = points[green_indices]
346
  dbscan_map = green_indices
347
 
 
348
  est_eps = estimate_eps(dbscan_pts, sample_size=3000, k=8)
349
  eps1 = max(0.15, min(0.45, est_eps))
350
  eps2 = min(0.9, eps1 * 1.6)
 
352
 
353
  output_text += f"Estimated base eps: {eps1:.3f} (second-pass eps: {eps2:.3f}), min_samples: {min_samples}\n"
354
 
 
355
  clust1 = DBSCAN(eps=eps1, min_samples=min_samples).fit(dbscan_pts)
356
  labels1 = clust1.labels_
 
 
357
  clust2 = DBSCAN(eps=eps2, min_samples=max(6, int(min_samples / 2))).fit(dbscan_pts)
358
  labels2 = clust2.labels_
359
 
 
360
  combined_labels = labels1.copy()
361
  noise_mask = combined_labels == -1
362
  combined_labels[noise_mask] = labels2[noise_mask]
 
368
  continue
369
  norm_labels[combined_labels == lab] = nid
370
 
371
+ progress(0.75, desc="Refining clusters with region growing...")
 
 
372
  sampled_map = dbscan_map
373
  valid_labels = [lab for lab in np.unique(norm_labels) if lab != -1]
374
  green_pts_full = points[green_indices]
 
392
  for gp in neigh:
393
  full_label_assignment[int(gp)] = int(lab)
394
 
 
395
  final_label_positions = {}
396
  for pos, lab in enumerate(full_label_assignment):
397
  if lab == -1:
398
  continue
399
  final_label_positions.setdefault(int(lab), []).append(int(pos))
400
 
 
401
  clusters_info = []
402
  for lab, green_positions in final_label_positions.items():
403
  abs_indices = green_indices[green_positions]
 
405
  cluster_cols = np.asarray(colors[abs_indices])
406
  corners, centroid, length, width, height, zmin, zmax = get_bbox_and_metrics(cluster_pts)
407
  volume = length * width * height
 
408
  if height < MIN_HEIGHT or length > MAX_LENGTH or width > MAX_WIDTH:
409
  continue
410
  if volume < MIN_VOLUME:
 
413
  if density < MIN_DENSITY:
414
  continue
415
 
 
416
  temp_root = os.path.dirname(pts_npy_path)
417
  preview_fn = os.path.join(temp_root, f"obj_preview_lab{lab}_{uuid.uuid4().hex}.png")
418
  save_cluster_preview_png(cluster_pts, cluster_cols, preview_fn)
 
429
 
430
  output_text += f"Detected {len(clusters_info)} object-shaped clusters after filtering\n"
431
 
432
+ progress(0.9, desc="Generating 3D plot and Excel report...")
 
 
433
  if n_points > PREVIEW_MAX_POINTS:
434
  rng = np.random.default_rng(1)
435
  idx_preview = rng.choice(n_points, size=PREVIEW_MAX_POINTS, replace=False)
 
461
  add_bbox_to_fig(fig, info["corners"], color='red', width=4)
462
  fig.update_layout(scene=dict(aspectmode='data'), height=800, margin=dict(l=0, r=0, t=0, b=0))
463
 
 
464
  out_xlsx = None
465
  if clusters_info:
466
  out_xlsx = os.path.join(temp_root, "detected_objects_styled.xlsx")
467
  create_styled_excel(clusters_info, out_xlsx)
468
 
469
+ progress(1.0, desc="Analysis complete.")
470
+ return "Analysis complete.", fig, out_xlsx, gr.update(interactive=True)
471
 
472
  # Gradio Interface
473
  with gr.Blocks(title="Detection") as demo:
474
  gr.Markdown("# Green Dustbin & AIS Box Detection")
475
  gr.Markdown("Upload a `.pts` file to analyze the point cloud data.")
476
 
477
+ file_state = gr.State(value=[None, None])
478
 
479
  with gr.Row():
480
  file_input = gr.File(label="Upload .pts (X Y Z R G B)")
 
495
  analysis_button.click(
496
  fn=start_analysis,
497
  inputs=[file_state],
498
+ outputs=[output_text, output_plot, download_button, analysis_button]
 
 
 
 
499
  )
500
 
501
  demo.launch()