File size: 33,019 Bytes
5121eca
 
490858f
5121eca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490858f
5121eca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490858f
5121eca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
#!/usr/bin/env python3
"""
Automatic labeling for registered RGB/IR frame pairs (the layout of HotSight's Data/ folder).

Given a clip folder from the dataset —
    <Unit>/<Clip>/rgb/fNNNNN.png          RGB frame (2688x1512)
    <Unit>/<Clip>/ir/fNNNNN.png           colorized IR frame (640x360)
    <Unit>/<Clip>/homography/homography.json
                                          IR_pixel -> RGB_pixel homographies,
                                          one matrix per frame-range subset
— this tool predicts a dense per-pixel label mask for each RGB/IR pair and
saves it following the dataset's own conventions.

Method (unchanged from the original YOLO+IR+SAM pipeline):
  1. A trained YOLOv8 model (best.pt) detects boxes on the RGB frame (conf 0.25).
  2. The IR frame is thresholded for red/white hotspots; each hotspot's bounding
     box is mapped into RGB pixel space using the clip's homography (the
     registration shipped with the dataset — no registration is computed here).
  3. Fusion: an IR hotspot overlapping a YOLO box of internal class 0/1/2
     (IoU >= 0.1) boosts that box to conf*RGB_SPLIT + IR_SPLIT
     (RGB_SPLIT=0.57, IR_SPLIT=0.43); IR hotspots YOLO missed are added as new
     boxes at IR_SPLIT confidence. Per-class confidence thresholds then drop
     weak boxes.
  4. Surviving boxes prompt SAM (vit_b); masks accumulate per class and
     overlaps resolve with strict priority (class 1 on top ... class 5 bottom).
  5. KNN majority vote + DBSCAN smoothing assign a class to every remaining
     pixel, producing a dense label map.

Class ids: the model works internally with YOLO classes 0-4; all saved outputs
use the dataset's 1-5 convention (internal id + 1):
    1 = red, 2 = orange, 3 = yellow, 4 = green, 5 = black

Outputs, mirroring the dataset layout under --out:
    <out>/<Unit>/<Clip>/mask/fNNNNN.txt          predicted labels — one digit
                                                 (1-5) per pixel, row-major,
                                                 single line, no separators
                                                 (same format as dataset masks)
    <out>/<Unit>/<Clip>/mask_overlay/fNNNNN.jpg  label overlay on the RGB frame
                                                 (dataset overlay style)
    <out>/<Unit>/<Clip>/mask_color/fNNNNN.png    pure-color label image
    <out>/<Unit>/<Clip>/rgb/, ir/, homography/   copies of the inputs, so the
                                                 output folder is self-contained
                                                 and loads in viewer.html

Usage:
    python auto_annotate.py --dataset ../../Data \
        --clip Graminoid-08 --frames f00300
    python auto_annotate.py --dataset <root> --clip Canopy-10          (whole clip)
    python auto_annotate.py --dataset <root> --all                     (everything)

Requires: ultralytics, segment-anything, torch, opencv-python, scikit-learn.
The SAM vit_b checkpoint (~375 MB) is downloaded automatically if missing.
"""

import argparse
import csv
import glob
import json
import os
import re
import shutil
import sys
import urllib.request

import cv2
import numpy as np
import torch
from segment_anything import SamPredictor, sam_model_registry
from sklearn.cluster import DBSCAN
from sklearn.neighbors import KDTree
from sklearn.preprocessing import StandardScaler
from ultralytics import YOLO

SAM_CHECKPOINT_URL = "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth"
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))

# ── CONFIG (identical to the original pipeline) ─────────────────────────
# RGB/IR split — must sum to 1.0
RGB_SPLIT = 0.57
IR_SPLIT = 0.43

# Per-class confidence thresholds (internal 0-4 ids) — box removed if below
CLASS_CONF_THR = {0: 0.25, 1: 0.35, 2: 0.45, 3: 0.45, 4: 0.45}

# Class palette, keyed by internal id (dataset id = internal id + 1).
# RGB order; outputs are converted to BGR where cv2 needs it.
CLASS_COLORS = {
    0: (255, 0, 0),      # dataset class 1: red
    1: (255, 127, 0),    # dataset class 2: orange
    2: (255, 255, 0),    # dataset class 3: yellow
    3: (0, 255, 0),      # dataset class 4: green
    4: (0, 0, 0),        # dataset class 5: black
}

# Blend factor of the dataset's mask_overlay jpgs
OVERLAY_ALPHA = 0.45
# ────────────────────────────────────────────────────────────────────────


# ══════════════════════════════════════════════════════════════════════
# Registration: homography lookup (shipped with the dataset)
# ══════════════════════════════════════════════════════════════════════

def frame_number(name):
    """'f00300' or 'f00300.png' -> 300"""
    digits = re.sub(r"\D", "", os.path.basename(name))
    return int(digits) if digits else -1


def load_homography(clip_dir):
    path = os.path.join(clip_dir, "homography", "homography.json")
    with open(path) as f:
        return json.load(f)


def select_homography_matrix(hjson, frame_name):
    """Pick the homography subset whose frame range covers this frame.
    Falls back to the nearest range if the frame sits outside all of them."""
    n = frame_number(frame_name)
    best, best_dist = None, None
    for s in hjson["subsets"]:
        lo = frame_number(s["frame_start"])
        hi = frame_number(s["frame_end"])
        if lo <= n <= hi:
            return np.array(s["matrix"], dtype=np.float64), s["label"], False
        dist = min(abs(n - lo), abs(n - hi))
        if best_dist is None or dist < best_dist:
            best, best_dist = s, dist
    return np.array(best["matrix"], dtype=np.float64), best["label"], True


def map_box_ir_to_rgb(box_ir, H, rgb_w, rgb_h):
    """Map an axis-aligned IR-space box into RGB pixel space through the
    homography (IR_pixel -> RGB_pixel) and re-take the axis-aligned bounds."""
    x1, y1, x2, y2 = box_ir
    corners = np.array([[[x1, y1], [x2, y1], [x2, y2], [x1, y2]]], dtype=np.float64)
    mapped = cv2.perspectiveTransform(corners, H)[0]
    xs, ys = mapped[:, 0], mapped[:, 1]
    x1_rgb = max(0, min(rgb_w, xs.min()))
    y1_rgb = max(0, min(rgb_h, ys.min()))
    x2_rgb = max(0, min(rgb_w, xs.max()))
    y2_rgb = max(0, min(rgb_h, ys.max()))
    return [x1_rgb, y1_rgb, x2_rgb, y2_rgb]


# ══════════════════════════════════════════════════════════════════════
# Pipeline stages (logic unchanged from the original notebook/pipeline)
# ══════════════════════════════════════════════════════════════════════

def compute_iou(boxA, boxB):
    xA = max(boxA[0], boxB[0])
    yA = max(boxA[1], boxB[1])
    xB = min(boxA[2], boxB[2])
    yB = min(boxA[3], boxB[3])
    interW = max(0, xB - xA)
    interH = max(0, yB - yA)
    interArea = interW * interH
    boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
    boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])
    union = boxAArea + boxBArea - interArea
    return interArea / union if union > 0 else 0.0


def ir_hotspot_boxes(ir_image, H, rgb_w, rgb_h):
    """Threshold red and white hotspots in the colorized IR frame; return their
    bounding boxes mapped into RGB pixel space via the dataset homography."""
    ir_hsv = cv2.cvtColor(ir_image, cv2.COLOR_BGR2HSV)

    # Threshold red and white only
    white_mask = cv2.inRange(ir_image, (200, 200, 200), (255, 255, 255))

    red_mask1 = cv2.inRange(ir_hsv, (0, 100, 100), (10, 255, 255))
    red_mask2 = cv2.inRange(ir_hsv, (160, 100, 100), (180, 255, 255))
    red_mask = cv2.bitwise_or(red_mask1, red_mask2)
    red_mask = cv2.bitwise_and(red_mask, cv2.bitwise_not(white_mask))

    hotspot_mask = cv2.bitwise_or(white_mask, red_mask)

    contours, _ = cv2.findContours(hotspot_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    ir_boxes_rgb = []
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area < 50:
            continue
        x, y, bw, bh = cv2.boundingRect(cnt)
        ir_boxes_rgb.append(map_box_ir_to_rgb((x, y, x + bw, y + bh), H, rgb_w, rgb_h))

    return ir_boxes_rgb, contours


def fuse_boxes(boxes, classes, confidences, ir_boxes_rgb, rgb_w, rgb_h):
    """Boost IR-confirmed YOLO boxes, add IR-only hotspots as new boxes, then
    apply per-class confidence thresholds.

    Confirmed:   score = original × RGB_SPLIT + IR_SPLIT  (sums to 1)
    Unconfirmed: score = original (unchanged, full RGB contribution)
    IR-only:     new box at IR_SPLIT score
    """
    yolo_boxes_px = [(x1, y1, x2, y2) for x1, y1, x2, y2 in boxes]
    final_scores = list(confidences)
    boosted_indices = set()
    extra_boxes = []
    extra_scores = []
    extra_labels = []

    for ir_box in ir_boxes_rgb:
        best_iou = 0.0
        best_idx = -1

        for i, (yolo_box, cls_id) in enumerate(zip(yolo_boxes_px, classes)):
            if int(cls_id) not in [0, 1, 2]:
                continue
            iou = compute_iou(ir_box, yolo_box)
            if iou > best_iou:
                best_iou = iou
                best_idx = i

        if best_iou >= 0.1 and best_idx >= 0:
            # Boost: blend RGB and IR contributions
            final_scores[best_idx] = min(
                1.0, confidences[best_idx] * RGB_SPLIT + IR_SPLIT
            )
            boosted_indices.add(best_idx)
        else:
            # Add: IR found hotspot YOLO missed → new box
            extra_boxes.append([
                ir_box[0] / rgb_w, ir_box[1] / rgb_h,
                ir_box[2] / rgb_w, ir_box[3] / rgb_h
            ])
            extra_scores.append(IR_SPLIT)
            extra_labels.append(2)

    print(f"  YOLO boxes boosted by IR: {len(boosted_indices)}")
    print(f"  New boxes from IR: {len(extra_boxes)}")

    all_boxes_norm = [[x1 / rgb_w, y1 / rgb_h, x2 / rgb_w, y2 / rgb_h]
                      for x1, y1, x2, y2 in yolo_boxes_px]
    all_scores_norm = final_scores
    all_labels_norm = [int(c) for c in classes]

    all_boxes_norm += extra_boxes
    all_scores_norm += extra_scores
    all_labels_norm += extra_labels

    # Per-class confidence threshold filter
    before_filter = len(all_boxes_norm)
    filtered = [
        (b, float(s), l)
        for b, s, l in zip(all_boxes_norm, all_scores_norm, all_labels_norm)
        if float(s) >= CLASS_CONF_THR.get(l, 0.3)
    ]
    if filtered:
        all_boxes_norm = [x[0] for x in filtered]
        all_scores_norm = [x[1] for x in filtered]
        all_labels_norm = [x[2] for x in filtered]
    else:
        all_boxes_norm, all_scores_norm, all_labels_norm = [], [], []

    print(f"  Removed {before_filter - len(all_boxes_norm)} boxes below per-class threshold")
    print(f"  Total boxes into SAM: {len(all_boxes_norm)}")

    return all_boxes_norm, all_scores_norm, all_labels_norm


def sam_segment(predictor, image, all_boxes_norm, all_labels_norm):
    """Prompt SAM with each fused box and accumulate per-class masks."""
    rgb_h, rgb_w = image.shape[:2]

    predictor.set_image(image)
    accumulated_masks = {i: np.zeros((rgb_h, rgb_w), dtype=bool) for i in range(5)}

    for box_norm, cls_id in zip(all_boxes_norm, all_labels_norm):
        cls_id = int(cls_id)
        x1 = int(box_norm[0] * rgb_w)
        y1 = int(box_norm[1] * rgb_h)
        x2 = int(box_norm[2] * rgb_w)
        y2 = int(box_norm[3] * rgb_h)

        masks, _, _ = predictor.predict(
            box=np.array([x1, y1, x2, y2]),
            multimask_output=False
        )
        if cls_id in accumulated_masks:
            accumulated_masks[cls_id] = np.logical_or(
                accumulated_masks[cls_id], masks[0]
            )

    return accumulated_masks


def resolve_overlaps(accumulated_masks):
    """Strict layering priority: internal class 0 on top -> class 4 bottom
    (dataset classes 1 on top -> 5 bottom)."""
    final_masks = {}
    final_masks[0] = accumulated_masks[0]
    final_masks[1] = np.logical_and(accumulated_masks[1], ~final_masks[0])
    occ1 = np.logical_or(final_masks[0], final_masks[1])
    final_masks[2] = np.logical_and(accumulated_masks[2], ~occ1)
    occ2 = np.logical_or(occ1, final_masks[2])
    final_masks[3] = np.logical_and(accumulated_masks[3], ~occ2)
    occ3 = np.logical_or(occ2, final_masks[3])
    final_masks[4] = np.logical_and(accumulated_masks[4], ~occ3)
    return final_masks


def dbscan_fill(image, final_masks):
    """Fill unlabeled pixels using labeled neighbors (KNN majority vote), then
    spatially smooth the assignments with DBSCAN. Returns a dense (h, w) label
    map with internal values 0-4, or None if the frame has no labeled pixels."""
    print("Running DBSCAN to fill unlabeled pixels...")

    h, w = image.shape[:2]

    label_map = np.full((h, w), -1, dtype=np.int8)  # -1 = unlabeled
    for cls_id in range(5):
        label_map[final_masks[cls_id]] = cls_id

    labeled_px = (label_map >= 0).sum()
    unlabeled_px = (label_map == -1).sum()
    print(f"  Labeled pixels:   {labeled_px}  ({labeled_px / (h * w) * 100:.1f}%)")
    print(f"  Unlabeled pixels: {unlabeled_px} ({unlabeled_px / (h * w) * 100:.1f}%)")

    if labeled_px == 0:
        print("   No labeled pixels in this frame — nothing to propagate, skipping fill.")
        return None

    # Features: x, y, R, G, B
    ys_all, xs_all = np.mgrid[0:h, 0:w]
    ys_all = ys_all.ravel()
    xs_all = xs_all.ravel()

    rgb_all = image.reshape(-1, 3).astype(np.float32) / 255.0
    pos_all = np.stack([xs_all / w, ys_all / h], axis=1)
    features_all = np.concatenate([pos_all, rgb_all], axis=1)  # (h*w, 5)

    labeled_idx = np.where(label_map.ravel() >= 0)[0]
    unlabeled_idx = np.where(label_map.ravel() == -1)[0]

    MAX_LABELED = 15000
    if len(labeled_idx) > MAX_LABELED:
        sampled_labeled = np.random.choice(labeled_idx, MAX_LABELED, replace=False)
    else:
        sampled_labeled = labeled_idx

    print(f"  Using {len(sampled_labeled)} labeled pixels to guide DBSCAN...")

    labeled_features = features_all[sampled_labeled]
    labeled_classes = label_map.ravel()[sampled_labeled]

    scaler = StandardScaler()
    labeled_features_scaled = scaler.fit_transform(labeled_features)

    tree = KDTree(labeled_features_scaled)

    dbscan_label_map = label_map.ravel().copy()

    if len(unlabeled_idx) > 0:
        print("  Finding nearest labeled neighbors for unlabeled pixels...")
        unlabeled_features = features_all[unlabeled_idx]
        unlabeled_features_scaled = scaler.transform(unlabeled_features)

        # Get 5 nearest labeled neighbors
        distances, indices = tree.query(unlabeled_features_scaled, k=5)

        # Majority vote from neighbors (vectorized per-row bincount+argmax;
        # produces exactly the same result as a per-row np.bincount/argmax loop)
        print("  Assigning classes by majority vote from neighbors...")
        neighbor_classes = labeled_classes[indices]  # (N_unlabeled, 5)

        counts = (neighbor_classes[:, :, None] == np.arange(5)[None, None, :]).sum(axis=1)
        assigned_classes = counts.argmax(axis=1)

        dbscan_label_map[unlabeled_idx] = assigned_classes
        dbscan_label_map = dbscan_label_map.reshape(h, w)

        print("  Running DBSCAN to spatially smooth unlabeled assignments...")

        unlabeled_features_for_dbscan = np.concatenate([
            unlabeled_features_scaled,
            assigned_classes.reshape(-1, 1) * 2.0  # weight class label heavily
        ], axis=1)

        MAX_DBSCAN = 20000
        if len(unlabeled_idx) > MAX_DBSCAN:
            dbscan_sample_idx = np.random.choice(
                len(unlabeled_idx), MAX_DBSCAN, replace=False
            )
            features_for_db = unlabeled_features_for_dbscan[dbscan_sample_idx]
        else:
            dbscan_sample_idx = np.arange(len(unlabeled_idx))
            features_for_db = unlabeled_features_for_dbscan

        db = DBSCAN(eps=0.4, min_samples=8).fit(features_for_db)
        db_labels = db.labels_

        unique_clusters = set(db_labels) - {-1}
        print(f"  DBSCAN found {len(unique_clusters)} spatial clusters in unlabeled region")

        for cluster_id in unique_clusters:
            cluster_mask = (db_labels == cluster_id)
            cluster_original_idx = dbscan_sample_idx[cluster_mask]

            cluster_classes = assigned_classes[cluster_original_idx]
            majority_cls = np.bincount(cluster_classes, minlength=5).argmax()

            pixel_indices = unlabeled_idx[cluster_original_idx]
            dbscan_label_map.ravel()[pixel_indices] = majority_cls
    else:
        dbscan_label_map = dbscan_label_map.reshape(h, w)

    return dbscan_label_map


# ══════════════════════════════════════════════════════════════════════
# Dataset-convention output writers
# ══════════════════════════════════════════════════════════════════════

def write_mask_txt(path, dataset_label_map):
    """Dataset mask format: one ASCII digit per pixel, row-major, single line,
    no separators, no trailing newline."""
    (dataset_label_map.astype(np.uint8) + ord("0")).astype(np.uint8).tofile(path)


def make_color_mask(dataset_label_map):
    """Pure-color RGB image of the label map (dataset palette)."""
    h, w = dataset_label_map.shape
    color = np.zeros((h, w, 3), dtype=np.uint8)
    for internal_id, rgb in CLASS_COLORS.items():
        color[dataset_label_map == internal_id + 1] = rgb
    return color


def make_dataset_overlay(image_rgb, color_mask):
    """Dataset mask_overlay style: overlay = (1-a)*rgb + a*class_color."""
    return (image_rgb.astype(np.float64) * (1 - OVERLAY_ALPHA)
            + color_mask.astype(np.float64) * OVERLAY_ALPHA).astype(np.uint8)


# ══════════════════════════════════════════════════════════════════════
# Per-frame annotation
# ══════════════════════════════════════════════════════════════════════

def frames_from_splits_csv(dataset_root, splits):
    """Authoritative frame list: rows of <dataset>/samples_splits.csv whose
    split matches. Returns {clip_dir: [frame, ...]}."""
    csv_path = os.path.join(dataset_root, "samples_splits.csv")
    if not os.path.exists(csv_path):
        raise SystemExit(f"Error: {csv_path} not found (required for --split).")
    plan = {}
    with open(csv_path, newline="") as f:
        for row in csv.DictReader(f):
            if row["split"] not in splits:
                continue
            if row.get("ir_ok", "True") != "True":
                continue
            parts = row["rgb_path"].replace("\\", "/").split("/")
            unit, clip = parts[0], parts[1]
            frame = os.path.splitext(parts[-1])[0]
            clip_dir = os.path.join(dataset_root, unit, clip)
            plan.setdefault(clip_dir, []).append(frame)
    return {d: sorted(fs) for d, fs in sorted(plan.items())}


def annotate_frame(model, predictor, clip_dir, out_clip_dir, frame, hjson,
                   copy_inputs=True, overwrite=True):
    rgb_path = os.path.join(clip_dir, "rgb", frame + ".png")
    ir_path = os.path.join(clip_dir, "ir", frame + ".png")

    if not overwrite and os.path.exists(os.path.join(out_clip_dir, "mask", frame + ".txt")):
        print(f" {os.path.basename(clip_dir)}/{frame}: mask already exists — skipping (use --overwrite to redo).")
        return None

    if not os.path.exists(rgb_path):
        print(f" Missing RGB frame: {rgb_path}")
        return False
    if not os.path.exists(ir_path):
        print(f" No IR partner for {frame} — skipping (pipeline needs both).")
        return False

    print(f"\n Processing {os.path.basename(clip_dir)}/{frame}")

    image = cv2.imread(rgb_path)
    ir_image = cv2.imread(ir_path)
    if image is None or ir_image is None:
        print(" Could not read RGB or IR image — skipping.")
        return False
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    rgb_h, rgb_w = image.shape[:2]
    ir_h, ir_w = ir_image.shape[:2]

    H, subset_label, fallback = select_homography_matrix(hjson, frame)
    note = " (nearest-range fallback)" if fallback else ""
    print(f"  Registration: homography subset '{subset_label}'{note}")
    print(f"  RGB size: {rgb_w}x{rgb_h} | IR size: {ir_w}x{ir_h}")

    # ── YOLO on the RGB frame ──
    yolo_results = model.predict(source=rgb_path, conf=0.25, verbose=False)
    boxes = yolo_results[0].boxes.xyxy.cpu().numpy()
    classes = yolo_results[0].boxes.cls.cpu().numpy()
    confidences = yolo_results[0].boxes.conf.cpu().numpy()
    print(f" YOLO detected {len(boxes)} object boxes")

    # ── IR thresholding -> hotspot boxes mapped through the homography ──
    ir_boxes_rgb, _ = ir_hotspot_boxes(ir_image, H, rgb_w, rgb_h)
    print(f"IR thresholding found {len(ir_boxes_rgb)} hotspot boxes")

    # ── Fusion + per-class thresholds ──
    all_boxes_norm, all_scores_norm, all_labels_norm = fuse_boxes(
        boxes, classes, confidences, ir_boxes_rgb, rgb_w, rgb_h
    )

    # ── SAM + overlap priority ──
    accumulated_masks = sam_segment(predictor, image, all_boxes_norm, all_labels_norm)
    final_masks = resolve_overlaps(accumulated_masks)

    # ── Dense fill ──
    internal_map = dbscan_fill(image, final_masks)
    if internal_map is None:
        print(f" Skipping outputs for {frame} (no labeled pixels).")
        return False

    dataset_map = internal_map.astype(np.int16) + 1  # 0-4 -> dataset classes 1-5

    # ── Write outputs (dataset conventions) ──
    subdirs = ["mask", "mask_overlay", "mask_color"] + (["rgb", "ir"] if copy_inputs else [])
    for sub in subdirs:
        os.makedirs(os.path.join(out_clip_dir, sub), exist_ok=True)

    write_mask_txt(os.path.join(out_clip_dir, "mask", frame + ".txt"), dataset_map)

    color_mask = make_color_mask(dataset_map)
    overlay = make_dataset_overlay(image, color_mask)
    cv2.imwrite(os.path.join(out_clip_dir, "mask_overlay", frame + ".jpg"),
                cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR))
    cv2.imwrite(os.path.join(out_clip_dir, "mask_color", frame + ".png"),
                cv2.cvtColor(color_mask, cv2.COLOR_RGB2BGR))

    # Copies of the inputs so the output clip folder is self-contained
    if copy_inputs:
        shutil.copy(rgb_path, os.path.join(out_clip_dir, "rgb", frame + ".png"))
        shutil.copy(ir_path, os.path.join(out_clip_dir, "ir", frame + ".png"))

    print("Pixel counts (dataset classes):")
    for internal_id in range(5):
        px = (dataset_map == internal_id + 1).sum()
        print(f"  Class {internal_id + 1}: {px} pixels ({px / (rgb_h * rgb_w) * 100:.1f}%)")
    print(f" Saved outputs for {frame} under {out_clip_dir}")
    return True


# ══════════════════════════════════════════════════════════════════════
# Main
# ══════════════════════════════════════════════════════════════════════

def find_clip_dirs(dataset_root, clip_names=None):
    """Return clip directories, e.g. <root>/Graminoid/Graminoid-08."""
    clip_dirs = []
    for unit in sorted(os.listdir(dataset_root)):
        unit_dir = os.path.join(dataset_root, unit)
        if not os.path.isdir(unit_dir):
            continue
        for clip in sorted(os.listdir(unit_dir)):
            clip_dir = os.path.join(unit_dir, clip)
            if os.path.isdir(os.path.join(clip_dir, "rgb")):
                clip_dirs.append(clip_dir)
    if clip_names:
        wanted = {c.split("/")[-1].split("\\")[-1] for c in clip_names}
        clip_dirs = [d for d in clip_dirs if os.path.basename(d) in wanted]
        missing = wanted - {os.path.basename(d) for d in clip_dirs}
        if missing:
            raise SystemExit(f"Error: clip(s) not found in dataset: {sorted(missing)}")
    return clip_dirs


def load_sam(checkpoint_path):
    if not os.path.exists(checkpoint_path):
        print(f"  Downloading SAM checkpoint (~375 MB) to {checkpoint_path} ...")
        # Download to a temp name so an interrupted download can't leave a
        # truncated checkpoint that poisons every later run.
        tmp_path = checkpoint_path + ".part"
        try:
            urllib.request.urlretrieve(SAM_CHECKPOINT_URL, tmp_path)
            os.replace(tmp_path, checkpoint_path)
        except BaseException:
            if os.path.exists(tmp_path):
                os.remove(tmp_path)
            raise

    sam = sam_model_registry["vit_b"](checkpoint=checkpoint_path)
    sam.to("cuda" if torch.cuda.is_available() else "cpu")
    predictor = SamPredictor(sam)
    print(" SAM loaded")
    return predictor


def main():
    parser = argparse.ArgumentParser(
        description="Automatic per-pixel labeling for registered RGB/IR pairs "
                    "(FilteredDataset10s layout) using YOLO + IR + SAM."
    )
    parser.add_argument("--dataset", required=True,
                        help="Dataset root — the folder that contains Canopy/ and Graminoid/.")
    parser.add_argument("--clip", action="append", default=None,
                        help="Clip name (e.g. Graminoid-08). Repeatable. Default: all clips (with --all).")
    parser.add_argument("--frames", nargs="+", default=None,
                        help="Frame names to annotate (e.g. f00300 f00600). Default: every frame of the clip.")
    parser.add_argument("--all", action="store_true",
                        help="Annotate every clip in the dataset.")
    parser.add_argument("--split", nargs="+", choices=["train", "val", "test"], default=None,
                        help="Annotate exactly the RGB/IR pairs listed in the dataset's samples_splits.csv "
                             "for these split(s), e.g. --split train test. Overrides --clip/--frames/--all.")
    parser.add_argument("--overwrite", action="store_true",
                        help="Re-annotate frames whose mask already exists in --out (default: skip them, "
                             "so an interrupted batch run can simply be restarted).")
    parser.add_argument("--no-copy-inputs", action="store_true",
                        help="Do not copy the rgb/ and ir/ frames into the output folder (saves disk space; "
                             "the homography folder is still copied).")
    parser.add_argument("--out", default=os.path.join(SCRIPT_DIR, "predictions"),
                        help="Output root; mirrors the dataset's <Unit>/<Clip>/... layout (default: ./predictions).")
    parser.add_argument("--weights", default=os.path.join(SCRIPT_DIR, "weights", "best.pt"),
                        help="Trained YOLO weights (default: weights/best.pt next to this script).")
    parser.add_argument("--sam-checkpoint", default=os.path.join(SCRIPT_DIR, "sam_vit_b_01ec64.pth"),
                        help="SAM vit_b checkpoint path (auto-downloaded if missing).")
    parser.add_argument("--class-thr", nargs=5, type=float, default=None,
                        metavar=("T1", "T2", "T3", "T4", "T5"),
                        help="Override the per-class confidence thresholds for dataset classes 1-5 "
                             "in order (default: 0.25 0.35 0.45 0.45 0.45). Passing "
                             "0.25 0.25 0.45 0.45 0.45 lowers only class 2 (class 1 is already at "
                             "0.25); on our validation split that raised class-2 IoU from 0.152 to "
                             "0.198 with no measured loss on the other classes.")
    args = parser.parse_args()

    # Emoji-friendly output even when stdout is piped/redirected (Windows
    # defaults redirected streams to cp1252, which cannot encode them).
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
        sys.stderr.reconfigure(encoding="utf-8", errors="replace")

    if args.class_thr:
        for i, t in enumerate(args.class_thr):
            CLASS_CONF_THR[i] = t

    if not os.path.isdir(args.dataset):
        raise SystemExit(f"Error: dataset root '{args.dataset}' not found.")
    if not args.split and not args.clip and not args.all:
        raise SystemExit("Error: pass --split <train/val/test>, --clip <name> (repeatable), or --all.")
    if not os.path.exists(args.weights):
        raise SystemExit(f"Error: YOLO weights not found at '{args.weights}'.")

    # Work plan: {clip_dir: [frames] or None (= every frame in the clip)}
    if args.split:
        plan = frames_from_splits_csv(args.dataset, set(args.split))
        n_pairs = sum(len(v) for v in plan.values())
        print(f"Split(s) {'+'.join(args.split)}: {n_pairs} RGB/IR pairs across "
              f"{len(plan)} clips (from samples_splits.csv)")
    else:
        clip_dirs = find_clip_dirs(args.dataset, None if args.all else args.clip)
        frames = [f.replace(".png", "") for f in args.frames] if args.frames else None
        plan = {d: frames for d in clip_dirs}
    if not plan:
        raise SystemExit(
            f"Error: nothing to annotate under '{args.dataset}'. Expected <root>/<Unit>/<Clip>/rgb/ "
            "layout — pass the folder that directly contains Canopy/ and Graminoid/ "
            "(in this repository: ../../Data relative to annotation_tool/)."
        )

    print(f"PyTorch {torch.__version__} | CUDA: {torch.cuda.is_available()}")

    model = YOLO(args.weights)
    names = model.names
    print(f" YOLO loaded from {args.weights} | classes: {names}")
    if len(names) != 5:
        print(f" Expected 5 classes, model has {len(names)} — check the weights file.")

    predictor = load_sam(args.sam_checkpoint)

    print(f"Clips to process: {[os.path.basename(d) for d in plan]}")
    print(f"Fusion: RGB_SPLIT={RGB_SPLIT} | IR_SPLIT={IR_SPLIT} | per-class thresholds "
          f"(dataset ids): {{ {', '.join(f'{k + 1}: {v}' for k, v in CLASS_CONF_THR.items())} }}")

    processed, skipped, already = 0, 0, 0
    for clip_dir, frames in plan.items():
        unit = os.path.basename(os.path.dirname(clip_dir))
        clip = os.path.basename(clip_dir)
        out_clip_dir = os.path.join(args.out, unit, clip)

        try:
            hjson = load_homography(clip_dir)
        except (OSError, json.JSONDecodeError) as e:
            print(f" Skipping {clip}: cannot read homography ({e})")
            continue

        if frames is None:
            frames = sorted(
                os.path.splitext(os.path.basename(p))[0]
                for p in glob.glob(os.path.join(clip_dir, "rgb", "*.png"))
            )

        # Copy the clip's registration files so the output stands alone
        os.makedirs(out_clip_dir, exist_ok=True)
        src_hom = os.path.join(clip_dir, "homography")
        dst_hom = os.path.join(out_clip_dir, "homography")
        if os.path.isdir(src_hom) and not os.path.isdir(dst_hom):
            shutil.copytree(src_hom, dst_hom)

        for frame in frames:
            # A single bad frame must not abort a long batch run.
            try:
                ok = annotate_frame(model, predictor, clip_dir, out_clip_dir, frame, hjson,
                                    copy_inputs=not args.no_copy_inputs,
                                    overwrite=args.overwrite)
            except Exception as e:
                print(f" Frame {frame} failed ({type(e).__name__}: {e}) — skipping.")
                ok = False
            if ok is None:
                already += 1
            elif ok:
                processed += 1
            else:
                skipped += 1

    print(f"\n✅ Done. Annotated {processed} frame(s), skipped {skipped}"
          + (f", already existed {already}" if already else "") + ".")
    print(f"Outputs written to: {os.path.abspath(args.out)}")


if __name__ == "__main__":
    main()