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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py -- complete, self-contained application
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import numpy as np
|
| 4 |
+
import os
|
| 5 |
+
import uuid
|
| 6 |
+
import tempfile
|
| 7 |
+
import plotly.graph_objects as go
|
| 8 |
+
import plotly.io as pio
|
| 9 |
+
from sklearn.cluster import DBSCAN
|
| 10 |
+
from sklearn.neighbors import NearestNeighbors, BallTree
|
| 11 |
+
import openpyxl
|
| 12 |
+
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
| 13 |
+
from openpyxl.drawing.image import Image as XLImage
|
| 14 |
+
import math
|
| 15 |
+
|
| 16 |
+
# ---- Hardcoded parameters (RELAXED for broader detection) ----
|
| 17 |
+
PREVIEW_MAX_POINTS = 80_000
|
| 18 |
+
PREVIEW_GREEN_MAX = 50_000
|
| 19 |
+
|
| 20 |
+
# Relaxed physical filters to catch more clusters
|
| 21 |
+
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 ,ASSET_ID1 = "3051047","2859571"
|
| 27 |
+
|
| 28 |
+
# DBSCAN defaults (auto-tuned below)
|
| 29 |
+
DBSCAN_MIN_SAMPLES_DEFAULT = 12
|
| 30 |
+
EPS_SCALE = 1.15
|
| 31 |
+
|
| 32 |
+
# sampling priority: fraction of top-saturation points to always include
|
| 33 |
+
SAT_PRIORITY_FRAC = 0.5
|
| 34 |
+
|
| 35 |
+
# region grow radius factor (grow clusters on full green set)
|
| 36 |
+
REGION_GROW_FACTOR = 1.2
|
| 37 |
+
|
| 38 |
+
# minimal cluster volume to accept (m^3)
|
| 39 |
+
MIN_VOLUME = 0.001
|
| 40 |
+
|
| 41 |
+
# minimal density (points per cubic meter) to accept cluster
|
| 42 |
+
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('#'): continue
|
| 51 |
+
parts=line.split()
|
| 52 |
+
if len(parts)<6: continue
|
| 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)); cols.append((r,g,b))
|
| 59 |
+
pts = np.asarray(pts, dtype=np.float32)
|
| 60 |
+
cols = np.asarray(cols, dtype=np.uint8)
|
| 61 |
+
np.save(pts_npy, pts); np.save(cols_npy, cols)
|
| 62 |
+
return pts_npy, cols_npy
|
| 63 |
+
|
| 64 |
+
def rgb_to_hsv_array(rgb_uint8):
|
| 65 |
+
rgb = rgb_uint8.astype(np.float32)/255.0
|
| 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); gc = np.zeros_like(maxc); bc = 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]],
|
| 103 |
+
[min_pt[0], max_pt[1], min_pt[2]],
|
| 104 |
+
[min_pt[0], max_pt[1], max_pt[2]],
|
| 105 |
+
[max_pt[0], min_pt[1], min_pt[2]],
|
| 106 |
+
[max_pt[0], min_pt[1], max_pt[2]],
|
| 107 |
+
[max_pt[0], max_pt[1], min_pt[2]],
|
| 108 |
+
[max_pt[0], max_pt[1], max_pt[2]],
|
| 109 |
+
])
|
| 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 |
+
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)]
|
| 114 |
+
for s,e in edges:
|
| 115 |
+
fig.add_trace(go.Scatter3d(
|
| 116 |
+
x=[corners[s][0], corners[e][0]],
|
| 117 |
+
y=[corners[s][1], corners[e][1]],
|
| 118 |
+
z=[corners[s][2], corners[e][2]],
|
| 119 |
+
mode='lines',
|
| 120 |
+
line=dict(color=color, width=width),
|
| 121 |
+
showlegend=False
|
| 122 |
+
))
|
| 123 |
+
|
| 124 |
+
def save_cluster_preview_png(cluster_pts, cluster_cols, out_path, size=(500,500), downsample=200000):
|
| 125 |
+
n=cluster_pts.shape[0]
|
| 126 |
+
if n>downsample:
|
| 127 |
+
rng=np.random.default_rng(0)
|
| 128 |
+
idx=rng.choice(n, size=downsample, replace=False)
|
| 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"
|
| 149 |
+
blue_fill = PatternFill(start_color="D9EAF7", end_color="D9EAF7", fill_type="solid")
|
| 150 |
+
header_fill = PatternFill(start_color="B7D6F5", end_color="B7D6F5", fill_type="solid")
|
| 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 |
+
"CloudPoint Image","CX1","CY2","CZ3","Length","Width","Height",
|
| 165 |
+
"Assest Name","Assest ID","Assest Img","Remarks"]
|
| 166 |
+
for c,h in enumerate(headers, start=1):
|
| 167 |
+
cell=ws.cell(row=row, column=c, value=h)
|
| 168 |
+
cell.font=bold; cell.fill=header_fill; cell.alignment=center; cell.border=border
|
| 169 |
+
row += 1
|
| 170 |
+
corners = info["corners"]; centroid = info["centroid"]
|
| 171 |
+
length,width,height = info["length"], info["width"], info["height"]
|
| 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,value=c[0]); ws.cell(row=row,column=3,value=c[0])
|
| 176 |
+
ws.cell(row=row,column=4,value=c[1]); ws.cell(row=row,column=5,value=c[1])
|
| 177 |
+
ws.cell(row=row,column=6,value=c[2]); ws.cell(row=row,column=7,value=c[2])
|
| 178 |
+
ws.cell(row=row,column=9,value=round(centroid[0],4)); ws.cell(row=row,column=10,value=round(centroid[1],4))
|
| 179 |
+
ws.cell(row=row,column=11,value=round(centroid[2],4))
|
| 180 |
+
ws.cell(row=row,column=12,value=round(length,4)); ws.cell(row=row,column=13,value=round(width,4))
|
| 181 |
+
ws.cell(row=row,column=14,value=round(height,4))
|
| 182 |
+
ws.cell(row=row,column=15,value=ASSET_NAME); ws.cell(row=row,column=16,value=ASSET_ID)
|
| 183 |
+
ws.cell(row=row,column=17,value=""); ws.cell(row=row,column=18,value="")
|
| 184 |
+
for col_idx in range(1,19):
|
| 185 |
+
ws.cell(row=row,column=col_idx).fill=blue_fill; ws.cell(row=row,column=col_idx).border=border
|
| 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
|
| 203 |
+
if n > sample_size:
|
| 204 |
+
rng = np.random.default_rng(42)
|
| 205 |
+
sample_idx = rng.choice(n, size=sample_size, replace=False)
|
| 206 |
+
pts_sample = points_for_estimate[sample_idx]
|
| 207 |
+
else:
|
| 208 |
+
pts_sample = points_for_estimate
|
| 209 |
+
neigh = NearestNeighbors(n_neighbors=k)
|
| 210 |
+
neigh.fit(pts_sample)
|
| 211 |
+
dists, _ = neigh.kneighbors(pts_sample)
|
| 212 |
+
kth = dists[:, -1]
|
| 213 |
+
return float(np.percentile(kth, 75))
|
| 214 |
+
|
| 215 |
+
def process_file(uploaded_file):
|
| 216 |
+
if uploaded_file is None:
|
| 217 |
+
return "No file uploaded.", None, None
|
| 218 |
+
|
| 219 |
+
# Use the path to the temporary file Gradio provides
|
| 220 |
+
orig_path = uploaded_file.name
|
| 221 |
+
|
| 222 |
+
# Create a unique temporary directory for output files
|
| 223 |
+
temp_root = os.path.join(tempfile.gettempdir(), f"temp_pts_{uuid.uuid4().hex}")
|
| 224 |
+
os.makedirs(temp_root, exist_ok=True)
|
| 225 |
+
|
| 226 |
+
# Process the file from the path Gradio gave us
|
| 227 |
+
pts_npy = os.path.join(temp_root, "cloud_points.npy")
|
| 228 |
+
cols_npy = os.path.join(temp_root, "cloud_colors.npy")
|
| 229 |
+
pts_to_npy(orig_path, pts_npy, cols_npy)
|
| 230 |
+
|
| 231 |
+
points = np.load(pts_npy, mmap_mode='r')
|
| 232 |
+
colors = np.load(cols_npy, mmap_mode='r')
|
| 233 |
+
n_points = points.shape[0]
|
| 234 |
+
|
| 235 |
+
output_text = f"Total points: {n_points:,}\n"
|
| 236 |
+
|
| 237 |
+
# compute green mask in chunks
|
| 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]
|
| 245 |
+
output_text += f"Green-colored points: {green_count:,}\n"
|
| 246 |
+
|
| 247 |
+
if green_count == 0:
|
| 248 |
+
return "No green points detected.", None, None
|
| 249 |
+
|
| 250 |
+
# ---- Auto-adjust max dbscan points based on green_count ----
|
| 251 |
+
if green_count <= 1000:
|
| 252 |
+
max_dbscan_points = green_count
|
| 253 |
+
elif green_count <= 5000:
|
| 254 |
+
max_dbscan_points = 1000
|
| 255 |
+
elif green_count <= 50000:
|
| 256 |
+
max_dbscan_points = 2000
|
| 257 |
+
else:
|
| 258 |
+
max_dbscan_points = 5000
|
| 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]
|
| 266 |
+
|
| 267 |
+
if green_count > max_dbscan_points:
|
| 268 |
+
remaining = order_by_sat[n_priority:]
|
| 269 |
+
rng = np.random.default_rng(123)
|
| 270 |
+
n_remaining_needed = max_dbscan_points - n_priority
|
| 271 |
+
if n_remaining_needed > 0 and remaining.size > 0:
|
| 272 |
+
chosen_remaining = rng.choice(remaining, size=min(n_remaining_needed, remaining.size), replace=False)
|
| 273 |
+
chosen = np.concatenate([priority_idx, chosen_remaining])
|
| 274 |
+
else:
|
| 275 |
+
chosen = priority_idx[:max_dbscan_points]
|
| 276 |
+
sample_inds = green_indices[chosen]
|
| 277 |
+
dbscan_pts = points[sample_inds]
|
| 278 |
+
dbscan_map = sample_inds
|
| 279 |
+
else:
|
| 280 |
+
dbscan_pts = points[green_indices]
|
| 281 |
+
dbscan_map = green_indices
|
| 282 |
+
|
| 283 |
+
# ---- Estimate eps adaptively and run multi-scale DBSCAN ----
|
| 284 |
+
est_eps = estimate_eps(dbscan_pts, sample_size=3000, k=8)
|
| 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
|
| 292 |
+
clust1 = DBSCAN(eps=eps1, min_samples=min_samples).fit(dbscan_pts)
|
| 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
|
| 300 |
+
combined_labels = labels1.copy()
|
| 301 |
+
noise_mask = combined_labels == -1
|
| 302 |
+
combined_labels[noise_mask] = labels2[noise_mask]
|
| 303 |
+
unique = np.unique(combined_labels)
|
| 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: continue
|
| 308 |
+
norm_labels[combined_labels == lab] = nid
|
| 309 |
+
|
| 310 |
+
# ---- Merge neighboring clusters that overlap after mapping back to full green set ----
|
| 311 |
+
sampled_map = dbscan_map
|
| 312 |
+
valid_labels = [lab for lab in np.unique(norm_labels) if lab != -1]
|
| 313 |
+
green_pts_full = points[green_indices]
|
| 314 |
+
bt = BallTree(green_pts_full, leaf_size=40)
|
| 315 |
+
global_to_greenpos = {int(g): i for i, g in enumerate(green_indices)}
|
| 316 |
+
full_label_assignment = np.full(green_count, -1, dtype=int)
|
| 317 |
+
|
| 318 |
+
for lab in valid_labels:
|
| 319 |
+
mask_sample = (norm_labels == lab)
|
| 320 |
+
if mask_sample.sum() == 0: continue
|
| 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: continue
|
| 325 |
+
seeds = green_pts_full[green_positions]
|
| 326 |
+
radius = eps1 * REGION_GROW_FACTOR
|
| 327 |
+
neigh_lists = bt.query_radius(seeds, r=radius)
|
| 328 |
+
for neigh in neigh_lists:
|
| 329 |
+
for gp in neigh:
|
| 330 |
+
full_label_assignment[int(gp)] = int(lab)
|
| 331 |
+
|
| 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: continue
|
| 336 |
+
final_label_positions.setdefault(int(lab), []).append(int(pos))
|
| 337 |
+
|
| 338 |
+
# Build clusters_info
|
| 339 |
+
clusters_info = []
|
| 340 |
+
for lab, green_positions in final_label_positions.items():
|
| 341 |
+
abs_indices = green_indices[green_positions]
|
| 342 |
+
cluster_pts = np.asarray(points[abs_indices])
|
| 343 |
+
cluster_cols = np.asarray(colors[abs_indices])
|
| 344 |
+
corners, centroid, length, width, height, zmin, zmax = get_bbox_and_metrics(cluster_pts)
|
| 345 |
+
volume = length * width * height
|
| 346 |
+
# Apply relaxed filters
|
| 347 |
+
if height < MIN_HEIGHT or length > MAX_LENGTH or width > MAX_WIDTH:
|
| 348 |
+
continue
|
| 349 |
+
if volume < MIN_VOLUME:
|
| 350 |
+
continue
|
| 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({
|
| 358 |
+
"cluster_id": int(lab) + 1,
|
| 359 |
+
"centroid": centroid.tolist(),
|
| 360 |
+
"corners": corners,
|
| 361 |
+
"length": length,
|
| 362 |
+
"width": width,
|
| 363 |
+
"height": height,
|
| 364 |
+
"points_count": int(cluster_pts.shape[0]),
|
| 365 |
+
"preview_path": preview_fn
|
| 366 |
+
})
|
| 367 |
+
|
| 368 |
+
output_text += f"Detected {len(clusters_info)} object-shaped clusters after filtering\n"
|
| 369 |
+
|
| 370 |
+
# ---- Interactive preview (downsampled) ----
|
| 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]; preview_colors = colors[idx_preview]
|
| 375 |
+
else:
|
| 376 |
+
preview_points = points[:]; preview_colors = colors[:]
|
| 377 |
+
preview_rgb = ["rgb(%d,%d,%d)"%tuple(c) for c in preview_colors]
|
| 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]; preview_green_colors = colors[idxg]
|
| 383 |
+
else:
|
| 384 |
+
preview_green_points = points[green_indices]; preview_green_colors = colors[green_indices]
|
| 385 |
+
preview_green_rgb = ["rgb(%d,%d,%d)"%tuple(c) for c in preview_green_colors]
|
| 386 |
+
|
| 387 |
+
fig = go.Figure()
|
| 388 |
+
fig.add_trace(go.Scatter3d(x=preview_points[:,0], y=preview_points[:,1], z=preview_points[:,2],
|
| 389 |
+
mode='markers', marker=dict(size=1, color=preview_rgb), name='All (preview)',
|
| 390 |
+
hoverinfo='none'))
|
| 391 |
+
fig.add_trace(go.Scatter3d(x=preview_green_points[:,0], y=preview_green_points[:,1], z=preview_green_points[:,2],
|
| 392 |
+
mode='markers', marker=dict(size=2, color=preview_green_rgb), name='Green (preview)',
|
| 393 |
+
hoverinfo='none'))
|
| 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 |
+
|
| 407 |
+
|
| 408 |
+
# Gradio Interface
|
| 409 |
+
with gr.Blocks(title="Detection") as demo:
|
| 410 |
+
gr.Markdown("# Green Dustbin & AIS Box Detection")
|
| 411 |
+
gr.Markdown("Upload a `.pts` file to analyze the point cloud data.")
|
| 412 |
+
|
| 413 |
+
with gr.Row():
|
| 414 |
+
file_input = gr.File(label="Upload .pts (X Y Z R G B)")
|
| 415 |
+
with gr.Column():
|
| 416 |
+
output_text = gr.Textbox(label="Processing Log", lines=10)
|
| 417 |
+
download_button = gr.DownloadButton("Download styled Excel")
|
| 418 |
+
|
| 419 |
+
output_plot = gr.Plot(label="Interactive 3D Preview (downsampled)")
|
| 420 |
+
|
| 421 |
+
file_input.upload(
|
| 422 |
+
fn=process_file,
|
| 423 |
+
inputs=[file_input],
|
| 424 |
+
outputs=[output_text, output_plot, download_button]
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
demo.launch(share=True)
|