Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# app.py
|
| 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
|
|
@@ -14,7 +14,7 @@ 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
|
| 18 |
CONFIDENCE_SCORE_PLACEHOLDER = 1.0
|
| 19 |
CHUNK_SIZE = 1_000_000
|
| 20 |
ASSET_NAME, ASSET_ID = "Green Object", "3051047"
|
|
@@ -27,192 +27,218 @@ def pts_to_npy(src, pts_out, col_out):
|
|
| 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):
|
| 32 |
-
|
|
|
|
| 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)
|
| 40 |
-
|
|
|
|
| 41 |
h = np.zeros_like(maxc)
|
| 42 |
-
mask_r=(rgb[:,0]
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
h[
|
| 46 |
-
h=(
|
| 47 |
-
|
|
|
|
|
|
|
| 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)
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
| 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:
|
| 84 |
-
return None
|
| 85 |
|
| 86 |
-
# βββββββββββββ Excel writer
|
| 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,
|
| 106 |
row+=1
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
| 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 |
-
|
| 120 |
row+=1
|
|
|
|
| 121 |
if cl["preview_path"]:
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 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)>
|
| 135 |
-
|
| 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_")
|
| 148 |
-
|
| 149 |
-
|
|
|
|
| 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 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
comb
|
| 175 |
-
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,
|
| 197 |
-
|
|
|
|
|
|
|
| 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',
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
|
|
|
| 214 |
progress(1.0)
|
| 215 |
-
return out,fig,xlsx,gr.update(interactive=True)
|
| 216 |
|
| 217 |
# βββββββββββββ UI
|
| 218 |
with gr.Blocks(title="Detection") as demo:
|
|
@@ -221,10 +247,10 @@ with gr.Blocks(title="Detection") as demo:
|
|
| 221 |
with gr.Row():
|
| 222 |
file = gr.File(label="Upload .pts (X Y Z R G B)")
|
| 223 |
with gr.Column():
|
| 224 |
-
log
|
| 225 |
-
start = gr.Button("Start Analysis",interactive=False)
|
| 226 |
-
dl
|
| 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()
|
|
|
|
| 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
|
|
|
|
| 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
|
| 18 |
CONFIDENCE_SCORE_PLACEHOLDER = 1.0
|
| 19 |
CHUNK_SIZE = 1_000_000
|
| 20 |
ASSET_NAME, ASSET_ID = "Green Object", "3051047"
|
|
|
|
| 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):
|
| 32 |
+
continue
|
| 33 |
+
pts.append((x, y, z)); cols.append((r, g, b))
|
| 34 |
np.save(pts_out, np.asarray(pts, dtype=np.float32))
|
| 35 |
np.save(col_out, np.asarray(cols, dtype=np.uint8))
|
| 36 |
return pts_out, col_out
|
| 37 |
|
| 38 |
def rgb_to_hsv_array(rgb):
|
| 39 |
+
rgb = rgb.astype(np.float32) / 255
|
| 40 |
+
maxc, minc = rgb.max(1), rgb.min(1)
|
| 41 |
+
diff = maxc - minc
|
| 42 |
+
s = np.where(maxc > 0, diff / maxc, 0)
|
| 43 |
h = np.zeros_like(maxc)
|
| 44 |
+
mask_r = (rgb[:, 0] == maxc) & (diff > 0)
|
| 45 |
+
mask_g = (rgb[:, 1] == maxc) & (diff > 0)
|
| 46 |
+
mask_b = (rgb[:, 2] == maxc) & (diff > 0)
|
| 47 |
+
h[mask_r] = (rgb[mask_r, 1] - rgb[mask_r, 2]) / diff[mask_r]
|
| 48 |
+
h[mask_g] = 2 + (rgb[mask_g, 2] - rgb[mask_g, 0]) / diff[mask_g]
|
| 49 |
+
h[mask_b] = 4 + (rgb[mask_b, 0] - rgb[mask_b, 1]) / diff[mask_b]
|
| 50 |
+
h = (h / 6) % 1
|
| 51 |
+
return np.stack([h, s, maxc], 1)
|
| 52 |
|
| 53 |
def is_green(colors):
|
| 54 |
+
h, s, v = rgb_to_hsv_array(colors).T
|
| 55 |
+
return (0.22 < h) & (h < 0.48) & (s > 0.22) & (v > 0.12)
|
| 56 |
|
| 57 |
# βββββββββββββ geometry
|
| 58 |
def bbox_metrics(pts):
|
| 59 |
+
lo, hi = pts.min(0), pts.max(0)
|
| 60 |
+
cen = pts.mean(0)
|
| 61 |
+
L, W, H = hi - lo
|
| 62 |
+
corners = np.array([
|
| 63 |
+
[lo[0], lo[1], lo[2]], [lo[0], lo[1], hi[2]],
|
| 64 |
+
[lo[0], hi[1], lo[2]], [lo[0], hi[1], hi[2]],
|
| 65 |
+
[hi[0], lo[1], lo[2]], [hi[0], lo[1], hi[2]],
|
| 66 |
+
[hi[0], hi[1], lo[2]], [hi[0], hi[1], hi[2]],
|
| 67 |
+
])
|
| 68 |
+
return corners, cen, float(L), float(W), float(H), float(lo[2]), float(hi[2])
|
| 69 |
+
|
| 70 |
+
def add_bbox(fig, corners, color='red'):
|
| 71 |
+
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)]
|
| 72 |
+
for s, e in edges:
|
| 73 |
+
fig.add_trace(go.Scatter3d(
|
| 74 |
+
x=[corners[s,0], corners[e,0]],
|
| 75 |
+
y=[corners[s,1], corners[e,1]],
|
| 76 |
+
z=[corners[s,2], corners[e,2]],
|
| 77 |
+
mode='lines',
|
| 78 |
+
line=dict(color=color, width=4),
|
| 79 |
+
showlegend=False))
|
| 80 |
+
|
| 81 |
+
# βββββββββββββ preview PNG (safe if kaleido missing)
|
| 82 |
+
def preview_png(pts, cols, out, size=(500,500), down=200_000):
|
| 83 |
try:
|
| 84 |
+
if len(pts) > down:
|
| 85 |
+
idx = np.random.default_rng(0).choice(len(pts), down, False)
|
| 86 |
+
pts, cols = pts[idx], cols[idx]
|
| 87 |
+
fig = go.Figure(go.Scatter3d(
|
| 88 |
+
x=pts[:,0], y=pts[:,1], z=pts[:,2],
|
| 89 |
+
mode='markers',
|
| 90 |
+
marker=dict(size=2, color=[f'rgb({r},{g},{b})' for r,g,b in cols])))
|
| 91 |
+
fig.update_layout(scene=dict(aspectmode='data',
|
| 92 |
+
xaxis=dict(visible=False),
|
| 93 |
+
yaxis=dict(visible=False),
|
| 94 |
+
zaxis=dict(visible=False)),
|
| 95 |
margin=dict(l=0,r=0,t=0,b=0),
|
| 96 |
+
width=size[0], height=size[1])
|
| 97 |
+
with open(out, 'wb') as f:
|
| 98 |
+
f.write(pio.to_image(fig, format='png'))
|
| 99 |
return out
|
| 100 |
+
except Exception:
|
| 101 |
+
return None # kaleido not available β skip image
|
| 102 |
|
| 103 |
+
# βββββββββββββ Excel writer
|
| 104 |
def excel(clusters, xlsx):
|
| 105 |
+
wb = openpyxl.Workbook(); ws = wb.active; ws.title = "Detected Green Objects"
|
| 106 |
+
hfill = PatternFill("solid", "E0E0E0"); dfill = PatternFill("solid", "F2F2F2")
|
| 107 |
+
bold = Font(bold=True); cent = Alignment(horizontal="center", vertical="center")
|
| 108 |
+
thin = Side("thin", "000"); border = Border(top=thin, bottom=thin, left=thin, right=thin)
|
| 109 |
+
dv = DataValidation(type="list", formula1='"Ok,Not Ok"', allow_blank=True)
|
| 110 |
+
dv2 = DataValidation(type="list", formula1='"Ok,Not Ok"', allow_blank=True)
|
| 111 |
ws.add_data_validation(dv); ws.add_data_validation(dv2)
|
| 112 |
|
| 113 |
+
row = 1
|
| 114 |
+
for i, cl in enumerate(clusters, 1):
|
| 115 |
+
ws.merge_cells(row, row, 1, 22); ws.cell(row,1,"Cloud Point Creation").font=Font(bold=True,size=12); row+=1
|
| 116 |
+
ws.merge_cells(row, row, 1, 22); ws.cell(row,1,f"Object {i}").font=Font(bold=True,size=11); row+=1
|
| 117 |
head=["S.No","Point X","Coordinate X","Point Y","Coordinate Y","Point Z","Coordinate Z",
|
| 118 |
"CloudPoint Image","CX1","CY2","CZ3","Length","Width","Height",
|
| 119 |
"Asset Name","Asset ID","Asset Img","Remarks","Check","NX",
|
| 120 |
"Class Name","Confidence"]
|
| 121 |
for c,h in enumerate(head,1):
|
| 122 |
+
cell=ws.cell(row,c,h); cell.font=bold; cell.alignment=cent; cell.fill=hfill; cell.border=border
|
| 123 |
row+=1
|
| 124 |
+
|
| 125 |
+
corners,cen = cl["corners"], cl["centroid"]
|
| 126 |
+
L,W,H = cl["length"], cl["width"], cl["height"]; zmin = cl["zmin"]
|
| 127 |
+
cls = "AIS Box" if zmin >= Z_THRESHOLD_ELEVATED else "Green Dustbin"
|
| 128 |
+
start = row
|
| 129 |
+
|
| 130 |
+
for n, pt in enumerate(corners, 1):
|
| 131 |
+
vals=[n,pt[0],pt[0],pt[1],pt[1],pt[2],pt[2],"",
|
| 132 |
+
cen[0],cen[1],cen[2],L,W,H,ASSET_NAME,ASSET_ID,"","","","",cls,CONFIDENCE_SCORE_PLACEHOLDER]
|
| 133 |
for c,v in enumerate(vals,1):
|
| 134 |
ws.cell(row,c,v)
|
|
|
|
| 135 |
dv.add(ws.cell(row,19).coordinate); dv2.add(ws.cell(row,20).coordinate)
|
| 136 |
for c in range(1,23):
|
| 137 |
+
ws.cell(row,c).fill=dfill; ws.cell(row,c).border=border
|
| 138 |
row+=1
|
| 139 |
+
|
| 140 |
if cl["preview_path"]:
|
| 141 |
+
ws.add_image(XLImage(cl["preview_path"]), f'H{start}')
|
| 142 |
+
for r in range(start, start+8): ws.row_dimensions[r].height = 60
|
| 143 |
+
ws.column_dimensions['H'].width = 20
|
|
|
|
| 144 |
row+=1
|
| 145 |
|
| 146 |
+
for col,w in zip("STUV",[10,10,15,12]): ws.column_dimensions[col].width = w
|
| 147 |
wb.save(xlsx); return xlsx
|
| 148 |
|
| 149 |
# βββββββββββββ DBSCAN helper
|
| 150 |
+
def estimate_eps(pts, sample=3000, k=8):
|
| 151 |
+
if len(pts) <= k: return 0.3
|
| 152 |
+
if len(pts) > sample:
|
| 153 |
+
pts = pts[np.random.default_rng(42).choice(len(pts), sample, False)]
|
| 154 |
+
kth = NearestNeighbors(k).fit(pts).kneighbors(pts)[0][:,-1]
|
| 155 |
+
return float(np.percentile(kth, 75))
|
| 156 |
|
| 157 |
# βββββββββββββ Gradio callbacks
|
| 158 |
+
def upload_cb(up, last):
|
| 159 |
+
if not up: return "No file.", gr.update(interactive=False), gr.update(visible=False), [None,None], {}
|
| 160 |
+
p = up.name
|
| 161 |
+
if not os.path.exists(p): return "Path error.", gr.update(interactive=False), gr.update(visible=False), [None,None], {}
|
| 162 |
+
sz, mt = os.path.getsize(p), os.path.getmtime(p)
|
| 163 |
+
if last.get('file_path') == p and last.get('file_size') == sz and last.get('mod_time') == mt:
|
| 164 |
+
return "Cached. Click Start Analysis.", gr.update(interactive=True), gr.update(visible=False), [last['pts'], last['cols']], last
|
| 165 |
+
tmp = tempfile.mkdtemp(prefix="pts_")
|
| 166 |
+
pts, cols = os.path.join(tmp,"pts.npy"), os.path.join(tmp,"cols.npy")
|
| 167 |
+
try: pts_to_npy(p, pts, cols)
|
| 168 |
+
except Exception as e: return f"Conversion error: {e}", gr.update(interactive=False), gr.update(visible=False), [None,None], {}
|
| 169 |
info={'file_path':p,'file_size':sz,'mod_time':mt,'pts':pts,'cols':cols}
|
| 170 |
+
return "Loaded. Click Start Analysis.", gr.update(interactive=True), gr.update(visible=False), [pts,cols], info
|
| 171 |
|
| 172 |
+
def analysis_cb(state, progress=gr.Progress(track_tqdm=True)):
|
| 173 |
+
if not state[0]: return "Upload first.", None, None, gr.update(interactive=False)
|
| 174 |
+
pts = np.load(state[0], mmap_mode='r'); cols = np.load(state[1], mmap_mode='r'); n=len(pts)
|
| 175 |
+
out=f"Total points: {n:,}\n"; progress(0.15, desc="green mask")
|
| 176 |
+
gmask = is_green(cols); gidx = np.nonzero(gmask)[0]; g=len(gidx); out+=f"Green: {g:,}\n"
|
| 177 |
+
if g == 0: return "No green points.", None, None, gr.update(interactive=True)
|
| 178 |
|
| 179 |
# sampling
|
| 180 |
+
maxpts = g if g<=1000 else 1000 if g<=5000 else 2000 if g<=50_000 else 5000
|
| 181 |
+
hsv = rgb_to_hsv_array(cols[gidx]); sat = hsv[:,1]; order = np.argsort(-sat)
|
| 182 |
+
pri = int(len(order)*SAT_PRIORITY_FRAC); idx = order[:pri]
|
| 183 |
+
if g > maxpts:
|
| 184 |
+
rest = order[pri:]; need = maxpts - pri
|
| 185 |
+
idx = np.concatenate([idx, np.random.default_rng(123).choice(rest, need, False)]) if need>0 else idx
|
| 186 |
+
sample = gidx[idx]; db_pts = pts[sample]
|
| 187 |
+
|
| 188 |
+
eps1 = max(0.15, min(0.45, estimate_eps(db_pts))); eps2 = min(0.9, eps1*1.6); ms = DBSCAN_MIN_SAMPLES_DEFAULT
|
| 189 |
+
progress(0.35, desc="DBSCAN")
|
| 190 |
+
lab1 = DBSCAN(eps=eps1, min_samples=ms).fit(db_pts).labels_
|
| 191 |
+
lab2 = DBSCAN(eps=eps2, min_samples=max(6, ms//2)).fit(db_pts).labels_
|
| 192 |
+
comb = lab1.copy()
|
| 193 |
+
comb[comb == -1] = lab2[comb == -1]
|
| 194 |
+
|
| 195 |
+
# re-index labels to 0,1,2β¦ (-1 stays noise)
|
| 196 |
+
norm = np.full_like(comb, -1)
|
| 197 |
+
unique_labels = [lab for lab in np.unique(comb) if lab != -1]
|
| 198 |
+
for new_id, lab in enumerate(unique_labels):
|
| 199 |
+
norm[comb == lab] = new_id
|
| 200 |
|
| 201 |
# region grow
|
| 202 |
+
bt = BallTree(pts[gidx], leaf_size=40); lab_full = np.full(len(gidx), -1, int)
|
| 203 |
for l in np.unique(norm):
|
| 204 |
+
if l == -1: continue
|
| 205 |
+
seeds_pos = [np.where(gidx == s)[0][0] for s in sample[norm == l]]
|
| 206 |
+
neighs = bt.query_radius(pts[gidx][seeds_pos], r=eps1*REGION_GROW_FACTOR)
|
| 207 |
+
for nbs in neighs: lab_full[nbs] = l
|
| 208 |
|
| 209 |
# clusters
|
| 210 |
+
clusters = []
|
| 211 |
for l in np.unique(lab_full):
|
| 212 |
+
if l == -1: continue
|
| 213 |
+
pos = np.where(lab_full == l)[0]; abs_idx = gidx[pos]; cpts = pts[abs_idx]; ccols = cols[abs_idx]
|
| 214 |
+
corn, cen, L, W, H, zmin, zmax = bbox_metrics(cpts)
|
| 215 |
+
vol = L*W*H
|
| 216 |
if H<MIN_HEIGHT or L>MAX_LENGTH or W>MAX_WIDTH or vol<MIN_VOLUME: continue
|
| 217 |
+
if len(cpts)/(vol+1e-9) < MIN_DENSITY: continue
|
| 218 |
+
preview = preview_png(cpts, ccols, os.path.join(os.path.dirname(state[0]), f"prev_{uuid.uuid4().hex}.png"))
|
| 219 |
+
clusters.append(dict(corners=corn, centroid=cen, length=L, width=W, height=H,
|
| 220 |
+
zmin=zmin, preview_path=preview))
|
| 221 |
+
|
| 222 |
+
out += f"Detected {len(clusters)} objects\n"; progress(0.75, desc="visualisation")
|
| 223 |
|
| 224 |
# plot
|
| 225 |
+
idx_show = np.random.default_rng(1).choice(n, PREVIEW_MAX_POINTS, False) if n>PREVIEW_MAX_POINTS else slice(None)
|
| 226 |
+
gshow = gidx if g<=PREVIEW_GREEN_MAX else np.random.default_rng(2).choice(gidx, PREVIEW_GREEN_MAX, False)
|
| 227 |
+
fig = go.Figure()
|
| 228 |
+
fig.add_trace(go.Scatter3d(x=pts[idx_show,0], y=pts[idx_show,1], z=pts[idx_show,2],
|
| 229 |
+
mode='markers',
|
| 230 |
+
marker=dict(size=1, color=[f'rgb({r},{g},{b})' for r,g,b in cols[idx_show]]),
|
| 231 |
+
name='All', hoverinfo='none'))
|
| 232 |
+
fig.add_trace(go.Scatter3d(x=pts[gshow,0], y=pts[gshow,1], z=pts[gshow,2],
|
| 233 |
+
mode='markers',
|
| 234 |
+
marker=dict(size=2, color=[f'rgb({r},{g},{b})' for r,g,b in cols[gshow]]),
|
| 235 |
+
name='Green', hoverinfo='none'))
|
| 236 |
+
for cl in clusters: add_bbox(fig, cl["corners"])
|
| 237 |
+
fig.update_layout(scene=dict(aspectmode='data'), height=800, margin=dict(l=0,r=0,t=0,b=0))
|
| 238 |
+
|
| 239 |
+
xlsx = excel(clusters, os.path.join(os.path.dirname(state[0]), "objects.xlsx")) if clusters else None
|
| 240 |
progress(1.0)
|
| 241 |
+
return out, fig, xlsx, gr.update(interactive=True)
|
| 242 |
|
| 243 |
# βββββββββββββ UI
|
| 244 |
with gr.Blocks(title="Detection") as demo:
|
|
|
|
| 247 |
with gr.Row():
|
| 248 |
file = gr.File(label="Upload .pts (X Y Z R G B)")
|
| 249 |
with gr.Column():
|
| 250 |
+
log = gr.Textbox(lines=10, label="Log")
|
| 251 |
+
start = gr.Button("Start Analysis", interactive=False)
|
| 252 |
+
dl = gr.DownloadButton("Download Excel", visible=False)
|
| 253 |
plot = gr.Plot(label="3-D preview")
|
| 254 |
+
file.upload(upload_cb, [file, last_state], [log, start, dl, file_state, last_state], queue=False)
|
| 255 |
+
start.click(analysis_cb, [file_state], [log, plot, dl, start])
|
| 256 |
demo.launch()
|