Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,383 +1,230 @@
|
|
| 1 |
-
# app.py ββ
|
| 2 |
-
import gradio as gr
|
| 3 |
-
import numpy as np
|
| 4 |
-
import os, uuid, tempfile, csv
|
| 5 |
-
import plotly.graph_objects as go
|
| 6 |
import plotly.io as pio
|
| 7 |
from sklearn.cluster import DBSCAN
|
| 8 |
from sklearn.neighbors import NearestNeighbors, BallTree
|
| 9 |
import openpyxl
|
| 10 |
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
| 11 |
from openpyxl.drawing.image import Image as XLImage
|
| 12 |
-
from openpyxl.worksheet.datavalidation import DataValidation
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
CONFIDENCE_SCORE_PLACEHOLDER = 1.0
|
| 28 |
-
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
# ------------- Helper: read .pts in chunks --------------------------
|
| 32 |
-
def pts_to_npy(file_path, pts_npy, cols_npy):
|
| 33 |
pts, cols = [], []
|
| 34 |
-
with open(
|
| 35 |
-
|
| 36 |
-
for row in
|
| 37 |
-
if not row or row[0].startswith('#'):
|
| 38 |
-
continue
|
| 39 |
try:
|
| 40 |
-
x,y,z = map(float, row[:3])
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
# ------------- Color utilities --------------------------------------
|
| 54 |
-
def rgb_to_hsv_array(rgb_uint8):
|
| 55 |
-
rgb = rgb_uint8.astype(np.float32) / 255.0
|
| 56 |
-
maxc, minc = np.max(rgb,1), np.min(rgb,1)
|
| 57 |
-
diff = maxc - minc
|
| 58 |
-
s = np.zeros_like(maxc)
|
| 59 |
-
s[maxc>0] = diff[maxc>0] / maxc[maxc>0]
|
| 60 |
h = np.zeros_like(maxc)
|
| 61 |
-
mask_r
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
h[
|
| 65 |
-
h
|
| 66 |
-
h[mask_b] = 4 + (rgb[mask_b,0]-rgb[mask_b,1]) / diff[mask_b]
|
| 67 |
-
h = (h/6.0) % 1.0
|
| 68 |
return np.stack([h,s,maxc],1)
|
| 69 |
|
| 70 |
-
def
|
| 71 |
-
|
| 72 |
-
h
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
[
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
f.write(pio.to_image(fig, format='png'))
|
| 117 |
-
return out_path
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
# ------------- Excel creation (fixed) -------------------------------
|
| 121 |
-
def create_styled_excel(clusters_info, out_xlsx_path):
|
| 122 |
-
wb=openpyxl.Workbook()
|
| 123 |
-
ws=wb.active; ws.title="Detected Green Objects"
|
| 124 |
-
|
| 125 |
-
header_fill = PatternFill("solid","E0E0E0")
|
| 126 |
-
data_fill = PatternFill("solid","F2F2F2")
|
| 127 |
-
bold,center = Font(bold=True), Alignment(horizontal="center",vertical="center")
|
| 128 |
-
thin = Side("thin","000000")
|
| 129 |
-
border = Border(top=thin,bottom=thin,left=thin,right=thin)
|
| 130 |
-
|
| 131 |
-
# Dropdown definition (inline list is simpler than a hidden sheet)
|
| 132 |
-
dv_check = DataValidation(type="list", formula1='"Ok,Not Ok"', allow_blank=True)
|
| 133 |
-
dv_nx = DataValidation(type="list", formula1='"Ok,Not Ok"', allow_blank=True)
|
| 134 |
-
ws.add_data_validation(dv_check)
|
| 135 |
-
ws.add_data_validation(dv_nx)
|
| 136 |
|
| 137 |
row=1
|
| 138 |
-
for
|
| 139 |
-
ws.merge_cells(
|
| 140 |
-
ws.cell(row,1,"
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
"Check","NX","Class Name","Confidence Score"]
|
| 148 |
-
for c,h in enumerate(headers,1):
|
| 149 |
-
cell=ws.cell(row,row,column=c,value=h)
|
| 150 |
-
cell.font=bold; cell.alignment=center; cell.fill=header_fill; cell.border=border
|
| 151 |
row+=1
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
ws.cell(row,
|
| 162 |
-
ws.cell(row,
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
ws.cell(row,10,round(centroid[1],4))
|
| 166 |
-
ws.cell(row,11,round(centroid[2],4))
|
| 167 |
-
ws.cell(row,12,round(length,4)); ws.cell(row,13,round(width,4)); ws.cell(row,14,round(height,4))
|
| 168 |
-
ws.cell(row,15,ASSET_NAME); ws.cell(row,16,ASSET_ID)
|
| 169 |
-
|
| 170 |
-
# preset blank for image / remarks
|
| 171 |
-
ws.cell(row,17,""); ws.cell(row,18,"")
|
| 172 |
-
|
| 173 |
-
# Check & NX dropdowns
|
| 174 |
-
chk = ws.cell(row,19,"")
|
| 175 |
-
nx = ws.cell(row,20,"")
|
| 176 |
-
dv_check.add(chk.coordinate)
|
| 177 |
-
dv_nx.add(nx.coordinate)
|
| 178 |
-
|
| 179 |
-
ws.cell(row,21,class_name)
|
| 180 |
-
ws.cell(row,22,CONFIDENCE_SCORE_PLACEHOLDER)
|
| 181 |
-
|
| 182 |
-
# styling
|
| 183 |
-
for col in range(1,23):
|
| 184 |
-
c=ws.cell(row,col); c.fill=data_fill; c.border=border
|
| 185 |
row+=1
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
for r in range(start_data_row,start_data_row+8):
|
| 191 |
-
ws.row_dimensions[r].height=60
|
| 192 |
ws.column_dimensions['H'].width=20
|
| 193 |
-
ws.add_image(img, f'H{start_data_row}')
|
| 194 |
row+=1
|
| 195 |
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
ws.column_dimensions['T'].width=10
|
| 199 |
-
ws.column_dimensions['U'].width=15
|
| 200 |
-
ws.column_dimensions['V'].width=15
|
| 201 |
-
wb.save(out_xlsx_path)
|
| 202 |
-
return out_xlsx_path
|
| 203 |
-
|
| 204 |
|
| 205 |
-
#
|
| 206 |
-
def estimate_eps(pts,
|
| 207 |
-
|
| 208 |
-
if
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
pts=pts[idx]
|
| 212 |
-
neigh=NearestNeighbors(n_neighbors=k).fit(pts)
|
| 213 |
-
kth=neigh.kneighbors(pts)[0][:,-1]
|
| 214 |
return float(np.percentile(kth,75))
|
| 215 |
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
return "Upload a file first.", None, None, gr.update(interactive=False)
|
| 250 |
-
|
| 251 |
-
pts=np.load(file_state[0],mmap_mode='r')
|
| 252 |
-
cols=np.load(file_state[1],mmap_mode='r')
|
| 253 |
-
n=len(pts); out=f"Total points: {n:,}\n"
|
| 254 |
-
|
| 255 |
-
progress(0.2, desc="Filtering green points")
|
| 256 |
-
green_mask=is_green_mask_from_rgb(cols)
|
| 257 |
-
g_idx=np.nonzero(green_mask)[0]
|
| 258 |
-
g_cnt=len(g_idx)
|
| 259 |
-
out+=f"Green-colored points: {g_cnt:,}\n"
|
| 260 |
-
if g_cnt==0:
|
| 261 |
-
return "No green points.",None,None,gr.update(interactive=True)
|
| 262 |
-
|
| 263 |
-
# DBSCAN sampling
|
| 264 |
-
if g_cnt<=1000: max_pts=g_cnt
|
| 265 |
-
elif g_cnt<=5000: max_pts=1000
|
| 266 |
-
elif g_cnt<=50_000: max_pts=2000
|
| 267 |
-
else: max_pts=5000
|
| 268 |
-
|
| 269 |
-
hsv=rgb_to_hsv_array(cols[g_idx]); sat=hsv[:,1]
|
| 270 |
-
order=np.argsort(-sat)
|
| 271 |
-
n_pri=int(len(order)*SAT_PRIORITY_FRAC)
|
| 272 |
-
pri=order[:n_pri]
|
| 273 |
-
if g_cnt>max_pts:
|
| 274 |
-
rng=np.random.default_rng(123)
|
| 275 |
-
rest=order[n_pri:]; need=max_pts-n_pri
|
| 276 |
-
choose=rng.choice(rest,need,False) if need>0 else []
|
| 277 |
-
sample_idx=g_idx[np.concatenate([pri,choose])]
|
| 278 |
-
else:
|
| 279 |
-
sample_idx=g_idx
|
| 280 |
-
db_pts=pts[sample_idx]
|
| 281 |
-
|
| 282 |
-
progress(0.4, desc="Clustering")
|
| 283 |
-
eps1=max(0.15,min(0.45,estimate_eps(db_pts)))
|
| 284 |
-
eps2=min(0.9,eps1*1.6)
|
| 285 |
-
ms=DBSCAN_MIN_SAMPLES_DEFAULT
|
| 286 |
lab1=DBSCAN(eps=eps1,min_samples=ms).fit(db_pts).labels_
|
| 287 |
lab2=DBSCAN(eps=eps2,min_samples=max(6,ms//2)).fit(db_pts).labels_
|
| 288 |
comb=lab1.copy(); comb[comb==-1]=lab2[comb==-1]
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
for l,nid in maplab.items():
|
| 292 |
-
norm[comb==l]=nid
|
| 293 |
|
| 294 |
# region grow
|
| 295 |
-
bt=BallTree(pts[
|
| 296 |
-
label_full=np.full(len(g_idx),-1,int)
|
| 297 |
for l in np.unique(norm):
|
| 298 |
if l==-1: continue
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
for neigh in radii:
|
| 303 |
-
label_full[neigh]=l
|
| 304 |
|
| 305 |
-
#
|
| 306 |
clusters=[]
|
| 307 |
-
for l in np.unique(
|
| 308 |
if l==-1: continue
|
| 309 |
-
pos=np.where(
|
| 310 |
-
|
| 311 |
-
c_pts=pts[abs_idx]; c_cols=cols[abs_idx]
|
| 312 |
-
corners,centroid,L,W,H,zmin,zmax=get_bbox_and_metrics(c_pts)
|
| 313 |
vol=L*W*H
|
| 314 |
if H<MIN_HEIGHT or L>MAX_LENGTH or W>MAX_WIDTH or vol<MIN_VOLUME: continue
|
| 315 |
-
if len(
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
clusters.append(dict(corners=corners,centroid=centroid,
|
| 320 |
-
length=L,width=W,height=H,
|
| 321 |
-
zmin=zmin,
|
| 322 |
-
preview_path=prev))
|
| 323 |
-
|
| 324 |
-
out+=f"Detected {len(clusters)} objects after filtering\n"
|
| 325 |
|
| 326 |
# plot
|
| 327 |
-
|
| 328 |
-
if
|
| 329 |
-
idx=np.random.default_rng(1).choice(n,PREVIEW_MAX_POINTS,False)
|
| 330 |
-
p_pts,p_cols=pts[idx],cols[idx]
|
| 331 |
-
else: p_pts,p_cols=pts,cols
|
| 332 |
-
p_rgb=[f'rgb({r},{g},{b})' for r,g,b in p_cols]
|
| 333 |
-
|
| 334 |
-
g_show=g_idx if g_cnt<=PREVIEW_GREEN_MAX else np.random.default_rng(2).choice(g_idx,PREVIEW_GREEN_MAX,False)
|
| 335 |
-
g_pts,g_cols=pts[g_show],cols[g_show]
|
| 336 |
-
g_rgb=[f'rgb({r},{g},{b})' for r,g,b in g_cols]
|
| 337 |
-
|
| 338 |
fig=go.Figure()
|
| 339 |
-
fig.add_trace(go.Scatter3d(x=
|
| 340 |
-
mode='markers',marker=dict(size=1,color=
|
| 341 |
name='All',hoverinfo='none'))
|
| 342 |
-
fig.add_trace(go.Scatter3d(x=
|
| 343 |
-
mode='markers',marker=dict(size=2,color=
|
| 344 |
name='Green',hoverinfo='none'))
|
| 345 |
-
for
|
| 346 |
-
fig.update_layout(scene=dict(aspectmode='data'),height=800,
|
| 347 |
-
margin=dict(l=0,r=0,t=0,b=0))
|
| 348 |
|
| 349 |
xlsx=None
|
| 350 |
-
if clusters:
|
| 351 |
-
|
| 352 |
-
create_styled_excel(clusters,xlsx)
|
| 353 |
-
|
| 354 |
-
progress(1.0, desc="Done")
|
| 355 |
return out,fig,xlsx,gr.update(interactive=True)
|
| 356 |
|
| 357 |
-
|
| 358 |
-
# ------------- UI ----------------------------------------------------
|
| 359 |
with gr.Blocks(title="Detection") as demo:
|
| 360 |
gr.Markdown("# Green Dustbin & AIS Box Detection")
|
| 361 |
-
gr.
|
| 362 |
-
|
| 363 |
-
file_state = gr.State([None,None])
|
| 364 |
-
last_file_state = gr.State({})
|
| 365 |
-
|
| 366 |
with gr.Row():
|
| 367 |
-
|
| 368 |
with gr.Column():
|
| 369 |
-
log
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
plot = gr.Plot(label="3-D preview
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
inputs=[file_in,last_file_state],
|
| 376 |
-
outputs=[log,analyse,dl_btn,file_state,last_file_state],
|
| 377 |
-
queue=False)
|
| 378 |
-
|
| 379 |
-
analyse.click(start_analysis,
|
| 380 |
-
inputs=[file_state],
|
| 381 |
-
outputs=[log,plot,dl_btn,analyse])
|
| 382 |
-
|
| 383 |
demo.launch()
|
|
|
|
| 1 |
+
# app.py ββ self-contained Space
|
| 2 |
+
import gradio as gr, numpy as np, os, uuid, tempfile, csv, plotly.graph_objects as go
|
|
|
|
|
|
|
|
|
|
| 3 |
import plotly.io as pio
|
| 4 |
from sklearn.cluster import DBSCAN
|
| 5 |
from sklearn.neighbors import NearestNeighbors, BallTree
|
| 6 |
import openpyxl
|
| 7 |
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
| 8 |
from openpyxl.drawing.image import Image as XLImage
|
| 9 |
+
from openpyxl.worksheet.datavalidation import DataValidation
|
| 10 |
+
|
| 11 |
+
# βββββββββββββ parameters
|
| 12 |
+
PREVIEW_MAX_POINTS, PREVIEW_GREEN_MAX = 80_000, 50_000
|
| 13 |
+
MIN_HEIGHT, MAX_LENGTH, MAX_WIDTH = 0.05, 2.0, 2.0
|
| 14 |
+
DBSCAN_MIN_SAMPLES_DEFAULT = 12
|
| 15 |
+
SAT_PRIORITY_FRAC, REGION_GROW_FACTOR = 0.5, 1.2
|
| 16 |
+
MIN_VOLUME, MIN_DENSITY = 0.001, 5
|
| 17 |
+
Z_THRESHOLD_ELEVATED = 0.5 # m
|
| 18 |
+
CONFIDENCE_SCORE_PLACEHOLDER = 1.0
|
| 19 |
+
CHUNK_SIZE = 1_000_000
|
| 20 |
+
ASSET_NAME, ASSET_ID = "Green Object", "3051047"
|
| 21 |
+
|
| 22 |
+
# βββββββββββββ I/O helpers
|
| 23 |
+
def pts_to_npy(src, pts_out, col_out):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
pts, cols = [], []
|
| 25 |
+
with open(src, newline='') as f:
|
| 26 |
+
rdr = csv.reader(f, delimiter=' ')
|
| 27 |
+
for row in rdr:
|
| 28 |
+
if not row or row[0].startswith('#'): continue
|
|
|
|
| 29 |
try:
|
| 30 |
+
x,y,z = map(float, row[:3]); r,g,b = map(int, row[3:6])
|
| 31 |
+
except (ValueError, IndexError): continue
|
| 32 |
+
pts.append((x,y,z)); cols.append((r,g,b))
|
| 33 |
+
np.save(pts_out, np.asarray(pts, dtype=np.float32))
|
| 34 |
+
np.save(col_out, np.asarray(cols, dtype=np.uint8))
|
| 35 |
+
return pts_out, col_out
|
| 36 |
+
|
| 37 |
+
def rgb_to_hsv_array(rgb):
|
| 38 |
+
rgb = rgb.astype(np.float32)/255
|
| 39 |
+
maxc, minc = rgb.max(1), rgb.min(1); diff = maxc-minc
|
| 40 |
+
s = np.where(maxc>0, diff/maxc, 0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
h = np.zeros_like(maxc)
|
| 42 |
+
mask_r=(rgb[:,0]==maxc)&(diff>0); mask_g=(rgb[:,1]==maxc)&(diff>0); mask_b=(rgb[:,2]==maxc)&(diff>0)
|
| 43 |
+
h[mask_r]=(rgb[mask_r,1]-rgb[mask_r,2])/diff[mask_r]
|
| 44 |
+
h[mask_g]=2+(rgb[mask_g,2]-rgb[mask_g,0])/diff[mask_g]
|
| 45 |
+
h[mask_b]=4+(rgb[mask_b,0]-rgb[mask_b,1])/diff[mask_b]
|
| 46 |
+
h=(h/6)%1
|
|
|
|
|
|
|
| 47 |
return np.stack([h,s,maxc],1)
|
| 48 |
|
| 49 |
+
def is_green(colors):
|
| 50 |
+
h,s,v=rgb_to_hsv_array(colors).T
|
| 51 |
+
return (0.22<h)&(h<0.48)&(s>0.22)&(v>0.12)
|
| 52 |
+
|
| 53 |
+
# βββββββββββββ geometry
|
| 54 |
+
def bbox_metrics(pts):
|
| 55 |
+
lo,hi = pts.min(0), pts.max(0); cen = pts.mean(0)
|
| 56 |
+
L,W,H = hi-lo
|
| 57 |
+
c=[[lo[0],lo[1],lo[2]],[lo[0],lo[1],hi[2]],[lo[0],hi[1],lo[2]],[lo[0],hi[1],hi[2]],
|
| 58 |
+
[hi[0],lo[1],lo[2]],[hi[0],lo[1],hi[2]],[hi[0],hi[1],lo[2]],[hi[0],hi[1],hi[2]]]
|
| 59 |
+
return np.array(c),cen,float(L),float(W),float(H),float(lo[2]),float(hi[2])
|
| 60 |
+
|
| 61 |
+
def add_bbox(fig,c,color='red'):
|
| 62 |
+
e=[(0,1),(1,3),(3,2),(2,0),(4,5),(5,7),(7,6),(6,4),(0,4),(1,5),(2,6),(3,7)]
|
| 63 |
+
for s,e in e:
|
| 64 |
+
fig.add_trace(go.Scatter3d(x=[c[s,0],c[e,0]],y=[c[s,1],c[e,1]],z=[c[s,2],c[e,2]],
|
| 65 |
+
mode='lines',line=dict(color=color,width=4),showlegend=False))
|
| 66 |
+
|
| 67 |
+
# βββββββββββββ preview PNG (safe if Kaleido absent)
|
| 68 |
+
def preview_png(pts,cols,out,size=(500,500),down=200_000):
|
| 69 |
+
try:
|
| 70 |
+
if len(pts)>down:
|
| 71 |
+
idx=np.random.default_rng(0).choice(len(pts),down,False)
|
| 72 |
+
pts,cols=pts[idx],cols[idx]
|
| 73 |
+
fig=go.Figure(go.Scatter3d(x=pts[:,0],y=pts[:,1],z=pts[:,2],
|
| 74 |
+
mode='markers',
|
| 75 |
+
marker=dict(size=2,color=[f'rgb({r},{g},{b})' for r,g,b in cols])))
|
| 76 |
+
fig.update_layout(scene=dict(aspectmode='data',xaxis=dict(visible=False),
|
| 77 |
+
yaxis=dict(visible=False),zaxis=dict(visible=False)),
|
| 78 |
+
margin=dict(l=0,r=0,t=0,b=0),
|
| 79 |
+
width=size[0],height=size[1])
|
| 80 |
+
with open(out,'wb') as f:
|
| 81 |
+
f.write(pio.to_image(fig,format='png'))
|
| 82 |
+
return out
|
| 83 |
+
except Exception: # Kaleido missing or any other error β skip but donβt crash
|
| 84 |
+
return None
|
| 85 |
+
|
| 86 |
+
# βββββββββββββ Excel writer (with dropdown fix)
|
| 87 |
+
def excel(clusters, xlsx):
|
| 88 |
+
wb=openpyxl.Workbook(); ws=wb.active; ws.title="Detected Green Objects"
|
| 89 |
+
hfill=PatternFill("solid","E0E0E0"); dfill=PatternFill("solid","F2F2F2")
|
| 90 |
+
bold=Font(bold=True); cent=Alignment(horizontal="center",vertical="center")
|
| 91 |
+
thin=Side("thin","000"); border=Border(top=thin,bottom=thin,left=thin,right=thin)
|
| 92 |
+
dv=DataValidation(type="list",formula1='"Ok,Not Ok"',allow_blank=True)
|
| 93 |
+
dv2=DataValidation(type="list",formula1='"Ok,Not Ok"',allow_blank=True)
|
| 94 |
+
ws.add_data_validation(dv); ws.add_data_validation(dv2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
row=1
|
| 97 |
+
for i,cl in enumerate(clusters,1):
|
| 98 |
+
ws.merge_cells(row,row,1,22); ws.cell(row,1,"Cloud Point Creation").font=Font(bold=True,size=12); row+=1
|
| 99 |
+
ws.merge_cells(row,row,1,22); ws.cell(row,1,f"Object {i}").font=Font(bold=True,size=11); row+=1
|
| 100 |
+
head=["S.No","Point X","Coordinate X","Point Y","Coordinate Y","Point Z","Coordinate Z",
|
| 101 |
+
"CloudPoint Image","CX1","CY2","CZ3","Length","Width","Height",
|
| 102 |
+
"Asset Name","Asset ID","Asset Img","Remarks","Check","NX",
|
| 103 |
+
"Class Name","Confidence"]
|
| 104 |
+
for c,h in enumerate(head,1):
|
| 105 |
+
cell=ws.cell(row, c, h); cell.font=bold; cell.alignment=cent; cell.fill=hfill; cell.border=border
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
row+=1
|
| 107 |
+
corners,cen=cl["corners"],cl["centroid"]
|
| 108 |
+
L,W,H=cl["length"],cl["width"],cl["height"]; zmin=cl["zmin"]
|
| 109 |
+
cls="AIS Box" if zmin>=Z_THRESHOLD_ELEVATED else "Green Dustbin"
|
| 110 |
+
start=row
|
| 111 |
+
for n,pt in enumerate(corners,1):
|
| 112 |
+
vals=[n,pt[0],pt[0],pt[1],pt[1],pt[2],pt[2],"",cen[0],cen[1],cen[2],
|
| 113 |
+
L,W,H,ASSET_NAME,ASSET_ID,"","","","",cls,CONFIDENCE_SCORE_PLACEHOLDER]
|
| 114 |
+
for c,v in enumerate(vals,1):
|
| 115 |
+
ws.cell(row,c,v)
|
| 116 |
+
ws.cell(row,19,""); ws.cell(row,20,"") # make sure cells exist before dv
|
| 117 |
+
dv.add(ws.cell(row,19).coordinate); dv2.add(ws.cell(row,20).coordinate)
|
| 118 |
+
for c in range(1,23):
|
| 119 |
+
cell=ws.cell(row,c); cell.fill=dfill; cell.border=border
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
row+=1
|
| 121 |
+
if cl["preview_path"]:
|
| 122 |
+
img=XLImage(cl["preview_path"])
|
| 123 |
+
ws.add_image(img, f'H{start}')
|
| 124 |
+
for r in range(start,start+8): ws.row_dimensions[r].height=60
|
|
|
|
|
|
|
| 125 |
ws.column_dimensions['H'].width=20
|
|
|
|
| 126 |
row+=1
|
| 127 |
|
| 128 |
+
for col,w in zip("STUV",[10,10,15,12]): ws.column_dimensions[col].width=w
|
| 129 |
+
wb.save(xlsx); return xlsx
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
+
# βββββββββββββ DBSCAN helper
|
| 132 |
+
def estimate_eps(pts,sample=3000,k=8):
|
| 133 |
+
if len(pts)<=k: return 0.3
|
| 134 |
+
if len(pts)>sample: pts=pts[np.random.default_rng(42).choice(len(pts),sample,False)]
|
| 135 |
+
from sklearn.neighbors import NearestNeighbors
|
| 136 |
+
kth=NearestNeighbors(k).fit(pts).kneighbors(pts)[0][:,-1]
|
|
|
|
|
|
|
|
|
|
| 137 |
return float(np.percentile(kth,75))
|
| 138 |
|
| 139 |
+
# βββββββββββββ Gradio callbacks
|
| 140 |
+
def upload_cb(up,last):
|
| 141 |
+
if not up: return "No file.",gr.update(interactive=False),gr.update(visible=False),[None,None],{}
|
| 142 |
+
p=up.name
|
| 143 |
+
if not os.path.exists(p): return "Path error.",gr.update(interactive=False),gr.update(visible=False),[None,None],{}
|
| 144 |
+
sz,mt=os.path.getsize(p),os.path.getmtime(p)
|
| 145 |
+
if last.get('file_path')==p and last.get('file_size')==sz and last.get('mod_time')==mt:
|
| 146 |
+
return "Cached. Click Start Analysis.",gr.update(interactive=True),gr.update(visible=False),[last['pts'],last['cols']],last
|
| 147 |
+
tmp=tempfile.mkdtemp(prefix="pts_"); pts,cols=os.path.join(tmp,"pts.npy"),os.path.join(tmp,"cols.npy")
|
| 148 |
+
try: pts_to_npy(p,pts,cols)
|
| 149 |
+
except Exception as e: return f"Conversion error: {e}",gr.update(interactive=False),gr.update(visible=False),[None,None],{}
|
| 150 |
+
info={'file_path':p,'file_size':sz,'mod_time':mt,'pts':pts,'cols':cols}
|
| 151 |
+
return "Loaded. Click Start Analysis.",gr.update(interactive=True),gr.update(visible=False),[pts,cols],info
|
| 152 |
+
|
| 153 |
+
def analysis_cb(state,progress=gr.Progress(track_tqdm=True)):
|
| 154 |
+
if not state[0]: return "Upload first.",None,None,gr.update(interactive=False)
|
| 155 |
+
pts=np.load(state[0],mmap_mode='r'); cols=np.load(state[1],mmap_mode='r'); n=len(pts)
|
| 156 |
+
out=f"Total points: {n:,}\n"; progress(0.15,desc="green mask")
|
| 157 |
+
gmask=is_green(cols); gidx=np.nonzero(gmask)[0]; g=len(gidx); out+=f"Green: {g:,}\n"
|
| 158 |
+
if g==0: return "No green points.",None,None,gr.update(interactive=True)
|
| 159 |
+
|
| 160 |
+
# sampling
|
| 161 |
+
maxpts= g if g<=1000 else 1000 if g<=5000 else 2000 if g<=50_000 else 5000
|
| 162 |
+
hsv=rgb_to_hsv_array(cols[gidx]); sat=hsv[:,1]; order=np.argsort(-sat)
|
| 163 |
+
pri=int(len(order)*SAT_PRIORITY_FRAC); idx=order[:pri]
|
| 164 |
+
if g>maxpts:
|
| 165 |
+
rest=order[pri:]; need=maxpts-pri
|
| 166 |
+
idx=np.concatenate([idx, np.random.default_rng(123).choice(rest,need,False)]) if need>0 else idx
|
| 167 |
+
sample=gidx[idx]
|
| 168 |
+
db_pts=pts[sample]
|
| 169 |
+
|
| 170 |
+
eps1=max(0.15,min(0.45,estimate_eps(db_pts))); eps2=min(0.9,eps1*1.6); ms=DBSCAN_MIN_SAMPLES_DEFAULT
|
| 171 |
+
progress(0.35,desc="DBSCAN")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
lab1=DBSCAN(eps=eps1,min_samples=ms).fit(db_pts).labels_
|
| 173 |
lab2=DBSCAN(eps=eps2,min_samples=max(6,ms//2)).fit(db_pts).labels_
|
| 174 |
comb=lab1.copy(); comb[comb==-1]=lab2[comb==-1]
|
| 175 |
+
norm=np.full_like(comb,-1); for l in np.unique(comb):
|
| 176 |
+
if l!=-1: norm[comb==l]=np.sum(l>=0 and np.unique(comb[:l+1])>=0)-1
|
|
|
|
|
|
|
| 177 |
|
| 178 |
# region grow
|
| 179 |
+
bt=BallTree(pts[gidx],leaf_size=40); lab_full=np.full(len(gidx),-1,int)
|
|
|
|
| 180 |
for l in np.unique(norm):
|
| 181 |
if l==-1: continue
|
| 182 |
+
seeds_pos=[np.where(gidx==s)[0][0] for s in sample[norm==l]]
|
| 183 |
+
neighs=bt.query_radius(pts[gidx][seeds_pos],r=eps1*REGION_GROW_FACTOR)
|
| 184 |
+
for nbs in neighs: lab_full[nbs]=l
|
|
|
|
|
|
|
| 185 |
|
| 186 |
+
# clusters
|
| 187 |
clusters=[]
|
| 188 |
+
for l in np.unique(lab_full):
|
| 189 |
if l==-1: continue
|
| 190 |
+
pos=np.where(lab_full==l)[0]; abs_idx=gidx[pos]; cpts=pts[abs_idx]; ccols=cols[abs_idx]
|
| 191 |
+
corn,cen,L,W,H,zmin,zmax=bbox_metrics(cpts)
|
|
|
|
|
|
|
| 192 |
vol=L*W*H
|
| 193 |
if H<MIN_HEIGHT or L>MAX_LENGTH or W>MAX_WIDTH or vol<MIN_VOLUME: continue
|
| 194 |
+
if len(cpts)/(vol+1e-9)<MIN_DENSITY: continue
|
| 195 |
+
preview=preview_png(cpts,ccols, os.path.join(os.path.dirname(state[0]),f"prev_{uuid.uuid4().hex}.png"))
|
| 196 |
+
clusters.append(dict(corners=corn,centroid=cen,length=L,width=W,height=H,zmin=zmin,preview_path=preview))
|
| 197 |
+
out+=f"Detected {len(clusters)} objects\n"; progress(0.75,desc="visualisation")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
# plot
|
| 200 |
+
idx_show=np.random.default_rng(1).choice(n,PREVIEW_MAX_POINTS,False) if n>PREVIEW_MAX_POINTS else slice(None)
|
| 201 |
+
gshow=gidx if g<=PREVIEW_GREEN_MAX else np.random.default_rng(2).choice(gidx,PREVIEW_GREEN_MAX,False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
fig=go.Figure()
|
| 203 |
+
fig.add_trace(go.Scatter3d(x=pts[idx_show,0],y=pts[idx_show,1],z=pts[idx_show,2],
|
| 204 |
+
mode='markers',marker=dict(size=1,color=['rgb(%d,%d,%d)'%tuple(c) for c in cols[idx_show]]),
|
| 205 |
name='All',hoverinfo='none'))
|
| 206 |
+
fig.add_trace(go.Scatter3d(x=pts[gshow,0],y=pts[gshow,1],z=pts[gshow,2],
|
| 207 |
+
mode='markers',marker=dict(size=2,color=['rgb(%d,%d,%d)'%tuple(c) for c in cols[gshow]]),
|
| 208 |
name='Green',hoverinfo='none'))
|
| 209 |
+
for cl in clusters: add_bbox(fig,cl["corners"])
|
| 210 |
+
fig.update_layout(scene=dict(aspectmode='data'),height=800,margin=dict(l=0,r=0,t=0,b=0))
|
|
|
|
| 211 |
|
| 212 |
xlsx=None
|
| 213 |
+
if clusters: xlsx=excel(clusters, os.path.join(os.path.dirname(state[0]),"objects.xlsx"))
|
| 214 |
+
progress(1.0)
|
|
|
|
|
|
|
|
|
|
| 215 |
return out,fig,xlsx,gr.update(interactive=True)
|
| 216 |
|
| 217 |
+
# βββββββββββββ UI
|
|
|
|
| 218 |
with gr.Blocks(title="Detection") as demo:
|
| 219 |
gr.Markdown("# Green Dustbin & AIS Box Detection")
|
| 220 |
+
file_state, last_state = gr.State([None,None]), gr.State({})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
with gr.Row():
|
| 222 |
+
file = gr.File(label="Upload .pts (X Y Z R G B)")
|
| 223 |
with gr.Column():
|
| 224 |
+
log = gr.Textbox(lines=10,label="Log")
|
| 225 |
+
start = gr.Button("Start Analysis",interactive=False)
|
| 226 |
+
dl = gr.DownloadButton("Download Excel",visible=False)
|
| 227 |
+
plot = gr.Plot(label="3-D preview")
|
| 228 |
+
file.upload(upload_cb, [file,last_state], [log,start,dl,file_state,last_state], queue=False)
|
| 229 |
+
start.click(analysis_cb, [file_state], [log,plot,dl,start])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
demo.launch()
|