File size: 13,490 Bytes
995a7e5
4edea97
2593b70
 
 
 
 
 
4edea97
 
 
 
 
 
 
 
0af054b
4edea97
 
 
 
 
 
ef1061f
4edea97
 
 
995a7e5
 
ef1061f
995a7e5
 
0af054b
 
995a7e5
 
4edea97
 
 
 
995a7e5
4edea97
0af054b
 
 
 
2593b70
0af054b
 
 
 
 
 
 
 
ef1061f
995a7e5
4edea97
0af054b
 
4edea97
 
 
0af054b
 
 
 
 
 
 
 
 
 
 
995a7e5
0af054b
 
 
 
 
 
 
 
 
 
 
995a7e5
0af054b
4edea97
0af054b
 
 
 
 
 
995a7e5
 
0af054b
 
 
 
4edea97
0af054b
 
 
4edea97
0af054b
 
4edea97
995a7e5
0af054b
4edea97
995a7e5
 
 
 
 
 
 
 
 
 
 
0af054b
 
4edea97
ef1061f
0af054b
995a7e5
 
 
 
 
 
 
 
 
 
 
 
ef1061f
0af054b
 
 
 
995a7e5
0af054b
 
 
995a7e5
 
 
 
 
 
 
 
 
 
ef1061f
0af054b
4edea97
995a7e5
 
 
0af054b
ef1061f
 
995a7e5
 
 
 
 
ef1061f
4edea97
0af054b
 
 
 
995a7e5
0af054b
ef1061f
4edea97
0af054b
995a7e5
 
0af054b
995a7e5
 
0af054b
 
995a7e5
 
 
0af054b
 
995a7e5
 
 
 
 
 
 
 
 
4edea97
0af054b
995a7e5
 
 
 
 
 
 
 
 
 
 
 
 
 
4edea97
 
0af054b
 
995a7e5
 
0af054b
995a7e5
 
 
 
 
 
0af054b
995a7e5
 
 
0af054b
 
 
 
 
 
995a7e5
0af054b
995a7e5
0af054b
ef1061f
 
995a7e5
 
ef1061f
995a7e5
 
0af054b
 
995a7e5
 
ef1061f
4edea97
0af054b
4edea97
995a7e5
 
 
 
 
0af054b
995a7e5
 
 
 
 
 
 
 
 
 
 
ef1061f
 
995a7e5
 
 
 
0af054b
995a7e5
 
 
 
 
 
 
 
 
 
 
 
 
 
0af054b
 
4edea97
0af054b
ef1061f
4edea97
2593b70
 
4edea97
2593b70
4edea97
2593b70
0af054b
 
 
4edea97
995a7e5
 
 
 
 
 
 
3370762
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# app.py  – stable version with proper merge_cells syntax
import gradio as gr, numpy as np, os, uuid, tempfile, csv, plotly.graph_objects as go
import plotly.io as pio
from sklearn.cluster import DBSCAN
from sklearn.neighbors import NearestNeighbors, BallTree
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.drawing.image import Image as XLImage
from openpyxl.worksheet.datavalidation import DataValidation

# ───────────── parameters
PREVIEW_MAX_POINTS, PREVIEW_GREEN_MAX = 80_000, 50_000
MIN_HEIGHT, MAX_LENGTH, MAX_WIDTH     = 0.05, 2.0, 2.0
DBSCAN_MIN_SAMPLES_DEFAULT            = 12
SAT_PRIORITY_FRAC,  REGION_GROW_FACTOR = 0.5, 1.2
MIN_VOLUME, MIN_DENSITY               = 0.001, 5
Z_THRESHOLD_ELEVATED                  = 0.5
CONFIDENCE_SCORE_PLACEHOLDER          = 1.0
CHUNK_SIZE                            = 1_000_000
ASSET_NAME, ASSET_ID                  = "Green Object", "3051047"

# ───────────── I/O helpers
def pts_to_npy(src, pts_out, col_out):
    pts, cols = [], []
    with open(src, newline='') as f:
        rdr = csv.reader(f, delimiter=' ')
        for row in rdr:
            if not row or row[0].startswith('#'):
                continue
            try:
                x, y, z = map(float, row[:3])
                r, g, b = map(int, row[3:6])
            except (ValueError, IndexError):
                continue
            pts.append((x, y, z))
            cols.append((r, g, b))
    np.save(pts_out, np.asarray(pts,  dtype=np.float32))
    np.save(col_out, np.asarray(cols, dtype=np.uint8))
    return pts_out, col_out


def rgb_to_hsv_array(rgb):
    rgb = rgb.astype(np.float32) / 255
    maxc, minc = rgb.max(1), rgb.min(1)
    diff = maxc - minc
    s = np.where(maxc > 0, diff / maxc, 0)
    h = np.zeros_like(maxc)
    mask_r = (rgb[:, 0] == maxc) & (diff > 0)
    mask_g = (rgb[:, 1] == maxc) & (diff > 0)
    mask_b = (rgb[:, 2] == maxc) & (diff > 0)
    h[mask_r] = (rgb[mask_r, 1] - rgb[mask_r, 2]) / diff[mask_r]
    h[mask_g] = 2 + (rgb[mask_g, 2] - rgb[mask_g, 0]) / diff[mask_g]
    h[mask_b] = 4 + (rgb[mask_b, 0] - rgb[mask_b, 1]) / diff[mask_b]
    h = (h / 6) % 1
    return np.stack([h, s, maxc], 1)


def is_green(colors):
    h, s, v = rgb_to_hsv_array(colors).T
    return (0.22 < h) & (h < 0.48) & (s > 0.22) & (v > 0.12)

# ───────────── geometry
def bbox_metrics(pts):
    lo, hi = pts.min(0), pts.max(0)
    cen = pts.mean(0)
    L, W, H = hi - lo
    corners = np.array([
        [lo[0], lo[1], lo[2]], [lo[0], lo[1], hi[2]],
        [lo[0], hi[1], lo[2]], [lo[0], hi[1], hi[2]],
        [hi[0], lo[1], lo[2]], [hi[0], lo[1], hi[2]],
        [hi[0], hi[1], lo[2]], [hi[0], hi[1], hi[2]],
    ])
    return corners, cen, float(L), float(W), float(H), float(lo[2]), float(hi[2])


def add_bbox(fig, corners, color='red'):
    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)]
    for s, e in edges:
        fig.add_trace(go.Scatter3d(
            x=[corners[s,0], corners[e,0]],
            y=[corners[s,1], corners[e,1]],
            z=[corners[s,2], corners[e,2]],
            mode='lines',
            line=dict(color=color, width=4),
            showlegend=False))

# ───────────── preview PNG  (safe: doesn’t crash if kaleido missing)
def preview_png(pts, cols, out, size=(500,500), down=200_000):
    try:
        if len(pts) > down:
            idx = np.random.default_rng(0).choice(len(pts), down, False)
            pts, cols = pts[idx], cols[idx]
        fig = go.Figure(go.Scatter3d(
            x=pts[:,0], y=pts[:,1], z=pts[:,2],
            mode='markers',
            marker=dict(size=2,
                        color=[f'rgb({r},{g},{b})' for r,g,b in cols])))
        fig.update_layout(scene=dict(aspectmode='data',
                                     xaxis=dict(visible=False),
                                     yaxis=dict(visible=False),
                                     zaxis=dict(visible=False)),
                          margin=dict(l=0,r=0,t=0,b=0),
                          width=size[0], height=size[1])
        with open(out, 'wb') as f:
            f.write(pio.to_image(fig, format='png'))
        return out
    except Exception:
        return None   # kaleido not available – skip image


# ───────────── Excel writer
def excel(clusters, xlsx):
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "Detected Green Objects"

    hfill = PatternFill("solid", "E0E0E0")
    dfill = PatternFill("solid", "F2F2F2")
    bold  = Font(bold=True)
    cent  = Alignment(horizontal="center", vertical="center")
    thin  = Side("thin", "000000")
    border= Border(top=thin, bottom=thin, left=thin, right=thin)

    dv  = DataValidation(type="list", formula1='"Ok,Not Ok"', allow_blank=True)
    dv2 = DataValidation(type="list", formula1='"Ok,Not Ok"', allow_blank=True)
    ws.add_data_validation(dv); ws.add_data_validation(dv2)

    row = 1
    for idx, cl in enumerate(clusters, 1):
        ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=22)
        ws.cell(row,1,"Cloud Point Creation").font=Font(bold=True,size=12); row+=1
        ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=22)
        ws.cell(row,1,f"Object {idx}").font=Font(bold=True,size=11); row+=1

        headers=["S.No","Point X","Coordinate X","Point Y","Coordinate Y","Point Z","Coordinate Z",
                 "CloudPoint Image","CX1","CY2","CZ3","Length","Width","Height",
                 "Asset Name","Asset ID","Asset Img","Remarks","Check","NX",
                 "Class Name","Confidence"]
        for col,h in enumerate(headers,1):
            c=ws.cell(row,col,h); c.font=bold; c.alignment=cent; c.fill=hfill; c.border=border
        row+=1

        corners,cen = cl["corners"], cl["centroid"]
        L,W,H = cl["length"], cl["width"], cl["height"]; zmin = cl["zmin"]
        cls = "AIS Box" if zmin >= Z_THRESHOLD_ELEVATED else "Green Dustbin"
        start_data_row = row

        for n, pt in enumerate(corners, 1):
            vals=[n,pt[0],pt[0],pt[1],pt[1],pt[2],pt[2],"",
                  cen[0],cen[1],cen[2],L,W,H,
                  ASSET_NAME,ASSET_ID,"","","","",
                  cls,CONFIDENCE_SCORE_PLACEHOLDER]
            for col,v in enumerate(vals,1):
                ws.cell(row,col,v)
            # add dropdowns
            dv.add(ws.cell(row,19).coordinate)
            dv2.add(ws.cell(row,20).coordinate)
            for col in range(1,23):
                c=ws.cell(row,col); c.fill=dfill; c.border=border
            row+=1

        if cl["preview_path"]:
            ws.add_image(XLImage(cl["preview_path"]), f'H{start_data_row}')
            for r in range(start_data_row, start_data_row+8):
                ws.row_dimensions[r].height = 60
            ws.column_dimensions['H'].width = 20
        row+=1

    # widths for new columns
    for col, w in zip("STUV", (10,10,15,12)):
        ws.column_dimensions[col].width = w
    wb.save(xlsx)
    return xlsx

# ───────────── DBSCAN helper
def estimate_eps(pts, sample=3000, k=8):
    if len(pts) <= k: return 0.3
    if len(pts) > sample:
        pts = pts[np.random.default_rng(42).choice(len(pts), sample, False)]
    kth = NearestNeighbors(k).fit(pts).kneighbors(pts)[0][:, -1]
    return float(np.percentile(kth, 75))

# ───────────── Gradio callbacks
def upload_cb(up, last):
    if not up:
        return "No file.", gr.update(interactive=False), gr.update(visible=False), [None,None], {}
    p = up.name
    if not os.path.exists(p):
        return "Path error.", gr.update(interactive=False), gr.update(visible=False), [None,None], {}
    sz, mt = os.path.getsize(p), os.path.getmtime(p)
    if last.get('file_path') == p and last.get('file_size') == sz and last.get('mod_time') == mt:
        return ("Cached. Click Start Analysis.",
                gr.update(interactive=True), gr.update(visible=False),
                [last['pts'], last['cols']], last)
    tmp = tempfile.mkdtemp(prefix="pts_")
    pts, cols = os.path.join(tmp,"pts.npy"), os.path.join(tmp,"cols.npy")
    try:
        pts_to_npy(p, pts, cols)
    except Exception as e:
        return f"Conversion error: {e}", gr.update(interactive=False), gr.update(visible=False), [None,None], {}
    info = {'file_path':p,'file_size':sz,'mod_time':mt,'pts':pts,'cols':cols}
    return ("Loaded. Click Start Analysis.",
            gr.update(interactive=True), gr.update(visible=False),
            [pts, cols], info)


def analysis_cb(state, progress=gr.Progress(track_tqdm=True)):
    if not state[0]:
        return "Upload first.", None, None, gr.update(interactive=False)
    pts = np.load(state[0], mmap_mode='r')
    cols = np.load(state[1], mmap_mode='r')
    n = len(pts)
    out = f"Total points: {n:,}\n"
    progress(0.15, desc="Green mask")

    gmask = is_green(cols)
    gidx = np.nonzero(gmask)[0]
    g = len(gidx)
    out += f"Green: {g:,}\n"
    if g == 0:
        return "No green points.", None, None, gr.update(interactive=True)

    # sampling
    maxpts = g if g<=1000 else 1000 if g<=5000 else 2000 if g<=50_000 else 5000
    hsv = rgb_to_hsv_array(cols[gidx]); sat = hsv[:,1]; order = np.argsort(-sat)
    pri = int(len(order) * SAT_PRIORITY_FRAC)
    idx = order[:pri]
    if g > maxpts:
        rest = order[pri:]
        need = maxpts - pri
        idx = np.concatenate([idx,
                              np.random.default_rng(123).choice(rest, need, False)]) if need > 0 else idx
    sample = gidx[idx]
    db_pts = pts[sample]

    eps1 = max(0.15, min(0.45, estimate_eps(db_pts)))
    eps2 = min(0.9, eps1 * 1.6)
    ms = DBSCAN_MIN_SAMPLES_DEFAULT
    progress(0.35, desc="DBSCAN")
    lab1 = DBSCAN(eps=eps1, min_samples=ms).fit(db_pts).labels_
    lab2 = DBSCAN(eps=eps2, min_samples=max(6, ms//2)).fit(db_pts).labels_
    comb = lab1.copy()
    comb[comb == -1] = lab2[comb == -1]

    # re-index labels to 0,1,2…  (-1 remains noise)
    norm = np.full_like(comb, -1)
    for new_id, lab in enumerate([l for l in np.unique(comb) if l != -1]):
        norm[comb == lab] = new_id

    # region grow
    bt = BallTree(pts[gidx], leaf_size=40)
    lab_full = np.full(len(gidx), -1, int)
    for l in np.unique(norm):
        if l == -1:
            continue
        seeds_pos = [np.where(gidx == s)[0][0] for s in sample[norm == l]]
        neighs = bt.query_radius(pts[gidx][seeds_pos], r=eps1*REGION_GROW_FACTOR)
        for nb in neighs:
            lab_full[nb] = l

    # clusters
    clusters = []
    for l in np.unique(lab_full):
        if l == -1:
            continue
        pos = np.where(lab_full == l)[0]
        abs_idx = gidx[pos]
        cpts, ccols = pts[abs_idx], cols[abs_idx]
        corn, cen, L, W, H, zmin, zmax = bbox_metrics(cpts)
        vol = L * W * H
        if H < MIN_HEIGHT or L > MAX_LENGTH or W > MAX_WIDTH or vol < MIN_VOLUME:
            continue
        if len(cpts) / (vol + 1e-9) < MIN_DENSITY:
            continue
        preview = preview_png(cpts, ccols,
                              os.path.join(os.path.dirname(state[0]), f"prev_{uuid.uuid4().hex}.png"))
        clusters.append(dict(corners=corn, centroid=cen, length=L, width=W,
                             height=H, zmin=zmin, preview_path=preview))
    out += f"Detected {len(clusters)} objects\n"
    progress(0.75, desc="Visualisation")

    # plot
    idx_show = (np.random.default_rng(1).choice(n, PREVIEW_MAX_POINTS, False)
                if n > PREVIEW_MAX_POINTS else slice(None))
    gshow = (gidx if g <= PREVIEW_GREEN_MAX
             else np.random.default_rng(2).choice(gidx, PREVIEW_GREEN_MAX, False))
    fig = go.Figure()
    fig.add_trace(go.Scatter3d(
        x=pts[idx_show,0], y=pts[idx_show,1], z=pts[idx_show,2],
        mode='markers',
        marker=dict(size=1, color=[f'rgb({r},{g},{b})' for r,g,b in cols[idx_show]]),
        name='All', hoverinfo='none'))
    fig.add_trace(go.Scatter3d(
        x=pts[gshow,0], y=pts[gshow,1], z=pts[gshow,2],
        mode='markers',
        marker=dict(size=2, color=[f'rgb({r},{g},{b})' for r,g,b in cols[gshow]]),
        name='Green', hoverinfo='none'))
    for cl in clusters:
        add_bbox(fig, cl["corners"])
    fig.update_layout(scene=dict(aspectmode='data'), height=800,
                      margin=dict(l=0,r=0,t=0,b=0))

    xlsx = excel(clusters, os.path.join(os.path.dirname(state[0]), "objects.xlsx")) if clusters else None
    progress(1.0)
    return out, fig, xlsx, gr.update(interactive=True)

# ───────────── UI
with gr.Blocks(title="Detection") as demo:
    gr.Markdown("# Green Dustbin & AIS Box Detection")
    file_state, last_state = gr.State([None,None]), gr.State({})
    with gr.Row():
        file = gr.File(label="Upload .pts (X Y Z R G B)")
        with gr.Column():
            log   = gr.Textbox(lines=10, label="Log")
            start = gr.Button("Start Analysis", interactive=False)
            dl    = gr.DownloadButton("Download Excel", visible=False)
    plot = gr.Plot(label="3-D preview")
    file.upload(upload_cb,
                inputs=[file, last_state],
                outputs=[log, start, dl, file_state, last_state],
                queue=False)
    start.click(analysis_cb,
                inputs=[file_state],
                outputs=[log, plot, dl, start])
demo.launch()