Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -94,24 +94,24 @@ def rgb_to_hsv_array(rgb_uint8):
|
|
| 94 |
minc = np.min(rgb, axis=1)
|
| 95 |
v = maxc
|
| 96 |
diff = maxc - minc
|
|
|
|
| 97 |
s = np.zeros_like(maxc)
|
| 98 |
-
|
| 99 |
-
|
| 100 |
h = np.zeros_like(maxc)
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
mask_r = (
|
| 109 |
-
mask_g = (
|
| 110 |
-
mask_b = (
|
| 111 |
-
|
| 112 |
-
h[mask_g] = 2.0 + (rc - bc)[mask_g]
|
| 113 |
-
h[mask_b] = 4.0 + (gc - rc)[mask_b]
|
| 114 |
h = (h / 6.0) % 1.0
|
|
|
|
| 115 |
return np.stack([h, s, v], axis=1)
|
| 116 |
|
| 117 |
def is_green_mask_from_rgb(colors_uint8):
|
|
@@ -180,23 +180,26 @@ def create_styled_excel(clusters_info, out_xlsx_path):
|
|
| 180 |
wb = openpyxl.Workbook()
|
| 181 |
ws = wb.active
|
| 182 |
ws.title = "Detected Green Objects"
|
| 183 |
-
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
| 185 |
bold = Font(bold=True)
|
| 186 |
center = Alignment(horizontal="center", vertical="center")
|
| 187 |
thin = Side(border_style="thin", color="000000")
|
| 188 |
border = Border(left=thin, right=thin, top=thin, bottom=thin)
|
| 189 |
row = 1
|
| 190 |
for idx, info in enumerate(clusters_info, start=1):
|
| 191 |
-
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=
|
| 192 |
ws.cell(row=row, column=1, value="Cloud Point Creation").font = Font(bold=True, size=12)
|
| 193 |
row += 1
|
| 194 |
-
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=
|
| 195 |
ws.cell(row=row, column=1, value=f"Object {idx}").font = Font(bold=True, size=11)
|
| 196 |
row += 1
|
| 197 |
headers = ["S.No", "Point X", "Coordinate X", "Point Y", "Coordinate Y", "Point Z", "Coordinate Z",
|
| 198 |
"CloudPoint Image", "CX1", "CY2", "CZ3", "Length", "Width", "Height",
|
| 199 |
-
"Assest Name", "Assest ID", "Assest Img", "Remarks"]
|
| 200 |
for c, h in enumerate(headers, start=1):
|
| 201 |
cell = ws.cell(row=row, column=c, value=h)
|
| 202 |
cell.font = bold
|
|
@@ -226,8 +229,9 @@ def create_styled_excel(clusters_info, out_xlsx_path):
|
|
| 226 |
ws.cell(row=row, column=16, value=ASSET_ID)
|
| 227 |
ws.cell(row=row, column=17, value="")
|
| 228 |
ws.cell(row=row, column=18, value="")
|
| 229 |
-
|
| 230 |
-
|
|
|
|
| 231 |
ws.cell(row=row, column=col_idx).border = border
|
| 232 |
row += 1
|
| 233 |
img_path = info.get("preview_path")
|
|
@@ -260,37 +264,46 @@ def estimate_eps(points_for_estimate, sample_size=3000, k=8):
|
|
| 260 |
return float(np.percentile(kth, 75))
|
| 261 |
|
| 262 |
# ---- Main processing function for Gradio ----
|
| 263 |
-
def
|
| 264 |
"""
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
Returns:
|
| 268 |
-
A tuple of (str, Plotly figure, str) for Gradio outputs.
|
| 269 |
"""
|
| 270 |
if uploaded_file is None:
|
| 271 |
return "No file uploaded.", None, None
|
| 272 |
|
| 273 |
-
# Use the path to the temporary file Gradio provides
|
| 274 |
-
orig_path = uploaded_file.name
|
| 275 |
-
|
| 276 |
-
# Create a unique temporary directory for output files
|
| 277 |
temp_root = os.path.join(tempfile.gettempdir(), f"temp_pts_{uuid.uuid4().hex}")
|
| 278 |
os.makedirs(temp_root, exist_ok=True)
|
| 279 |
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
cols_npy = os.path.join(temp_root, "cloud_colors.npy")
|
| 283 |
|
| 284 |
-
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
n_points = points.shape[0]
|
| 291 |
|
| 292 |
output_text = f"Total points: {n_points:,}\n"
|
| 293 |
|
|
|
|
|
|
|
| 294 |
# compute green mask in chunks
|
| 295 |
chunk = 1_000_000
|
| 296 |
green_mask = np.zeros(n_points, dtype=bool)
|
|
@@ -302,7 +315,9 @@ def process_point_cloud(uploaded_file):
|
|
| 302 |
output_text += f"Green-colored points: {green_count:,}\n"
|
| 303 |
|
| 304 |
if green_count == 0:
|
| 305 |
-
|
|
|
|
|
|
|
| 306 |
|
| 307 |
# ---- Auto-adjust max dbscan points based on green_count ----
|
| 308 |
if green_count <= 1000:
|
|
@@ -365,6 +380,8 @@ def process_point_cloud(uploaded_file):
|
|
| 365 |
continue
|
| 366 |
norm_labels[combined_labels == lab] = nid
|
| 367 |
|
|
|
|
|
|
|
| 368 |
# ---- Merge neighboring clusters that overlap after mapping back to full green set ----
|
| 369 |
sampled_map = dbscan_map
|
| 370 |
valid_labels = [lab for lab in np.unique(norm_labels) if lab != -1]
|
|
@@ -412,7 +429,9 @@ def process_point_cloud(uploaded_file):
|
|
| 412 |
density = cluster_pts.shape[0] / (volume + 1e-9)
|
| 413 |
if density < MIN_DENSITY:
|
| 414 |
continue
|
| 415 |
-
|
|
|
|
|
|
|
| 416 |
preview_fn = os.path.join(temp_root, f"obj_preview_lab{lab}_{uuid.uuid4().hex}.png")
|
| 417 |
save_cluster_preview_png(cluster_pts, cluster_cols, preview_fn)
|
| 418 |
clusters_info.append({
|
|
@@ -428,6 +447,8 @@ def process_point_cloud(uploaded_file):
|
|
| 428 |
|
| 429 |
output_text += f"Detected {len(clusters_info)} object-shaped clusters after filtering\n"
|
| 430 |
|
|
|
|
|
|
|
| 431 |
# ---- Interactive preview (downsampled) ----
|
| 432 |
if n_points > PREVIEW_MAX_POINTS:
|
| 433 |
rng = np.random.default_rng(1)
|
|
@@ -466,7 +487,7 @@ def process_point_cloud(uploaded_file):
|
|
| 466 |
out_xlsx = os.path.join(temp_root, "detected_objects_styled.xlsx")
|
| 467 |
create_styled_excel(clusters_info, out_xlsx)
|
| 468 |
|
| 469 |
-
|
| 470 |
|
| 471 |
|
| 472 |
# Gradio Interface
|
|
@@ -474,18 +495,32 @@ 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 |
with gr.Row():
|
| 478 |
file_input = gr.File(label="Upload .pts (X Y Z R G B)")
|
| 479 |
with gr.Column():
|
| 480 |
output_text = gr.Textbox(label="Processing Log", lines=10)
|
| 481 |
-
|
|
|
|
| 482 |
|
| 483 |
output_plot = gr.Plot(label="Interactive 3D Preview (downsampled)")
|
| 484 |
|
| 485 |
file_input.upload(
|
| 486 |
-
fn=
|
| 487 |
inputs=[file_input],
|
| 488 |
-
outputs=[output_text,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
)
|
| 490 |
|
| 491 |
demo.launch()
|
|
|
|
| 94 |
minc = np.min(rgb, axis=1)
|
| 95 |
v = maxc
|
| 96 |
diff = maxc - minc
|
| 97 |
+
|
| 98 |
s = np.zeros_like(maxc)
|
| 99 |
+
s[maxc > 0] = diff[maxc > 0] / maxc[maxc > 0]
|
| 100 |
+
|
| 101 |
h = np.zeros_like(maxc)
|
| 102 |
+
|
| 103 |
+
# Create masks to determine which color channel is dominant
|
| 104 |
+
mask_r = (rgb[:, 0] == maxc) & (diff > 0)
|
| 105 |
+
mask_g = (rgb[:, 1] == maxc) & (diff > 0)
|
| 106 |
+
mask_b = (rgb[:, 2] == maxc) & (diff > 0)
|
| 107 |
+
|
| 108 |
+
# Calculate hue based on dominant channel
|
| 109 |
+
h[mask_r] = (rgb[mask_r, 1] - rgb[mask_r, 2]) / diff[mask_r]
|
| 110 |
+
h[mask_g] = 2.0 + (rgb[mask_g, 2] - rgb[mask_g, 0]) / diff[mask_g]
|
| 111 |
+
h[mask_b] = 4.0 + (rgb[mask_b, 0] - rgb[mask_b, 1]) / diff[mask_b]
|
| 112 |
+
|
|
|
|
|
|
|
| 113 |
h = (h / 6.0) % 1.0
|
| 114 |
+
|
| 115 |
return np.stack([h, s, v], axis=1)
|
| 116 |
|
| 117 |
def is_green_mask_from_rgb(colors_uint8):
|
|
|
|
| 180 |
wb = openpyxl.Workbook()
|
| 181 |
ws = wb.active
|
| 182 |
ws.title = "Detected Green Objects"
|
| 183 |
+
|
| 184 |
+
# Updated color palette
|
| 185 |
+
gray_fill = PatternFill(start_color="F2F2F2", end_color="F2F2F2", fill_type="solid")
|
| 186 |
+
header_fill = PatternFill(start_color="E0E0E0", end_color="E0E0E0", fill_type="solid")
|
| 187 |
+
|
| 188 |
bold = Font(bold=True)
|
| 189 |
center = Alignment(horizontal="center", vertical="center")
|
| 190 |
thin = Side(border_style="thin", color="000000")
|
| 191 |
border = Border(left=thin, right=thin, top=thin, bottom=thin)
|
| 192 |
row = 1
|
| 193 |
for idx, info in enumerate(clusters_info, start=1):
|
| 194 |
+
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=19)
|
| 195 |
ws.cell(row=row, column=1, value="Cloud Point Creation").font = Font(bold=True, size=12)
|
| 196 |
row += 1
|
| 197 |
+
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=19)
|
| 198 |
ws.cell(row=row, column=1, value=f"Object {idx}").font = Font(bold=True, size=11)
|
| 199 |
row += 1
|
| 200 |
headers = ["S.No", "Point X", "Coordinate X", "Point Y", "Coordinate Y", "Point Z", "Coordinate Z",
|
| 201 |
"CloudPoint Image", "CX1", "CY2", "CZ3", "Length", "Width", "Height",
|
| 202 |
+
"Assest Name", "Assest ID", "Assest Img", "Remarks", "Check"] # Added "Check"
|
| 203 |
for c, h in enumerate(headers, start=1):
|
| 204 |
cell = ws.cell(row=row, column=c, value=h)
|
| 205 |
cell.font = bold
|
|
|
|
| 229 |
ws.cell(row=row, column=16, value=ASSET_ID)
|
| 230 |
ws.cell(row=row, column=17, value="")
|
| 231 |
ws.cell(row=row, column=18, value="")
|
| 232 |
+
ws.cell(row=row, column=19, value="") # Added blank "Check" column
|
| 233 |
+
for col_idx in range(1, 20):
|
| 234 |
+
ws.cell(row=row, column=col_idx).fill = gray_fill
|
| 235 |
ws.cell(row=row, column=col_idx).border = border
|
| 236 |
row += 1
|
| 237 |
img_path = info.get("preview_path")
|
|
|
|
| 264 |
return float(np.percentile(kth, 75))
|
| 265 |
|
| 266 |
# ---- Main processing function for Gradio ----
|
| 267 |
+
def handle_file_upload(uploaded_file):
|
| 268 |
"""
|
| 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)
|
| 276 |
|
| 277 |
+
pts_npy_path = os.path.join(temp_root, "cloud_points.npy")
|
| 278 |
+
cols_npy_path = os.path.join(temp_root, "cloud_colors.npy")
|
|
|
|
| 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)
|
|
|
|
| 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:
|
|
|
|
| 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]
|
|
|
|
| 429 |
density = cluster_pts.shape[0] / (volume + 1e-9)
|
| 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)
|
| 437 |
clusters_info.append({
|
|
|
|
| 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)
|
|
|
|
| 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
|
|
|
|
| 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)")
|
| 502 |
with gr.Column():
|
| 503 |
output_text = gr.Textbox(label="Processing Log", lines=10)
|
| 504 |
+
analysis_button = gr.Button("Start Analysis", interactive=False)
|
| 505 |
+
download_button = gr.DownloadButton("Download styled Excel", visible=False)
|
| 506 |
|
| 507 |
output_plot = gr.Plot(label="Interactive 3D Preview (downsampled)")
|
| 508 |
|
| 509 |
file_input.upload(
|
| 510 |
+
fn=handle_file_upload,
|
| 511 |
inputs=[file_input],
|
| 512 |
+
outputs=[output_text, analysis_button, download_button, file_state],
|
| 513 |
+
queue=False
|
| 514 |
+
)
|
| 515 |
+
|
| 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()
|