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