Spaces:
Sleeping
Sleeping
update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
# app.py -- complete, self-contained application
|
| 2 |
import gradio as gr
|
| 3 |
import numpy as np
|
| 4 |
import os
|
|
@@ -22,8 +21,8 @@ MIN_HEIGHT = 0.05
|
|
| 22 |
MAX_LENGTH = 2.0
|
| 23 |
MAX_WIDTH = 2.0
|
| 24 |
|
| 25 |
-
ASSET_NAME,ASSET_NAME1 = "Green Object","AIS Box"
|
| 26 |
-
ASSET_ID
|
| 27 |
|
| 28 |
# DBSCAN defaults (auto-tuned below)
|
| 29 |
DBSCAN_MIN_SAMPLES_DEFAULT = 12
|
|
@@ -43,60 +42,70 @@ MIN_DENSITY = 5
|
|
| 43 |
|
| 44 |
# ---- Helper functions ----
|
| 45 |
def pts_to_npy(file_path, pts_npy, cols_npy):
|
|
|
|
| 46 |
pts, cols = [], []
|
| 47 |
-
with open(file_path,'r') as f:
|
| 48 |
for line in f:
|
| 49 |
-
line=line.strip()
|
| 50 |
-
if not line or line.startswith('#'):
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
| 53 |
try:
|
| 54 |
-
x,y,z = map(float, parts[:3])
|
| 55 |
-
r,g,b = map(int, parts[3:6])
|
| 56 |
-
except:
|
| 57 |
continue
|
| 58 |
-
pts.append((x,y,z))
|
|
|
|
| 59 |
pts = np.asarray(pts, dtype=np.float32)
|
| 60 |
cols = np.asarray(cols, dtype=np.uint8)
|
| 61 |
-
np.save(pts_npy, pts)
|
|
|
|
| 62 |
return pts_npy, cols_npy
|
| 63 |
|
| 64 |
def rgb_to_hsv_array(rgb_uint8):
|
| 65 |
-
|
|
|
|
| 66 |
maxc = np.max(rgb, axis=1)
|
| 67 |
minc = np.min(rgb, axis=1)
|
| 68 |
v = maxc
|
| 69 |
diff = maxc - minc
|
| 70 |
s = np.zeros_like(maxc)
|
| 71 |
nonzero = maxc > 1e-8
|
| 72 |
-
s[nonzero] = diff[nonzero]/(maxc[nonzero]+1e-8)
|
| 73 |
h = np.zeros_like(maxc)
|
| 74 |
-
rc = np.zeros_like(maxc)
|
|
|
|
|
|
|
| 75 |
mask = diff > 1e-8
|
| 76 |
-
rc[mask] = (maxc[mask]-rgb[mask,0]) / diff[mask]
|
| 77 |
-
gc[mask] = (maxc[mask]-rgb[mask,1]) / diff[mask]
|
| 78 |
-
bc[mask] = (maxc[mask]-rgb[mask,2]) / diff[mask]
|
| 79 |
-
mask_r = (maxc==rgb[:,0]) & mask
|
| 80 |
-
mask_g = (maxc==rgb[:,1]) & mask
|
| 81 |
-
mask_b = (maxc==rgb[:,2]) & mask
|
| 82 |
-
h[mask_r] = (bc-gc)[mask_r]
|
| 83 |
-
h[mask_g] = 2.0 + (rc-bc)[mask_g]
|
| 84 |
-
h[mask_b] = 4.0 + (gc-rc)[mask_b]
|
| 85 |
-
h = (h/6.0) % 1.0
|
| 86 |
-
return np.stack([h,s,v], axis=1)
|
| 87 |
|
| 88 |
def is_green_mask_from_rgb(colors_uint8):
|
|
|
|
| 89 |
hsv = rgb_to_hsv_array(colors_uint8)
|
| 90 |
-
h,s,v = hsv[:,0], hsv[:,1], hsv[:,2]
|
| 91 |
return (h > 0.22) & (h < 0.48) & (s > 0.22) & (v > 0.12)
|
| 92 |
|
| 93 |
def get_bbox_and_metrics(cluster_pts):
|
|
|
|
| 94 |
min_pt = cluster_pts.min(axis=0)
|
| 95 |
max_pt = cluster_pts.max(axis=0)
|
| 96 |
centroid = cluster_pts.mean(axis=0)
|
| 97 |
-
length = float(max_pt[0]-min_pt[0])
|
| 98 |
-
width = float(max_pt[1]-min_pt[1])
|
| 99 |
-
height = float(max_pt[2]-min_pt[2])
|
| 100 |
corners = np.array([
|
| 101 |
[min_pt[0], min_pt[1], min_pt[2]],
|
| 102 |
[min_pt[0], min_pt[1], max_pt[2]],
|
|
@@ -110,8 +119,9 @@ def get_bbox_and_metrics(cluster_pts):
|
|
| 110 |
return corners, centroid, length, width, height, float(min_pt[2]), float(max_pt[2])
|
| 111 |
|
| 112 |
def add_bbox_to_fig(fig, corners, color='red', width=4):
|
| 113 |
-
|
| 114 |
-
|
|
|
|
| 115 |
fig.add_trace(go.Scatter3d(
|
| 116 |
x=[corners[s][0], corners[e][0]],
|
| 117 |
y=[corners[s][1], corners[e][1]],
|
|
@@ -121,28 +131,30 @@ def add_bbox_to_fig(fig, corners, color='red', width=4):
|
|
| 121 |
showlegend=False
|
| 122 |
))
|
| 123 |
|
| 124 |
-
def save_cluster_preview_png(cluster_pts, cluster_cols, out_path, size=(500,500), downsample=200000):
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
| 129 |
pts, cols = cluster_pts[idx], cluster_cols[idx]
|
| 130 |
else:
|
| 131 |
pts, cols = cluster_pts, cluster_cols
|
| 132 |
fig = go.Figure()
|
| 133 |
fig.add_trace(go.Scatter3d(
|
| 134 |
-
x=pts[:,0], y=pts[:,1], z=pts[:,2],
|
| 135 |
-
mode='markers', marker=dict(size=2, color=["rgb(%d,%d,%d)"%tuple(c) for c in cols]),
|
| 136 |
showlegend=False
|
| 137 |
))
|
| 138 |
fig.update_layout(scene=dict(aspectmode='data', xaxis=dict(visible=False), yaxis=dict(visible=False), zaxis=dict(visible=False)),
|
| 139 |
-
margin=dict(l=0,r=0,t=0,b=0), width=size[0], height=size[1], paper_bgcolor='white')
|
| 140 |
img_bytes = pio.to_image(fig, format='png')
|
| 141 |
with open(out_path, 'wb') as f:
|
| 142 |
f.write(img_bytes)
|
| 143 |
return out_path
|
| 144 |
|
| 145 |
def create_styled_excel(clusters_info, out_xlsx_path):
|
|
|
|
| 146 |
wb = openpyxl.Workbook()
|
| 147 |
ws = wb.active
|
| 148 |
ws.title = "Detected Green Objects"
|
|
@@ -151,52 +163,65 @@ def create_styled_excel(clusters_info, out_xlsx_path):
|
|
| 151 |
bold = Font(bold=True)
|
| 152 |
center = Alignment(horizontal="center", vertical="center")
|
| 153 |
thin = Side(border_style="thin", color="000000")
|
| 154 |
-
border = Border(left=thin,right=thin,top=thin,bottom=thin)
|
| 155 |
row = 1
|
| 156 |
for idx, info in enumerate(clusters_info, start=1):
|
| 157 |
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=18)
|
| 158 |
ws.cell(row=row, column=1, value="Cloud Point Creation").font = Font(bold=True, size=12)
|
| 159 |
row += 1
|
| 160 |
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=18)
|
| 161 |
-
ws.cell(row=row,column=1,value=f"Object {idx}").font = Font(bold=True, size=11)
|
| 162 |
row += 1
|
| 163 |
-
headers=["S.No","Point X","Coordinate X","Point Y","Coordinate Y","Point Z","Coordinate Z",
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
for c,h in enumerate(headers, start=1):
|
| 167 |
-
cell=ws.cell(row=row, column=c, value=h)
|
| 168 |
-
cell.font
|
|
|
|
|
|
|
|
|
|
| 169 |
row += 1
|
| 170 |
-
corners = info["corners"]
|
| 171 |
-
|
|
|
|
| 172 |
for i in range(8):
|
| 173 |
c = corners[i]
|
| 174 |
-
ws.cell(row=row,column=1,value=i+1)
|
| 175 |
-
ws.cell(row=row,column=2,
|
| 176 |
-
ws.cell(row=row,
|
| 177 |
-
ws.cell(row=row,
|
| 178 |
-
ws.cell(row=row,
|
| 179 |
-
ws.cell(row=row,column=
|
| 180 |
-
ws.cell(row=row,
|
| 181 |
-
ws.cell(row=row,column=
|
| 182 |
-
ws.cell(row=row,column=
|
| 183 |
-
ws.cell(row=row,column=
|
| 184 |
-
|
| 185 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
row += 1
|
| 187 |
img_path = info.get("preview_path")
|
| 188 |
if img_path and os.path.exists(img_path):
|
| 189 |
image = XLImage(img_path)
|
| 190 |
-
for r_i in range(row-8,row):
|
| 191 |
-
ws.row_dimensions[r_i].height=60
|
| 192 |
-
ws.column_dimensions['H'].width=20
|
| 193 |
-
ws.add_image(image, f"H{row-8}")
|
| 194 |
row += 1
|
| 195 |
wb.save(out_xlsx_path)
|
| 196 |
return out_xlsx_path
|
| 197 |
|
| 198 |
# ---- Utility: estimate eps robustly using k-distance percentile ----
|
| 199 |
def estimate_eps(points_for_estimate, sample_size=3000, k=8):
|
|
|
|
| 200 |
n = points_for_estimate.shape[0]
|
| 201 |
if n <= k:
|
| 202 |
return 0.3
|
|
@@ -212,7 +237,14 @@ def estimate_eps(points_for_estimate, sample_size=3000, k=8):
|
|
| 212 |
kth = dists[:, -1]
|
| 213 |
return float(np.percentile(kth, 75))
|
| 214 |
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
if uploaded_file is None:
|
| 217 |
return "No file uploaded.", None, None
|
| 218 |
|
|
@@ -238,7 +270,7 @@ def process_file(uploaded_file):
|
|
| 238 |
chunk = 1_000_000
|
| 239 |
green_mask = np.zeros(n_points, dtype=bool)
|
| 240 |
for i in range(0, n_points, chunk):
|
| 241 |
-
j = min(n_points, i+chunk)
|
| 242 |
green_mask[i:j] = is_green_mask_from_rgb(colors[i:j])
|
| 243 |
green_indices = np.nonzero(green_mask)[0]
|
| 244 |
green_count = green_indices.shape[0]
|
|
@@ -259,7 +291,7 @@ def process_file(uploaded_file):
|
|
| 259 |
|
| 260 |
# ---- Saturation prioritized sampling (if we must sample) ----
|
| 261 |
hsv_all = rgb_to_hsv_array(colors[green_indices])
|
| 262 |
-
saturation = hsv_all[:,1]
|
| 263 |
order_by_sat = np.argsort(-saturation)
|
| 264 |
n_priority = int(len(order_by_sat) * SAT_PRIORITY_FRAC)
|
| 265 |
priority_idx = order_by_sat[:n_priority]
|
|
@@ -285,7 +317,7 @@ def process_file(uploaded_file):
|
|
| 285 |
eps1 = max(0.15, min(0.45, est_eps))
|
| 286 |
eps2 = min(0.9, eps1 * 1.6)
|
| 287 |
min_samples = DBSCAN_MIN_SAMPLES_DEFAULT
|
| 288 |
-
|
| 289 |
output_text += f"Estimated base eps: {eps1:.3f} (second-pass eps: {eps2:.3f}), min_samples: {min_samples}\n"
|
| 290 |
|
| 291 |
# First pass
|
|
@@ -293,7 +325,7 @@ def process_file(uploaded_file):
|
|
| 293 |
labels1 = clust1.labels_
|
| 294 |
|
| 295 |
# Second pass (coarser)
|
| 296 |
-
clust2 = DBSCAN(eps=eps2, min_samples=max(6, int(min_samples/2))).fit(dbscan_pts)
|
| 297 |
labels2 = clust2.labels_
|
| 298 |
|
| 299 |
# Combine clusters
|
|
@@ -304,7 +336,8 @@ def process_file(uploaded_file):
|
|
| 304 |
label_map = {lab: i for i, lab in enumerate(unique) if lab != -1}
|
| 305 |
norm_labels = np.full_like(combined_labels, fill_value=-1)
|
| 306 |
for lab, nid in label_map.items():
|
| 307 |
-
if lab == -1:
|
|
|
|
| 308 |
norm_labels[combined_labels == lab] = nid
|
| 309 |
|
| 310 |
# ---- Merge neighboring clusters that overlap after mapping back to full green set ----
|
|
@@ -317,11 +350,13 @@ def process_file(uploaded_file):
|
|
| 317 |
|
| 318 |
for lab in valid_labels:
|
| 319 |
mask_sample = (norm_labels == lab)
|
| 320 |
-
if mask_sample.sum() == 0:
|
|
|
|
| 321 |
sample_pos_in_db = np.nonzero(mask_sample)[0]
|
| 322 |
global_idxs = sampled_map[sample_pos_in_db]
|
| 323 |
green_positions = [global_to_greenpos[int(g)] for g in global_idxs if int(g) in global_to_greenpos]
|
| 324 |
-
if len(green_positions) == 0:
|
|
|
|
| 325 |
seeds = green_pts_full[green_positions]
|
| 326 |
radius = eps1 * REGION_GROW_FACTOR
|
| 327 |
neigh_lists = bt.query_radius(seeds, r=radius)
|
|
@@ -332,7 +367,8 @@ def process_file(uploaded_file):
|
|
| 332 |
# After region grow, group final labels by scanning full_label_assignment
|
| 333 |
final_label_positions = {}
|
| 334 |
for pos, lab in enumerate(full_label_assignment):
|
| 335 |
-
if lab == -1:
|
|
|
|
| 336 |
final_label_positions.setdefault(int(lab), []).append(int(pos))
|
| 337 |
|
| 338 |
# Build clusters_info
|
|
@@ -351,7 +387,7 @@ def process_file(uploaded_file):
|
|
| 351 |
density = cluster_pts.shape[0] / (volume + 1e-9)
|
| 352 |
if density < MIN_DENSITY:
|
| 353 |
continue
|
| 354 |
-
|
| 355 |
preview_fn = os.path.join(temp_root, f"obj_preview_lab{lab}_{uuid.uuid4().hex}.png")
|
| 356 |
save_cluster_preview_png(cluster_pts, cluster_cols, preview_fn)
|
| 357 |
clusters_info.append({
|
|
@@ -371,36 +407,39 @@ def process_file(uploaded_file):
|
|
| 371 |
if n_points > PREVIEW_MAX_POINTS:
|
| 372 |
rng = np.random.default_rng(1)
|
| 373 |
idx_preview = rng.choice(n_points, size=PREVIEW_MAX_POINTS, replace=False)
|
| 374 |
-
preview_points = points[idx_preview]
|
|
|
|
| 375 |
else:
|
| 376 |
-
preview_points = points[:]
|
| 377 |
-
|
|
|
|
| 378 |
|
| 379 |
if green_count > PREVIEW_GREEN_MAX:
|
| 380 |
rng = np.random.default_rng(2)
|
| 381 |
idxg = rng.choice(green_indices, size=PREVIEW_GREEN_MAX, replace=False)
|
| 382 |
-
preview_green_points = points[idxg]
|
|
|
|
| 383 |
else:
|
| 384 |
-
preview_green_points = points[green_indices]
|
| 385 |
-
|
|
|
|
| 386 |
|
| 387 |
fig = go.Figure()
|
| 388 |
-
fig.add_trace(go.Scatter3d(x=preview_points[:,0], y=preview_points[:,1], z=preview_points[:,2],
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
fig.add_trace(go.Scatter3d(x=preview_green_points[:,0], y=preview_green_points[:,1], z=preview_green_points[:,2],
|
| 392 |
-
|
| 393 |
-
|
| 394 |
for info in clusters_info:
|
| 395 |
add_bbox_to_fig(fig, info["corners"], color='red', width=4)
|
| 396 |
-
fig.update_layout(scene=dict(aspectmode='data'), height=800, margin=dict(l=0,r=0,t=0,b=0))
|
| 397 |
|
| 398 |
# ---- Excel export ----
|
|
|
|
| 399 |
if clusters_info:
|
| 400 |
out_xlsx = os.path.join(temp_root, "detected_objects_styled.xlsx")
|
| 401 |
create_styled_excel(clusters_info, out_xlsx)
|
| 402 |
-
else:
|
| 403 |
-
out_xlsx = None
|
| 404 |
|
| 405 |
return output_text, fig, out_xlsx
|
| 406 |
|
|
@@ -419,9 +458,9 @@ with gr.Blocks(title="Detection") as demo:
|
|
| 419 |
output_plot = gr.Plot(label="Interactive 3D Preview (downsampled)")
|
| 420 |
|
| 421 |
file_input.upload(
|
| 422 |
-
fn=
|
| 423 |
inputs=[file_input],
|
| 424 |
outputs=[output_text, output_plot, download_button]
|
| 425 |
)
|
| 426 |
|
| 427 |
-
demo.launch(
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import numpy as np
|
| 3 |
import os
|
|
|
|
| 21 |
MAX_LENGTH = 2.0
|
| 22 |
MAX_WIDTH = 2.0
|
| 23 |
|
| 24 |
+
ASSET_NAME, ASSET_NAME1 = "Green Object", "AIS Box"
|
| 25 |
+
ASSET_ID, ASSET_ID1 = "3051047", "2859571"
|
| 26 |
|
| 27 |
# DBSCAN defaults (auto-tuned below)
|
| 28 |
DBSCAN_MIN_SAMPLES_DEFAULT = 12
|
|
|
|
| 42 |
|
| 43 |
# ---- Helper functions ----
|
| 44 |
def pts_to_npy(file_path, pts_npy, cols_npy):
|
| 45 |
+
"""Converts a .pts file to a numpy array for faster processing."""
|
| 46 |
pts, cols = [], []
|
| 47 |
+
with open(file_path, 'r') as f:
|
| 48 |
for line in f:
|
| 49 |
+
line = line.strip()
|
| 50 |
+
if not line or line.startswith('#'):
|
| 51 |
+
continue
|
| 52 |
+
parts = line.split()
|
| 53 |
+
if len(parts) < 6:
|
| 54 |
+
continue
|
| 55 |
try:
|
| 56 |
+
x, y, z = map(float, parts[:3])
|
| 57 |
+
r, g, b = map(int, parts[3:6])
|
| 58 |
+
except (ValueError, IndexError):
|
| 59 |
continue
|
| 60 |
+
pts.append((x, y, z))
|
| 61 |
+
cols.append((r, g, b))
|
| 62 |
pts = np.asarray(pts, dtype=np.float32)
|
| 63 |
cols = np.asarray(cols, dtype=np.uint8)
|
| 64 |
+
np.save(pts_npy, pts)
|
| 65 |
+
np.save(cols_npy, cols)
|
| 66 |
return pts_npy, cols_npy
|
| 67 |
|
| 68 |
def rgb_to_hsv_array(rgb_uint8):
|
| 69 |
+
"""Converts an array of RGB values to HSV."""
|
| 70 |
+
rgb = rgb_uint8.astype(np.float32) / 255.0
|
| 71 |
maxc = np.max(rgb, axis=1)
|
| 72 |
minc = np.min(rgb, axis=1)
|
| 73 |
v = maxc
|
| 74 |
diff = maxc - minc
|
| 75 |
s = np.zeros_like(maxc)
|
| 76 |
nonzero = maxc > 1e-8
|
| 77 |
+
s[nonzero] = diff[nonzero] / (maxc[nonzero] + 1e-8)
|
| 78 |
h = np.zeros_like(maxc)
|
| 79 |
+
rc = np.zeros_like(maxc)
|
| 80 |
+
gc = np.zeros_like(maxc)
|
| 81 |
+
bc = np.zeros_like(maxc)
|
| 82 |
mask = diff > 1e-8
|
| 83 |
+
rc[mask] = (maxc[mask] - rgb[mask, 0]) / diff[mask]
|
| 84 |
+
gc[mask] = (maxc[mask] - rgb[mask, 1]) / diff[mask]
|
| 85 |
+
bc[mask] = (maxc[mask] - rgb[mask, 2]) / diff[mask]
|
| 86 |
+
mask_r = (maxc == rgb[:, 0]) & mask
|
| 87 |
+
mask_g = (maxc == rgb[:, 1]) & mask
|
| 88 |
+
mask_b = (maxc == rgb[:, 2]) & mask
|
| 89 |
+
h[mask_r] = (bc - gc)[mask_r]
|
| 90 |
+
h[mask_g] = 2.0 + (rc - bc)[mask_g]
|
| 91 |
+
h[mask_b] = 4.0 + (gc - rc)[mask_b]
|
| 92 |
+
h = (h / 6.0) % 1.0
|
| 93 |
+
return np.stack([h, s, v], axis=1)
|
| 94 |
|
| 95 |
def is_green_mask_from_rgb(colors_uint8):
|
| 96 |
+
"""Generates a boolean mask to identify green points based on HSV values."""
|
| 97 |
hsv = rgb_to_hsv_array(colors_uint8)
|
| 98 |
+
h, s, v = hsv[:, 0], hsv[:, 1], hsv[:, 2]
|
| 99 |
return (h > 0.22) & (h < 0.48) & (s > 0.22) & (v > 0.12)
|
| 100 |
|
| 101 |
def get_bbox_and_metrics(cluster_pts):
|
| 102 |
+
"""Calculates the bounding box, centroid, and dimensions of a point cluster."""
|
| 103 |
min_pt = cluster_pts.min(axis=0)
|
| 104 |
max_pt = cluster_pts.max(axis=0)
|
| 105 |
centroid = cluster_pts.mean(axis=0)
|
| 106 |
+
length = float(max_pt[0] - min_pt[0])
|
| 107 |
+
width = float(max_pt[1] - min_pt[1])
|
| 108 |
+
height = float(max_pt[2] - min_pt[2])
|
| 109 |
corners = np.array([
|
| 110 |
[min_pt[0], min_pt[1], min_pt[2]],
|
| 111 |
[min_pt[0], min_pt[1], max_pt[2]],
|
|
|
|
| 119 |
return corners, centroid, length, width, height, float(min_pt[2]), float(max_pt[2])
|
| 120 |
|
| 121 |
def add_bbox_to_fig(fig, corners, color='red', width=4):
|
| 122 |
+
"""Adds a 3D bounding box to a Plotly figure."""
|
| 123 |
+
edges = [(0, 1), (1, 3), (3, 2), (2, 0), (4, 5), (5, 7), (7, 6), (6, 4), (0, 4), (1, 5), (2, 6), (3, 7)]
|
| 124 |
+
for s, e in edges:
|
| 125 |
fig.add_trace(go.Scatter3d(
|
| 126 |
x=[corners[s][0], corners[e][0]],
|
| 127 |
y=[corners[s][1], corners[e][1]],
|
|
|
|
| 131 |
showlegend=False
|
| 132 |
))
|
| 133 |
|
| 134 |
+
def save_cluster_preview_png(cluster_pts, cluster_cols, out_path, size=(500, 500), downsample=200000):
|
| 135 |
+
"""Creates and saves a preview PNG of a point cluster."""
|
| 136 |
+
n = cluster_pts.shape[0]
|
| 137 |
+
if n > downsample:
|
| 138 |
+
rng = np.random.default_rng(0)
|
| 139 |
+
idx = rng.choice(n, size=downsample, replace=False)
|
| 140 |
pts, cols = cluster_pts[idx], cluster_cols[idx]
|
| 141 |
else:
|
| 142 |
pts, cols = cluster_pts, cluster_cols
|
| 143 |
fig = go.Figure()
|
| 144 |
fig.add_trace(go.Scatter3d(
|
| 145 |
+
x=pts[:, 0], y=pts[:, 1], z=pts[:, 2],
|
| 146 |
+
mode='markers', marker=dict(size=2, color=["rgb(%d,%d,%d)" % tuple(c) for c in cols]),
|
| 147 |
showlegend=False
|
| 148 |
))
|
| 149 |
fig.update_layout(scene=dict(aspectmode='data', xaxis=dict(visible=False), yaxis=dict(visible=False), zaxis=dict(visible=False)),
|
| 150 |
+
margin=dict(l=0, r=0, t=0, b=0), width=size[0], height=size[1], paper_bgcolor='white')
|
| 151 |
img_bytes = pio.to_image(fig, format='png')
|
| 152 |
with open(out_path, 'wb') as f:
|
| 153 |
f.write(img_bytes)
|
| 154 |
return out_path
|
| 155 |
|
| 156 |
def create_styled_excel(clusters_info, out_xlsx_path):
|
| 157 |
+
"""Creates a styled Excel file with cluster information and images."""
|
| 158 |
wb = openpyxl.Workbook()
|
| 159 |
ws = wb.active
|
| 160 |
ws.title = "Detected Green Objects"
|
|
|
|
| 163 |
bold = Font(bold=True)
|
| 164 |
center = Alignment(horizontal="center", vertical="center")
|
| 165 |
thin = Side(border_style="thin", color="000000")
|
| 166 |
+
border = Border(left=thin, right=thin, top=thin, bottom=thin)
|
| 167 |
row = 1
|
| 168 |
for idx, info in enumerate(clusters_info, start=1):
|
| 169 |
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=18)
|
| 170 |
ws.cell(row=row, column=1, value="Cloud Point Creation").font = Font(bold=True, size=12)
|
| 171 |
row += 1
|
| 172 |
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=18)
|
| 173 |
+
ws.cell(row=row, column=1, value=f"Object {idx}").font = Font(bold=True, size=11)
|
| 174 |
row += 1
|
| 175 |
+
headers = ["S.No", "Point X", "Coordinate X", "Point Y", "Coordinate Y", "Point Z", "Coordinate Z",
|
| 176 |
+
"CloudPoint Image", "CX1", "CY2", "CZ3", "Length", "Width", "Height",
|
| 177 |
+
"Assest Name", "Assest ID", "Assest Img", "Remarks"]
|
| 178 |
+
for c, h in enumerate(headers, start=1):
|
| 179 |
+
cell = ws.cell(row=row, column=c, value=h)
|
| 180 |
+
cell.font = bold
|
| 181 |
+
cell.fill = header_fill
|
| 182 |
+
cell.alignment = center
|
| 183 |
+
cell.border = border
|
| 184 |
row += 1
|
| 185 |
+
corners = info["corners"]
|
| 186 |
+
centroid = info["centroid"]
|
| 187 |
+
length, width, height = info["length"], info["width"], info["height"]
|
| 188 |
for i in range(8):
|
| 189 |
c = corners[i]
|
| 190 |
+
ws.cell(row=row, column=1, value=i + 1)
|
| 191 |
+
ws.cell(row=row, column=2, value=c[0])
|
| 192 |
+
ws.cell(row=row, column=3, value=c[0])
|
| 193 |
+
ws.cell(row=row, column=4, value=c[1])
|
| 194 |
+
ws.cell(row=row, column=5, value=c[1])
|
| 195 |
+
ws.cell(row=row, column=6, value=c[2])
|
| 196 |
+
ws.cell(row=row, column=7, value=c[2])
|
| 197 |
+
ws.cell(row=row, column=9, value=round(centroid[0], 4))
|
| 198 |
+
ws.cell(row=row, column=10, value=round(centroid[1], 4))
|
| 199 |
+
ws.cell(row=row, column=11, value=round(centroid[2], 4))
|
| 200 |
+
ws.cell(row=row, column=12, value=round(length, 4))
|
| 201 |
+
ws.cell(row=row, column=13, value=round(width, 4))
|
| 202 |
+
ws.cell(row=row, column=14, value=round(height, 4))
|
| 203 |
+
ws.cell(row=row, column=15, value=ASSET_NAME)
|
| 204 |
+
ws.cell(row=row, column=16, value=ASSET_ID)
|
| 205 |
+
ws.cell(row=row, column=17, value="")
|
| 206 |
+
ws.cell(row=row, column=18, value="")
|
| 207 |
+
for col_idx in range(1, 19):
|
| 208 |
+
ws.cell(row=row, column=col_idx).fill = blue_fill
|
| 209 |
+
ws.cell(row=row, column=col_idx).border = border
|
| 210 |
row += 1
|
| 211 |
img_path = info.get("preview_path")
|
| 212 |
if img_path and os.path.exists(img_path):
|
| 213 |
image = XLImage(img_path)
|
| 214 |
+
for r_i in range(row - 8, row):
|
| 215 |
+
ws.row_dimensions[r_i].height = 60
|
| 216 |
+
ws.column_dimensions['H'].width = 20
|
| 217 |
+
ws.add_image(image, f"H{row - 8}")
|
| 218 |
row += 1
|
| 219 |
wb.save(out_xlsx_path)
|
| 220 |
return out_xlsx_path
|
| 221 |
|
| 222 |
# ---- Utility: estimate eps robustly using k-distance percentile ----
|
| 223 |
def estimate_eps(points_for_estimate, sample_size=3000, k=8):
|
| 224 |
+
"""Estimates the optimal epsilon value for DBSCAN."""
|
| 225 |
n = points_for_estimate.shape[0]
|
| 226 |
if n <= k:
|
| 227 |
return 0.3
|
|
|
|
| 237 |
kth = dists[:, -1]
|
| 238 |
return float(np.percentile(kth, 75))
|
| 239 |
|
| 240 |
+
# ---- Main processing function for Gradio ----
|
| 241 |
+
def process_point_cloud(uploaded_file):
|
| 242 |
+
"""
|
| 243 |
+
Main function to process the uploaded .pts file.
|
| 244 |
+
|
| 245 |
+
Returns:
|
| 246 |
+
A tuple of (str, Plotly figure, str) for Gradio outputs.
|
| 247 |
+
"""
|
| 248 |
if uploaded_file is None:
|
| 249 |
return "No file uploaded.", None, None
|
| 250 |
|
|
|
|
| 270 |
chunk = 1_000_000
|
| 271 |
green_mask = np.zeros(n_points, dtype=bool)
|
| 272 |
for i in range(0, n_points, chunk):
|
| 273 |
+
j = min(n_points, i + chunk)
|
| 274 |
green_mask[i:j] = is_green_mask_from_rgb(colors[i:j])
|
| 275 |
green_indices = np.nonzero(green_mask)[0]
|
| 276 |
green_count = green_indices.shape[0]
|
|
|
|
| 291 |
|
| 292 |
# ---- Saturation prioritized sampling (if we must sample) ----
|
| 293 |
hsv_all = rgb_to_hsv_array(colors[green_indices])
|
| 294 |
+
saturation = hsv_all[:, 1]
|
| 295 |
order_by_sat = np.argsort(-saturation)
|
| 296 |
n_priority = int(len(order_by_sat) * SAT_PRIORITY_FRAC)
|
| 297 |
priority_idx = order_by_sat[:n_priority]
|
|
|
|
| 317 |
eps1 = max(0.15, min(0.45, est_eps))
|
| 318 |
eps2 = min(0.9, eps1 * 1.6)
|
| 319 |
min_samples = DBSCAN_MIN_SAMPLES_DEFAULT
|
| 320 |
+
|
| 321 |
output_text += f"Estimated base eps: {eps1:.3f} (second-pass eps: {eps2:.3f}), min_samples: {min_samples}\n"
|
| 322 |
|
| 323 |
# First pass
|
|
|
|
| 325 |
labels1 = clust1.labels_
|
| 326 |
|
| 327 |
# Second pass (coarser)
|
| 328 |
+
clust2 = DBSCAN(eps=eps2, min_samples=max(6, int(min_samples / 2))).fit(dbscan_pts)
|
| 329 |
labels2 = clust2.labels_
|
| 330 |
|
| 331 |
# Combine clusters
|
|
|
|
| 336 |
label_map = {lab: i for i, lab in enumerate(unique) if lab != -1}
|
| 337 |
norm_labels = np.full_like(combined_labels, fill_value=-1)
|
| 338 |
for lab, nid in label_map.items():
|
| 339 |
+
if lab == -1:
|
| 340 |
+
continue
|
| 341 |
norm_labels[combined_labels == lab] = nid
|
| 342 |
|
| 343 |
# ---- Merge neighboring clusters that overlap after mapping back to full green set ----
|
|
|
|
| 350 |
|
| 351 |
for lab in valid_labels:
|
| 352 |
mask_sample = (norm_labels == lab)
|
| 353 |
+
if mask_sample.sum() == 0:
|
| 354 |
+
continue
|
| 355 |
sample_pos_in_db = np.nonzero(mask_sample)[0]
|
| 356 |
global_idxs = sampled_map[sample_pos_in_db]
|
| 357 |
green_positions = [global_to_greenpos[int(g)] for g in global_idxs if int(g) in global_to_greenpos]
|
| 358 |
+
if len(green_positions) == 0:
|
| 359 |
+
continue
|
| 360 |
seeds = green_pts_full[green_positions]
|
| 361 |
radius = eps1 * REGION_GROW_FACTOR
|
| 362 |
neigh_lists = bt.query_radius(seeds, r=radius)
|
|
|
|
| 367 |
# After region grow, group final labels by scanning full_label_assignment
|
| 368 |
final_label_positions = {}
|
| 369 |
for pos, lab in enumerate(full_label_assignment):
|
| 370 |
+
if lab == -1:
|
| 371 |
+
continue
|
| 372 |
final_label_positions.setdefault(int(lab), []).append(int(pos))
|
| 373 |
|
| 374 |
# Build clusters_info
|
|
|
|
| 387 |
density = cluster_pts.shape[0] / (volume + 1e-9)
|
| 388 |
if density < MIN_DENSITY:
|
| 389 |
continue
|
| 390 |
+
|
| 391 |
preview_fn = os.path.join(temp_root, f"obj_preview_lab{lab}_{uuid.uuid4().hex}.png")
|
| 392 |
save_cluster_preview_png(cluster_pts, cluster_cols, preview_fn)
|
| 393 |
clusters_info.append({
|
|
|
|
| 407 |
if n_points > PREVIEW_MAX_POINTS:
|
| 408 |
rng = np.random.default_rng(1)
|
| 409 |
idx_preview = rng.choice(n_points, size=PREVIEW_MAX_POINTS, replace=False)
|
| 410 |
+
preview_points = points[idx_preview]
|
| 411 |
+
preview_colors = colors[idx_preview]
|
| 412 |
else:
|
| 413 |
+
preview_points = points[:]
|
| 414 |
+
preview_colors = colors[:]
|
| 415 |
+
preview_rgb = ["rgb(%d,%d,%d)" % tuple(c) for c in preview_colors]
|
| 416 |
|
| 417 |
if green_count > PREVIEW_GREEN_MAX:
|
| 418 |
rng = np.random.default_rng(2)
|
| 419 |
idxg = rng.choice(green_indices, size=PREVIEW_GREEN_MAX, replace=False)
|
| 420 |
+
preview_green_points = points[idxg]
|
| 421 |
+
preview_green_colors = colors[idxg]
|
| 422 |
else:
|
| 423 |
+
preview_green_points = points[green_indices]
|
| 424 |
+
preview_green_colors = colors[green_indices]
|
| 425 |
+
preview_green_rgb = ["rgb(%d,%d,%d)" % tuple(c) for c in preview_green_colors]
|
| 426 |
|
| 427 |
fig = go.Figure()
|
| 428 |
+
fig.add_trace(go.Scatter3d(x=preview_points[:, 0], y=preview_points[:, 1], z=preview_points[:, 2],
|
| 429 |
+
mode='markers', marker=dict(size=1, color=preview_rgb), name='All (preview)',
|
| 430 |
+
hoverinfo='none'))
|
| 431 |
+
fig.add_trace(go.Scatter3d(x=preview_green_points[:, 0], y=preview_green_points[:, 1], z=preview_green_points[:, 2],
|
| 432 |
+
mode='markers', marker=dict(size=2, color=preview_green_rgb), name='Green (preview)',
|
| 433 |
+
hoverinfo='none'))
|
| 434 |
for info in clusters_info:
|
| 435 |
add_bbox_to_fig(fig, info["corners"], color='red', width=4)
|
| 436 |
+
fig.update_layout(scene=dict(aspectmode='data'), height=800, margin=dict(l=0, r=0, t=0, b=0))
|
| 437 |
|
| 438 |
# ---- Excel export ----
|
| 439 |
+
out_xlsx = None
|
| 440 |
if clusters_info:
|
| 441 |
out_xlsx = os.path.join(temp_root, "detected_objects_styled.xlsx")
|
| 442 |
create_styled_excel(clusters_info, out_xlsx)
|
|
|
|
|
|
|
| 443 |
|
| 444 |
return output_text, fig, out_xlsx
|
| 445 |
|
|
|
|
| 458 |
output_plot = gr.Plot(label="Interactive 3D Preview (downsampled)")
|
| 459 |
|
| 460 |
file_input.upload(
|
| 461 |
+
fn=process_point_cloud,
|
| 462 |
inputs=[file_input],
|
| 463 |
outputs=[output_text, output_plot, download_button]
|
| 464 |
)
|
| 465 |
|
| 466 |
+
demo.launch()
|