Skip to content

OccluBoost

OccluBoost is an occlusion-aware hybrid tracker built on top of BoostTrack. It keeps BoostTrack's multi-cue association (IoU + Mahalanobis + shape similarity, optional ReID) and DLO confidence boosting, then layers on a BotSort-inspired confirmation state, a ReID-only recovery pass, a safe low-confidence second pass, and an OccluTrack-style Abnormal Motion Suppression (AMS) Kalman filter that protects tracks during partial occlusion.

On the MOT17 ablation split (yolox_x_MOT17_ablation + lmbn_n_duke), OccluBoost beats BotSort on 5/6 metrics with the locked defaults: HOTA 70.47, MOTA 78.32, IDF1 84.14, IDSW 135, AssA 74.73 (only DetA −0.27 vs BotSort).

What's layered on top of BoostTrack

  • AMS Kalman update. Every Kalman update (first pass, ReID recovery, low-conf second pass) is routed through _ams_update, which scales the Kalman gain on the mean update by alpha ∈ [ams_alpha0, 1] when an abnormal-motion event is detected. Covariance is left untouched so uncertainty grows naturally during the suppressed step.
    • Trigger. A per-track ring buffer of length ams_buffer_size tracks [cx, cy, w, h]. We compute the relative speed spike of the centre and aspect against the buffer mean; if either exceeds ams_threshold, the speed gate fires.
    • Shrink gate (key addition over the OccluTrack paper). Suppression only kicks in when the new detection is also physically smaller than the running mean: cur_area < ams_shrink_ratio * mean_area. Without this gate, pure speed spikes over-suppress legitimate fast motion and DetA collapses; with it, we get the IDF1/HOTA gain without losing detection accuracy.
    • OBB safety. OBB tracks bypass AMS (alpha=1.0) — the suppression model is defined for AABB motion only.
  • BotSort-style track confirmation (tentative -> activated). New tracks born from medium-confidence detections must accumulate confirm_hits consecutive matches before being emitted; detections above instant_confirm_thresh skip the wait. Tentative tracks expire after tentative_max_age frames, slashing ghost IDs from one-frame flickers.
  • ReID-only recovery pass. Unmatched high-confidence detections are re-attached to recently lost tracks when cosine appearance similarity exceeds recovery_appearance_thresh and a loose IoU sanity gate (recovery_iou_thresh) is satisfied. Recovered embeddings are EMA-blended with feat_alpha.
  • Safe appearance-gated second pass. Low-confidence detections (track_low_thresh ≤ conf < det_thresh) can re-attach only to confirmed tracks (is_activated=True) under strict IoU + appearance gates. This lifts MOTA without the ID switches an unrestricted ByteTrack-style second pass introduces.
  • Duplicate suppression. A conservative duplicate_iou_thresh (default 0.95) drops the younger of two near-identical emitted tracks.

What BoxMOT Needs For OccluBoost

  • A detector and a ReID model (the recovery pass and second-pass appearance gate both rely on embeddings).
  • AABB or OBB detections. OBB inputs are routed through a dedicated OBB code path that uses oriented IoU for association and a 9-column output schema ([cx, cy, w, h, angle, id, conf, cls, det_ind]); the OBB association path replaces the AABB-specific confidence-boosting and Mahalanobis matching logic.
  • Best for crowded / partial-occlusion scenes where identity preservation matters.

Native C++ Backend

BoxMOT ships a native C++17 OccluBoost implementation under boxmot/native/trackers/occluboost/. It mirrors the Python tracker and shares the BoTSORT-style ReID plumbing, so it supports:

  • cached replay for eval, tune, and research
  • live track through --tracker-backend cpp
  • AABB detections (OBB still goes through the Python path)
  • ReID inference through the shared native OnnxReIdModel, used for the first-pass association, the ReID-only recovery pass, and the appearance-gated low-confidence second pass
  • automatic .pt -> .onnx export for native cpp inference when you pass PyTorch ReID weights

Requirements:

  • C++17 compiler
  • CMake 3.16+
  • OpenCV 4.x
  • Eigen3 3.3+

Example:

boxmot eval --benchmark mot17 --split ablation --tracker occluboost --tracker-backend cpp \
  --detector yolox_x_MOT17_ablation.pt --reid models/lmbn_n_duke.onnx
boxmot track --tracker occluboost --tracker-backend cpp \
  --reid models/lmbn_n_duke.pt --source 0

When --tracker-backend cpp is set, embedding generation for cached replay also goes through the native C++ ReID and is written to a __cpp-suffixed cache bucket. See Native C++ Integration for the runtime knobs (BOXMOT_REID_BACKEND, BOXMOT_REID_DEVICE).

Tuning notes

  • AMS knobs (locked on the MOT17 ablation split but worth retuning per dataset):
    • ams_alpha0 (default 0.4): how strongly to suppress the gain when both gates fire. Lower = stronger suppression. 0.3 over-protects and inflates IDSW; 0.5+ recovers IDSW but loses HOTA.
    • ams_threshold (default 0.5): relative speed-spike trigger. Lower fires more often.
    • ams_shrink_ratio (default 0.75): only suppress when the new bbox shrinks below this fraction of the buffered mean area. Disable AMS entirely with ams_enabled: false.
    • ams_buffer_size (default 30 frames).
  • confirm_hits (default 4) and instant_confirm_thresh (default 0.77) control the tentative pool. Lower the threshold to emit faster (better recall, more FPs); raise confirm_hits to be stricter.
  • recovery_appearance_thresh is the dominant identity safety knob: raise it (e.g. 0.7) to be conservative and protect IDF1, lower it (e.g. 0.4) to recover more occluded objects.
  • use_second_pass is on by default and only re-attaches low-confidence detections to confirmed tracks above second_pass_min_hits. Tighten second_iou_thresh / second_appearance_thresh if you see ID switches in dense scenes; relax them to gain MOTA in clean scenes.
  • new_track_thresh is decoupled from det_thresh so weakly-confident detections can update existing tracks without spawning new ones.
  • Keep max_age >= nr_classes (default 120 vs 80 COCO classes) so per-class tracking survives the per-class predict loop.

Adaptive Kalman Filter (adaptive_kf)

When adaptive_kf: true is set in the tracker config, the process noise covariance Q is estimated online from innovation statistics (Mehra 1970) rather than kept constant. A sliding window (30 frames, warmup 15) accumulates the outer products of the Kalman innovations, and once warmed up the estimated Q is blended (α = 0.7) with the default static Q.

When to use it:

  • Deploying to a new domain where you have no ground truth to run --tune-kf.
  • Scenes where camera motion compensation (CMC) may fail intermittently (low-texture, rain, night).
  • Camera dynamics that vary significantly within a single sequence (e.g., drone footage alternating hover and fast sweep).

When NOT to use it:

  • You already have a tuned static Q from boxmot eval --tune-kf on representative data — the static solution is cheaper and deterministic.
  • Very short tracks (< 15 frames) dominate; the estimator never exits warmup so it adds overhead with no benefit.

Enable it from the CLI:

boxmot track --tracker occluboost --adaptive-kf
boxmot eval  --tracker occluboost --adaptive-kf

Or in the tracker config YAML:

adaptive_kf: true

The tuner will also explore it automatically since it's registered as a choice parameter in the search space.

Bases: BoostTrack

BoostTrack augmented with an appearance-only recovery pass.

Parameters:

Name Type Description Default
recovery_appearance_thresh float

Minimum cosine similarity required between a detection embedding and a track embedding for the recovery pass to accept a match. Higher = stricter (fewer recoveries but safer identities).

0.99
recovery_iou_thresh float

Minimum IoU between detection box and the predicted track box (sanity gate; kept low because predicted boxes of long-lost tracks are inaccurate).

0.1
recovery_max_age int

Maximum time_since_update (after predict) of a tracker eligible for the recovery pass.

1
feat_alpha float

EMA factor used when updating embeddings during recovery (lower = slower update; preserves identity feature).

0.95
**kwargs Any

Forwarded to :class:BoostTrack.

{}

Class attribute supports_obb = True advertises Oriented Bounding Box capability; oriented detections are dispatched to :meth:_update_obb.

Source code in boxmot/trackers/bbox/occluboost/occluboost.py
  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
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
class OccluBoost(BoostTrack):
    """BoostTrack augmented with an appearance-only recovery pass.

    Args:
        recovery_appearance_thresh (float): Minimum cosine similarity required
            between a detection embedding and a track embedding for the
            recovery pass to accept a match. Higher = stricter (fewer recoveries
            but safer identities).
        recovery_iou_thresh (float): Minimum IoU between detection box and the
            predicted track box (sanity gate; kept low because predicted boxes
            of long-lost tracks are inaccurate).
        recovery_max_age (int): Maximum ``time_since_update`` (after predict) of
            a tracker eligible for the recovery pass.
        feat_alpha (float): EMA factor used when updating embeddings during
            recovery (lower = slower update; preserves identity feature).
        **kwargs: Forwarded to :class:`BoostTrack`.

    Class attribute ``supports_obb = True`` advertises Oriented Bounding Box
    capability; oriented detections are dispatched to :meth:`_update_obb`.
    """

    supports_obb = True

    def __init__(
        self,
        reid_model: Any | None = None,
        recovery_appearance_thresh: float = 0.99,
        recovery_iou_thresh: float = 0.1,
        recovery_max_age: int = 1,
        feat_alpha: float = 0.95,
        track_low_thresh: float = 0.1,
        second_iou_thresh: float = 0.6,
        second_appearance_thresh: float = 0.5,
        second_pass_max_age: int = 1,
        second_pass_min_hits: int = 3,
        use_second_pass: bool = False,
        new_track_thresh: float = 0.6,
        confirm_hits: int = 2,
        instant_confirm_thresh: float = 0.7,
        tentative_max_age: int = 1,
        duplicate_iou_thresh: float = 0.85,
        ams_enabled: bool = True,
        ams_alpha0: float = 0.4,
        ams_threshold: float = 0.5,
        ams_buffer_size: int = 30,
        ams_shrink_ratio: float = 0.75,
        lambda_emb_multiplier: float = 1.5,
        # ---- Online GTA (Global Track Association) ----
        gta_enabled: bool = True,
        gta_appearance_thresh: float = 0.5,
        gta_min_track_length: int = 5,
        gta_smooth_tau: float = 5.0,
        gta_interpolate: bool = True,
        gta_max_gap: int = 60,
        # ---- Adaptive KF ----
        adaptive_kf: bool = False,
        **kwargs: Any,
    ):
        super().__init__(reid_model=reid_model, **kwargs)
        self.recovery_appearance_thresh = recovery_appearance_thresh
        self.recovery_iou_thresh = recovery_iou_thresh
        self.recovery_max_age = recovery_max_age
        self.feat_alpha = feat_alpha
        self.track_low_thresh = track_low_thresh
        self.second_iou_thresh = second_iou_thresh
        self.second_appearance_thresh = second_appearance_thresh
        self.second_pass_max_age = second_pass_max_age
        self.second_pass_min_hits = second_pass_min_hits
        self.use_second_pass = use_second_pass
        # ``new_track_thresh`` decouples new-track creation from the matching
        # det_thresh. Detections in [det_thresh, new_track_thresh) help update
        # existing tracks but do not spawn new ones.
        self.new_track_thresh = max(new_track_thresh, 0.0)
        # ---- BotSort-style track confirmation ----
        # Tracks created from low/medium-confidence detections start tentative
        # and are only emitted (and persisted past ``tentative_max_age`` frames)
        # once they accumulate ``confirm_hits`` consecutive matched updates.
        # Detections with confidence >= ``instant_confirm_thresh`` skip the
        # tentative state entirely so high-quality first detections still emit
        # immediately (preserves IDF1).
        self.confirm_hits = max(int(confirm_hits), 1)
        self.instant_confirm_thresh = instant_confirm_thresh
        self.tentative_max_age = max(int(tentative_max_age), 0)
        # ---- Duplicate-track suppression ----
        # IoU threshold above which two co-existing tracks are considered
        # duplicates; the younger one (lower ``age``) is dropped.
        self.duplicate_iou_thresh = duplicate_iou_thresh
        # ---- Abnormal Motion Suppression (OccluTrack AMS KF) ----
        # Detect speed spikes caused by partial occlusion (the bbox suddenly
        # shrinks/jumps because only part of the body is visible) and damp
        # the Kalman gain on the affected update so the predicted state is
        # trusted more than the abnormal observation. ``ams_threshold`` is the
        # relative-spike trigger (current speed magnitude vs. running mean),
        # ``ams_alpha0`` is the suppression factor applied to the gain when
        # an abnormal motion is detected, and ``ams_buffer_size`` is the
        # length of the per-track observation buffer used to compute the
        # mean speed. Defaults follow the paper (MOT17 setting).
        self.ams_enabled = bool(ams_enabled)
        self.ams_alpha0 = float(np.clip(ams_alpha0, 0.0, 1.0))
        self.ams_threshold = float(max(ams_threshold, 0.0))
        self.ams_buffer_size = int(max(ams_buffer_size, 2))
        self.ams_shrink_ratio = float(np.clip(ams_shrink_ratio, 0.0, 1.0))
        self.lambda_emb_multiplier = float(lambda_emb_multiplier)
        # ---- Online GTA (Global Track Association) ----
        # When a track dies it is buried in a graveyard with its EMA
        # embedding.  Before creating a new track from an unmatched
        # detection, the graveyard is searched for an appearance match.
        # If found, the new track *reuses* the dead track's ID (so
        # outputs are immediately correct — no retroactive remapping)
        # and the gap between death and resurrection is filled with
        # GP-smoothed linear interpolation.
        self.gta_enabled = bool(gta_enabled) and self.with_reid
        self.gta_appearance_thresh = float(gta_appearance_thresh)
        self.gta_min_track_length = max(int(gta_min_track_length), 1)
        self.gta_smooth_tau = float(gta_smooth_tau)
        self.gta_interpolate = bool(gta_interpolate)
        self.gta_max_gap = max(int(gta_max_gap), 1)
        # Graveyard of recently-dead tracks, keyed by track ID.
        self._gta_graveyard: dict[int, dict] = {}
        # Accumulated gap-fill rows (MOT format, 9 cols).
        self._gta_gap_entries: list[np.ndarray] = []
        # ---- Adaptive KF ----
        self.adaptive_kf = bool(adaptive_kf)

    def _update_impl(
        self,
        dets: np.ndarray,
        img: np.ndarray,
        embs: Optional[np.ndarray] = None,
        masks: np.ndarray = None,
    ) -> np.ndarray:
        self.check_inputs(dets=dets, embs=embs, img=img)

        if self.is_obb:
            return self._update_obb(dets, img, embs)

        dets = np.hstack([dets, np.arange(len(dets)).reshape(-1, 1)])
        self.frame_count += 1

        if self.cmc is not None:
            transform = self.cmc.apply(img, dets)
            for trk in self.trackers:
                trk.camera_update(transform)

        trks = []
        confs = []
        for trk in self.trackers:
            pos = trk.predict()[0]
            conf = trk.get_confidence()
            confs.append(conf)
            trks.append(np.concatenate([pos, [conf]]))
        trks_np = np.vstack(trks) if len(trks) > 0 else np.empty((0, 5))

        # Capture original detection confidences before any boosting so the
        # ByteTrack-style second pass can recover the genuinely low-conf set.
        orig_confs = dets[:, 4].copy() if dets.size > 0 else np.empty(0)

        if self.use_dlo_boost:
            dets = self.dlo_confidence_boost(dets)
        if self.use_duo_boost:
            dets = self.duo_confidence_boost(dets)

        if dets.size > 0:
            remain_inds = dets[:, 4] >= self.det_thresh
            second_inds = (
                (~remain_inds)
                & (orig_confs >= self.track_low_thresh)
                & (orig_confs < self.det_thresh)
            ) if self.use_second_pass else np.zeros_like(remain_inds, dtype=bool)
            dets_second = dets[second_inds]
            dets = dets[remain_inds]
            scores = dets[:, 4]
            if self.with_reid:
                if embs is not None:
                    dets_embs = embs[remain_inds]
                    dets_embs_second = embs[second_inds]
                else:
                    dets_embs = self.reid_model.get_features(dets[:, :4], img)
                    if dets_second.shape[0] > 0:
                        dets_embs_second = self.reid_model.get_features(dets_second[:, :4], img)
                    else:
                        dets_embs_second = np.empty((0, dets_embs.shape[1]) if dets_embs.size else (0, 1))
            else:
                dets_embs = np.ones((dets.shape[0], 1))
                dets_embs_second = np.ones((dets_second.shape[0], 1))
        else:
            scores = np.empty(0)
            dets_second = np.empty((0, dets.shape[1] if dets.ndim == 2 else 7))
            dets_embs = np.ones((dets.shape[0], 1))
            dets_embs_second = np.ones((0, 1))

        if self.with_reid and len(self.trackers) > 0 and dets_embs.shape[0] > 0:
            tracker_embs = np.array([trk.get_emb() for trk in self.trackers])
            emb_cost = (
                dets_embs.reshape(dets_embs.shape[0], -1)
                @ tracker_embs.reshape(tracker_embs.shape[0], -1).T
            )
        else:
            emb_cost = None

        mh_dist_matrix = self.get_mh_dist_matrix(dets)

        matched, unmatched_dets, unmatched_trks, _ = associate(
            dets,
            trks_np,
            self.iou_threshold,
            mahalanobis_distance=mh_dist_matrix,
            track_confidence=np.array(confs).reshape(-1, 1),
            detection_confidence=scores,
            emb_cost=emb_cost,
            lambda_iou=self.lambda_iou,
            lambda_mhd=self.lambda_mhd,
            lambda_shape=self.lambda_shape,
            s_sim_corr=self.s_sim_corr,
            lambda_emb_multiplier=self.lambda_emb_multiplier,
        )

        if dets.size > 0:
            trust = (dets[:, 4] - self.det_thresh) / (1 - self.det_thresh)
            af = 0.95
            dets_alpha = af + (1 - af) * (1 - trust)
        else:
            dets_alpha = np.empty(0)

        for m in matched:
            self._ams_update(self.trackers[m[1]], dets[m[0], :])
            if self.with_reid:
                self.trackers[m[1]].update_emb(dets_embs[m[0]], alpha=dets_alpha[m[0]])
            self._maybe_activate(self.trackers[m[1]])

        # ---- ReID-only recovery pass ----
        if (
            self.with_reid
            and len(unmatched_trks) > 0
            and len(unmatched_dets) > 0
        ):
            elig = [
                int(t)
                for t in unmatched_trks
                if self.trackers[int(t)].time_since_update <= self.recovery_max_age
                and self.trackers[int(t)].get_emb() is not None
            ]
            if elig:
                u_det_idx = [int(d) for d in unmatched_dets]
                trk_e = np.stack([self.trackers[t].get_emb() for t in elig], axis=0)
                trk_e = trk_e.reshape(len(elig), -1)
                det_e = dets_embs[u_det_idx].reshape(len(u_det_idx), -1)
                sim = det_e @ trk_e.T

                trks_pos = np.zeros((len(elig), 5))
                for j, t in enumerate(elig):
                    pos = self.trackers[t].get_state()[0]
                    trks_pos[j, :4] = pos
                    trks_pos[j, 4] = self.trackers[t].get_confidence()
                ious = iou_batch(dets[u_det_idx], trks_pos)

                gated = sim.copy()
                gated[ious < self.recovery_iou_thresh] = -1.0
                gated[sim < self.recovery_appearance_thresh] = -1.0

                if (gated > 0).any():
                    row_ind, col_ind = linear_sum_assignment(-gated)
                    matched_dets_set = set()
                    for r, c in zip(row_ind, col_ind):
                        if gated[r, c] <= 0:
                            continue
                        det_global = u_det_idx[r]
                        trk_global = elig[c]
                        matched_dets_set.add(det_global)
                        self._ams_update(self.trackers[trk_global], dets[det_global, :])
                        self.trackers[trk_global].update_emb(
                            dets_embs[det_global], alpha=self.feat_alpha
                        )
                        self._maybe_activate(self.trackers[trk_global])
                    if matched_dets_set:
                        unmatched_dets = np.array(
                            [d for d in unmatched_dets if int(d) not in matched_dets_set],
                            dtype=int,
                        )

        # ---- ByteTrack-style appearance-gated second pass on low-conf dets ----
        if (
            self.use_second_pass
            and len(unmatched_trks) > 0
            and dets_second.shape[0] > 0
        ):
            elig_sec = [
                int(t)
                for t in unmatched_trks
                if self.trackers[int(t)].time_since_update <= self.second_pass_max_age
                and self.trackers[int(t)].hit_streak >= self.second_pass_min_hits
                and getattr(self.trackers[int(t)], "is_activated", True)
            ]
            if elig_sec:
                trks_pos = np.zeros((len(elig_sec), 5))
                for j, t in enumerate(elig_sec):
                    pos = self.trackers[t].get_state()[0]
                    trks_pos[j, :4] = pos
                    trks_pos[j, 4] = self.trackers[t].get_confidence()
                ious2 = iou_batch(dets_second, trks_pos)

                cost = 1.0 - ious2
                cost[ious2 < self.second_iou_thresh] = 1.0

                if (
                    self.with_reid
                    and dets_embs_second.shape[0] > 0
                    and self.trackers[elig_sec[0]].get_emb() is not None
                ):
                    trk_e = np.stack(
                        [self.trackers[t].get_emb() for t in elig_sec], axis=0
                    ).reshape(len(elig_sec), -1)
                    det_e = dets_embs_second.reshape(dets_embs_second.shape[0], -1)
                    sim2 = det_e @ trk_e.T
                    cost[sim2 < self.second_appearance_thresh] = 1.0

                if (cost < 1.0).any():
                    row_ind, col_ind = linear_sum_assignment(cost)
                    used = set()
                    for r, c in zip(row_ind, col_ind):
                        if cost[r, c] >= 1.0:
                            continue
                        trk_global = elig_sec[c]
                        if trk_global in used:
                            continue
                        used.add(trk_global)
                        self._ams_update(self.trackers[trk_global], dets_second[r, :])
                        if self.with_reid and dets_embs_second.shape[0] > 0:
                            self.trackers[trk_global].update_emb(
                                dets_embs_second[r], alpha=self.feat_alpha
                            )
                        self._maybe_activate(self.trackers[trk_global])

        # ---- GTA: pure-appearance recovery for remaining unmatched dets ----
        # The IoU-gated recovery above can miss when the KF prediction has
        # drifted (fast-moving players). This pass matches remaining
        # unmatched detections against alive-but-unmatched tracks using
        # ONLY appearance similarity (no IoU gate), recovering the track's
        # ID without creating a new one. This is the "online windowed GTA".
        if (
            self.gta_enabled
            and len(unmatched_dets) > 0
            and len(unmatched_trks) > 0
        ):
            unmatched_dets = self._gta_appearance_recovery(
                dets, dets_embs, unmatched_dets, unmatched_trks, is_obb=False
            )

        for i in unmatched_dets:
            if dets[i, 4] >= self.new_track_thresh:
                det_emb = dets_embs[i] if self.with_reid else None
                new_trk = KalmanBoxTracker(
                    dets[i, :],
                    max_obs=self.max_obs,
                    emb=det_emb,
                    adaptive_kf=self.adaptive_kf,
                )
                # Tentative until confirmed; high-conf detections skip the
                # confirmation period so first-frame appearances still emit.
                new_trk.is_activated = bool(
                    dets[i, 4] >= self.instant_confirm_thresh
                    or self.confirm_hits <= 1
                )
                self.trackers.append(new_trk)

        outputs = []
        self.active_tracks = []
        emitted_now = []
        for trk in self.trackers:
            d = trk.get_state()[0]
            is_activated = getattr(trk, "is_activated", True)
            warmup = self.frame_count <= self.min_hits
            if (
                (trk.time_since_update < 1)
                and is_activated
                and (trk.hit_streak >= self.min_hits or warmup)
            ):
                emitted_now.append((trk, d))

        # ---- Duplicate-track suppression on emitted tracks ----
        # When two tracks predict to nearly the same box, BotSort kills the
        # younger one. Without this step OccluBoost can emit pairs of tracks on
        # a single object after a recovery/2nd-pass pickup, hurting MOTA (FP)
        # and IDSW. We only consider currently-emitted tracks so we never
        # delete a legitimate occluded track that just happens to overlap a
        # visible one in *prediction* space.
        if len(emitted_now) > 1 and 0.0 < self.duplicate_iou_thresh < 1.0:
            emitted_now = self._suppress_duplicate_emissions(emitted_now)

        for trk, d in emitted_now:
            outputs.append(
                np.array([d[0], d[1], d[2], d[3], trk.id, trk.conf, trk.cls, trk.det_ind])
            )
            self.active_tracks.append(trk)

        # Lifecycle: confirmed tracks live up to ``max_age`` frames; tentative
        # tracks are dropped after ``tentative_max_age`` to prevent ghost IDs
        # from spurious detections, mirroring BotSort's ``unconfirmed`` pool.
        surviving = []
        for trk in self.trackers:
            alive = trk.time_since_update <= self.max_age and (
                getattr(trk, "is_activated", True)
                or trk.time_since_update <= self.tentative_max_age
            )
            if alive:
                surviving.append(trk)
        self.trackers = surviving

        if len(outputs) == 0:
            return np.empty((0, 8))
        outputs = np.vstack(outputs)
        return self.filter_outputs(outputs)

    def _maybe_activate(self, trk: KalmanBoxTracker) -> None:
        """Promote a tentative track to activated once it accumulates enough
        consecutive matched updates."""
        if not getattr(trk, "is_activated", True) and trk.hit_streak >= self.confirm_hits:
            trk.is_activated = True

    # ------------------------------------------------------------------
    # Online GTA (Global Track Association) methods
    # ------------------------------------------------------------------

    # ------------------------------------------------------------------
    # Online GTA: pure-appearance recovery for unmatched detections
    # ------------------------------------------------------------------

    def _gta_appearance_recovery(
        self,
        dets: np.ndarray,
        dets_embs: np.ndarray,
        unmatched_dets: np.ndarray,
        unmatched_trks: np.ndarray,
        is_obb: bool,
    ) -> np.ndarray:
        """Match remaining unmatched detections to alive-but-unmatched tracks
        using ONLY appearance similarity (no IoU gate).

        This catches cases where the KF prediction has drifted too far for
        the IoU-gated recovery to fire, but the appearance embedding is
        still a strong match.  Successfully matched detections are removed
        from *unmatched_dets* and the existing track is force-updated.

        Returns:
            Updated ``unmatched_dets`` array with recovered detections removed.
        """
        # Build eligible tracks: alive, unmatched, with embeddings,
        # within gta_max_gap frames of last match.
        elig = [
            int(t) for t in unmatched_trks
            if self.trackers[int(t)].time_since_update <= self.gta_max_gap
            and self.trackers[int(t)].get_emb() is not None
            and self.trackers[int(t)].age >= self.gta_min_track_length
        ]
        if not elig:
            return unmatched_dets

        u_det_idx = [int(d) for d in unmatched_dets]
        if not u_det_idx:
            return unmatched_dets

        # Filter to detections that have embeddings
        det_with_emb = [d for d in u_det_idx if dets_embs[d] is not None]
        if not det_with_emb:
            return unmatched_dets

        # Compute cosine similarity
        trk_e = np.stack(
            [self.trackers[t].get_emb() for t in elig], axis=0
        ).reshape(len(elig), -1)
        det_e = dets_embs[det_with_emb].reshape(len(det_with_emb), -1)
        sim = det_e @ trk_e.T

        # Gate by appearance threshold
        gated = sim.copy()
        gated[sim < self.gta_appearance_thresh] = -1.0

        if not (gated > 0).any():
            return unmatched_dets

        row_ind, col_ind = linear_sum_assignment(-gated)
        matched_dets_set: set[int] = set()
        for r, c in zip(row_ind, col_ind):
            if gated[r, c] <= 0:
                continue
            det_global = det_with_emb[r]
            trk_global = elig[c]
            matched_dets_set.add(det_global)
            # Force-update the track with this detection
            if is_obb:
                self._ams_update_obb(self.trackers[trk_global], dets[det_global, :])
            else:
                self._ams_update(self.trackers[trk_global], dets[det_global, :])
            self.trackers[trk_global].update_emb(
                dets_embs[det_global], alpha=self.feat_alpha
            )
            self._maybe_activate(self.trackers[trk_global])

        if matched_dets_set:
            unmatched_dets = np.array(
                [d for d in unmatched_dets if int(d) not in matched_dets_set],
                dtype=int,
            )
        return unmatched_dets

    def flush_gta(self) -> np.ndarray:
        """Return accumulated gap-fill entries and reset state.

        Called once at the end of a sequence by the replay loop.

        Returns:
            np.ndarray: Interpolated gap entries in MOT format (9 cols).
        """
        if not self._gta_gap_entries:
            return np.empty((0, 9))

        entries = list(self._gta_gap_entries)

        # Apply GP smoothing to interpolated segments
        if self.gta_smooth_tau > 0:
            entries = self._gta_smooth_all(entries)

        self._gta_gap_entries = []
        self._gta_graveyard = {}
        return np.vstack(entries)

    def _gta_smooth_all(self, entries: list[np.ndarray]) -> list[np.ndarray]:
        """Apply GP smoothing to all interpolated segments.

        Groups entries by track_id, then applies RBF-kernel GP regression
        to each segment's bounding box columns.
        """
        if len(entries) < 3:
            return entries

        try:
            from sklearn.gaussian_process import GaussianProcessRegressor as GPR
            from sklearn.gaussian_process.kernels import RBF
        except ImportError:
            return entries

        # Group by track_id (column 1)
        from collections import defaultdict
        groups: dict[int, list[int]] = defaultdict(list)
        for idx, row in enumerate(entries):
            groups[int(row[1])].append(idx)

        tau = self.gta_smooth_tau
        for tid, indices in groups.items():
            if len(indices) < 3:
                continue
            frames = np.array([entries[i][0] for i in indices]).reshape(-1, 1)
            boxes = np.array([entries[i][2:6] for i in indices])
            n = len(indices)
            length_scale = np.clip(
                tau * np.log(max(tau**3 / n, 1e-6)), tau**-1, tau**2
            )
            kernel = RBF(length_scale, length_scale_bounds="fixed")
            gpr = GPR(kernel)
            smoothed = gpr.fit(frames, boxes).predict(frames)
            for k, idx in enumerate(indices):
                entries[idx][2:6] = smoothed[k]

        return entries

    @staticmethod
    def _xyxy_to_cxcywh(box: np.ndarray) -> np.ndarray:
        """Convert ``[x1, y1, x2, y2]`` to ``[cx, cy, w, h]``."""
        x1, y1, x2, y2 = float(box[0]), float(box[1]), float(box[2]), float(box[3])
        w = max(x2 - x1, 1e-6)
        h = max(y2 - y1, 1e-6)
        return np.array([x1 + 0.5 * w, y1 + 0.5 * h, w, h], dtype=float)

    def _compute_ams_alpha(
        self, trk: KalmanBoxTracker, det_box: np.ndarray
    ) -> float:
        """Compute the OccluTrack abnormal-motion suppression coefficient.

        Builds a per-track buffer of past observed ``[cx, cy, w, h]`` boxes
        (lazily attached to the tracker as ``_ams_obs_buf``). Compares the
        current speed magnitude (centre and aspect/scale separately) against
        the running mean of the previous speeds in the buffer. If either
        relative spike exceeds ``ams_threshold`` the corresponding pair of
        gain scalars is replaced with ``ams_alpha0``; the returned value is
        the mean of the four ``α_x, α_y, α_w, α_h`` per the paper.
        """
        if not self.ams_enabled or self.ams_alpha0 >= 1.0:
            return 1.0
        # OBB tracks use a different state layout (theta channel); skip AMS
        # to avoid mixing rectangular/oriented box semantics.
        if getattr(trk.kf, "_is_obb", False):
            return 1.0

        cur = self._xyxy_to_cxcywh(det_box[:4])
        buf = getattr(trk, "_ams_obs_buf", None)
        if buf is None:
            from collections import deque

            buf = deque(maxlen=self.ams_buffer_size)
            trk._ams_obs_buf = buf

        # Need at least 2 prior observations to estimate the mean speed.
        if len(buf) < 2:
            buf.append(cur)
            return 1.0

        prev = buf[-1]
        cur_v = cur - prev  # [vx, vy, vw, vh]

        # Mean speed over the (N-1) previous transitions in the buffer.
        diffs = np.diff(np.asarray(buf, dtype=float), axis=0)
        mean_v = diffs.mean(axis=0)

        eps = 1e-6
        cur_c_mag = float(np.linalg.norm(cur_v[:2]))
        mean_c_mag = float(np.linalg.norm(mean_v[:2]))
        cur_a_mag = float(np.linalg.norm(cur_v[2:]))
        mean_a_mag = float(np.linalg.norm(mean_v[2:]))

        # Relative spikes: how much faster is the current speed than the
        # running mean, normalised by the running mean magnitude.
        d_c = max(0.0, cur_c_mag - mean_c_mag) / max(mean_c_mag, eps)
        d_a = max(0.0, cur_a_mag - mean_a_mag) / max(mean_a_mag, eps)

        alpha_c = 1.0 if d_c <= self.ams_threshold else self.ams_alpha0
        alpha_a = 1.0 if d_a <= self.ams_threshold else self.ams_alpha0
        alpha = 0.5 * (alpha_c + alpha_a)

        # Physical sanity: partial occlusion specifically *shrinks* the bbox
        # (the occluder hides part of the body). Only suppress when the new
        # box area is meaningfully smaller than the running mean area;
        # otherwise the speed spike is more likely legitimate fast motion or
        # the track re-emerging from full occlusion at its true scale.
        cur_area = float(cur[2] * cur[3])
        mean_area = float(np.mean(np.asarray(buf, dtype=float)[:, 2:].prod(axis=1)))
        if cur_area >= mean_area * self.ams_shrink_ratio:
            alpha = 1.0

        buf.append(cur)
        return float(alpha)

    def _ams_update(self, trk: KalmanBoxTracker, det: np.ndarray) -> None:
        """Drop-in replacement for ``KalmanBoxTracker.update`` that also
        applies the OccluTrack abnormal-motion suppression coefficient to the
        Kalman gain.

        Mirrors :meth:`KalmanBoxTracker.update` exactly except for passing
        ``alpha`` to the underlying KF, so all bookkeeping (hit_streak,
        history_observations, conf/cls/det_ind) stays consistent across the
        first pass, ReID-only recovery, and the low-confidence second pass.
        """
        from boxmot.trackers.bbox.boosttrack.boosttrack import convert_bbox_to_z

        alpha = self._compute_ams_alpha(trk, det[:4])
        trk.time_since_update = 0
        trk.hit_streak += 1
        trk.history_observations.append(trk.get_state()[0])
        trk.kf.update(convert_bbox_to_z(det[:4]), alpha=alpha)
        trk.conf = det[4]
        trk.cls = det[5]
        trk.det_ind = det[6]

    def _suppress_duplicate_emissions(
        self, emitted: list[tuple[KalmanBoxTracker, np.ndarray]]
    ) -> list[tuple[KalmanBoxTracker, np.ndarray]]:
        """Drop duplicate emissions when two tracks predict to overlapping
        boxes. The younger track (smaller ``age``) is dropped *and* removed
        from ``self.trackers`` so it does not persist as a ghost.

        Mirrors BotSort's ``remove_duplicate_stracks``; uses ``age`` as the
        survival tiebreaker to favour the older identity.
        """
        if self.is_obb:
            # ``e[1]`` is ``[cx, cy, w, h, angle]`` in OBB mode; use oriented IoU.
            boxes = np.stack([e[1][:5] for e in emitted], axis=0)
            ious = AssociationFunction.iou_batch_obb(boxes, boxes)
        else:
            boxes = np.stack([e[1][:4] for e in emitted], axis=0)
            ious = iou_batch(
                np.hstack([boxes, np.ones((len(boxes), 3))]),
                np.hstack([boxes, np.ones((len(boxes), 3))]),
            )
        np.fill_diagonal(ious, 0.0)
        drop = set()
        n = len(emitted)
        for i in range(n):
            if i in drop:
                continue
            for j in range(i + 1, n):
                if j in drop:
                    continue
                if ious[i, j] >= self.duplicate_iou_thresh:
                    age_i = emitted[i][0].age
                    age_j = emitted[j][0].age
                    drop.add(j if age_i >= age_j else i)
        if not drop:
            return emitted
        # Also remove the dropped (younger) tracks from ``self.trackers`` so
        # they cannot spawn future emissions or absorb future detections.
        drop_ids = {emitted[k][0].id for k in drop}
        self.trackers = [trk for trk in self.trackers if trk.id not in drop_ids]
        return [e for k, e in enumerate(emitted) if k not in drop]

    # ------------------------------------------------------------------
    # OBB code path
    # ------------------------------------------------------------------

    def _ams_update_obb(self, trk: KalmanBoxTracker, det: np.ndarray) -> None:
        """OBB analogue of :meth:`_ams_update`.

        ``det`` is ``[cx, cy, w, h, angle, conf, cls, det_ind]``. AMS itself
        is skipped for OBB tracks (the speed-spike heuristic assumes a
        rectangular box; :meth:`_compute_ams_alpha` already returns ``1.0``
        for OBB KFs), so we just route the update through the OBB-aware KF
        and keep the same bookkeeping as :meth:`_ams_update`.
        """
        from boxmot.trackers.bbox.boosttrack.boosttrack import convert_xywha_to_z
        trk.time_since_update = 0
        trk.hit_streak += 1
        trk.history_observations.append(trk.get_state()[0])
        trk.kf.update(convert_xywha_to_z(det[:5]))
        trk.conf = det[5]
        trk.cls = det[6]
        trk.det_ind = det[7]

    def _update_obb(
        self,
        dets: np.ndarray,
        img: np.ndarray,
        embs: Optional[np.ndarray] = None,
    ) -> np.ndarray:
        """OBB-only update mirroring the AABB flow.

        Differences vs the AABB path:
        * Detections use the 7-col layout ``(cx, cy, w, h, angle, conf, cls)``;
          ``self.detection_layout.with_detection_indices`` appends ``det_ind``.
        * Camera-motion compensation, DLO/DUO confidence boosting, and
          Mahalanobis association are skipped (they are tied to the xyxy/xyhr
          AABB representation).
        * Association uses oriented IoU via
          :meth:`AssociationFunction.iou_batch_obb`, optionally fused with a
          ReID cosine-similarity term BoTSORT-style.
        * Outputs follow the OBB schema
          ``[cx, cy, w, h, angle, id, conf, cls, det_ind]`` (9 cols).
        """
        dets = self.detection_layout.with_detection_indices(dets)
        self.frame_count += 1

        # Predict all current trackers
        trks_xywha = []
        confs = []
        for trk in self.trackers:
            pos = trk.predict()[0]  # [cx, cy, w, h, angle]
            trks_xywha.append(pos)
            confs.append(trk.get_confidence())
        trks_xywha = (
            np.vstack(trks_xywha) if len(trks_xywha) > 0 else np.empty((0, 5))
        )

        # Confidence-based detection split (high / low for second pass)
        if dets.size > 0:
            orig_confs = dets[:, 5].copy()
            remain_inds = orig_confs >= self.det_thresh
            second_inds = (
                (~remain_inds)
                & (orig_confs >= self.track_low_thresh)
                & (orig_confs < self.det_thresh)
            ) if self.use_second_pass else np.zeros_like(remain_inds, dtype=bool)
            dets_second = dets[second_inds]
            dets = dets[remain_inds]
            scores = dets[:, 5]

            if self.with_reid:
                if embs is not None:
                    dets_embs = embs[remain_inds]
                    dets_embs_second = embs[second_inds]
                else:
                    # ReID models work on AABB crops; use enclosing rectangles.
                    crops_high = _xywha_to_xyxy_enclosing(dets[:, :5])
                    dets_embs = self.reid_model.get_features(crops_high, img)
                    if dets_second.shape[0] > 0:
                        crops_low = _xywha_to_xyxy_enclosing(dets_second[:, :5])
                        dets_embs_second = self.reid_model.get_features(
                            crops_low, img
                        )
                    else:
                        dets_embs_second = np.empty(
                            (0, dets_embs.shape[1]) if dets_embs.size else (0, 1)
                        )
            else:
                dets_embs = np.ones((dets.shape[0], 1))
                dets_embs_second = np.ones((dets_second.shape[0], 1))
        else:
            scores = np.empty(0)
            dets_second = np.empty((0, dets.shape[1] if dets.ndim == 2 else 8))
            dets_embs = np.ones((0, 1))
            dets_embs_second = np.ones((0, 1))

        # First-pass association: oriented IoU (+ optional ReID fusion)
        n_dets = dets.shape[0]
        n_trks = trks_xywha.shape[0]
        if n_dets == 0 or n_trks == 0:
            matched = np.empty((0, 2), dtype=int)
            unmatched_dets = np.arange(n_dets, dtype=int)
            unmatched_trks = np.arange(n_trks, dtype=int)
        else:
            iou = AssociationFunction.iou_batch_obb(dets[:, :5], trks_xywha)
            cost = 1.0 - iou
            cost[iou < self.iou_threshold] = 1e6

            if (
                self.with_reid
                and dets_embs.shape[0] > 0
                and self.trackers[0].get_emb() is not None
            ):
                tracker_embs = np.stack(
                    [trk.get_emb() for trk in self.trackers], axis=0
                ).reshape(n_trks, -1)
                emb_sim = (
                    dets_embs.reshape(n_dets, -1)
                    @ tracker_embs.T
                )
                # BoTSORT-style fusion: subtract a scaled appearance term.
                lambda_emb = float(getattr(self, "lambda_iou", 0.5)) + 0.5
                cost = cost - lambda_emb * emb_sim
                # Re-apply IoU gate so good appearance can't bypass geometry.
                cost[iou < self.iou_threshold] = 1e6

            row_ind, col_ind = linear_sum_assignment(cost)
            matched_pairs = []
            matched_d, matched_t = set(), set()
            for r, c in zip(row_ind, col_ind):
                if cost[r, c] >= 1e5:
                    continue
                matched_pairs.append([r, c])
                matched_d.add(r)
                matched_t.add(c)
            matched = (
                np.array(matched_pairs, dtype=int)
                if matched_pairs
                else np.empty((0, 2), dtype=int)
            )
            unmatched_dets = np.array(
                [i for i in range(n_dets) if i not in matched_d], dtype=int
            )
            unmatched_trks = np.array(
                [i for i in range(n_trks) if i not in matched_t], dtype=int
            )

        # Apply matched updates
        for m in matched:
            self._ams_update_obb(self.trackers[m[1]], dets[m[0], :])
            if self.with_reid:
                # Trust factor mirrors AABB path
                trust = (dets[m[0], 5] - self.det_thresh) / max(
                    1.0 - self.det_thresh, 1e-6
                )
                af = 0.95
                alpha_emb = af + (1 - af) * (1 - trust)
                self.trackers[m[1]].update_emb(
                    dets_embs[m[0]], alpha=float(alpha_emb)
                )
            self._maybe_activate(self.trackers[m[1]])

        # ---- ReID-only recovery pass ----
        if (
            self.with_reid
            and len(unmatched_trks) > 0
            and len(unmatched_dets) > 0
        ):
            elig = [
                int(t)
                for t in unmatched_trks
                if self.trackers[int(t)].time_since_update <= self.recovery_max_age
                and self.trackers[int(t)].get_emb() is not None
            ]
            if elig:
                u_det_idx = [int(d) for d in unmatched_dets]
                trk_e = np.stack(
                    [self.trackers[t].get_emb() for t in elig], axis=0
                ).reshape(len(elig), -1)
                det_e = dets_embs[u_det_idx].reshape(len(u_det_idx), -1)
                sim = det_e @ trk_e.T

                trks_pos = np.stack(
                    [self.trackers[t].get_state()[0] for t in elig], axis=0
                )
                ious = AssociationFunction.iou_batch_obb(
                    dets[u_det_idx, :5], trks_pos
                )

                gated = sim.copy()
                gated[ious < self.recovery_iou_thresh] = -1.0
                gated[sim < self.recovery_appearance_thresh] = -1.0

                if (gated > 0).any():
                    row_ind, col_ind = linear_sum_assignment(-gated)
                    matched_dets_set = set()
                    for r, c in zip(row_ind, col_ind):
                        if gated[r, c] <= 0:
                            continue
                        det_global = u_det_idx[r]
                        trk_global = elig[c]
                        matched_dets_set.add(det_global)
                        self._ams_update_obb(
                            self.trackers[trk_global], dets[det_global, :]
                        )
                        self.trackers[trk_global].update_emb(
                            dets_embs[det_global], alpha=self.feat_alpha
                        )
                        self._maybe_activate(self.trackers[trk_global])
                    if matched_dets_set:
                        unmatched_dets = np.array(
                            [
                                d
                                for d in unmatched_dets
                                if int(d) not in matched_dets_set
                            ],
                            dtype=int,
                        )

        # ---- Appearance-gated low-confidence second pass ----
        if (
            self.use_second_pass
            and len(unmatched_trks) > 0
            and dets_second.shape[0] > 0
        ):
            elig_sec = [
                int(t)
                for t in unmatched_trks
                if self.trackers[int(t)].time_since_update <= self.second_pass_max_age
                and self.trackers[int(t)].hit_streak >= self.second_pass_min_hits
                and getattr(self.trackers[int(t)], "is_activated", True)
            ]
            if elig_sec:
                trks_pos = np.stack(
                    [self.trackers[t].get_state()[0] for t in elig_sec], axis=0
                )
                ious2 = AssociationFunction.iou_batch_obb(
                    dets_second[:, :5], trks_pos
                )
                cost2 = 1.0 - ious2
                cost2[ious2 < self.second_iou_thresh] = 1.0

                if (
                    self.with_reid
                    and dets_embs_second.shape[0] > 0
                    and self.trackers[elig_sec[0]].get_emb() is not None
                ):
                    trk_e = np.stack(
                        [self.trackers[t].get_emb() for t in elig_sec], axis=0
                    ).reshape(len(elig_sec), -1)
                    det_e = dets_embs_second.reshape(
                        dets_embs_second.shape[0], -1
                    )
                    sim2 = det_e @ trk_e.T
                    cost2[sim2 < self.second_appearance_thresh] = 1.0

                if (cost2 < 1.0).any():
                    row_ind, col_ind = linear_sum_assignment(cost2)
                    used = set()
                    for r, c in zip(row_ind, col_ind):
                        if cost2[r, c] >= 1.0:
                            continue
                        trk_global = elig_sec[c]
                        if trk_global in used:
                            continue
                        used.add(trk_global)
                        self._ams_update_obb(
                            self.trackers[trk_global], dets_second[r, :]
                        )
                        if self.with_reid and dets_embs_second.shape[0] > 0:
                            self.trackers[trk_global].update_emb(
                                dets_embs_second[r], alpha=self.feat_alpha
                            )
                        self._maybe_activate(self.trackers[trk_global])

        # ---- GTA: pure-appearance recovery for remaining unmatched dets ----
        if (
            self.gta_enabled
            and len(unmatched_dets) > 0
            and len(unmatched_trks) > 0
        ):
            unmatched_dets = self._gta_appearance_recovery(
                dets, dets_embs, unmatched_dets, unmatched_trks, is_obb=True
            )

        # ---- New tracks for remaining unmatched high-conf detections ----
        for i in unmatched_dets:
            if dets[i, 5] >= self.new_track_thresh:
                det_emb = dets_embs[i] if self.with_reid else None
                new_trk = KalmanBoxTracker(
                    dets[i, :],
                    max_obs=self.max_obs,
                    emb=det_emb,
                    is_obb=True,
                    adaptive_kf=self.adaptive_kf,
                )
                new_trk.is_activated = bool(
                    dets[i, 5] >= self.instant_confirm_thresh
                    or self.confirm_hits <= 1
                )
                self.trackers.append(new_trk)

        # ---- Build outputs ----
        outputs = []
        self.active_tracks = []
        emitted_now = []
        for trk in self.trackers:
            d = trk.get_state()[0]  # [cx, cy, w, h, angle]
            is_activated = getattr(trk, "is_activated", True)
            warmup = self.frame_count <= self.min_hits
            if (
                (trk.time_since_update < 1)
                and is_activated
                and (trk.hit_streak >= self.min_hits or warmup)
            ):
                emitted_now.append((trk, d))

        if len(emitted_now) > 1 and 0.0 < self.duplicate_iou_thresh < 1.0:
            emitted_now = self._suppress_duplicate_emissions(emitted_now)

        for trk, d in emitted_now:
            outputs.append(
                np.array(
                    [d[0], d[1], d[2], d[3], d[4], trk.id, trk.conf, trk.cls, trk.det_ind]
                )
            )
            self.active_tracks.append(trk)

        # Lifecycle
        surviving = []
        for trk in self.trackers:
            alive = trk.time_since_update <= self.max_age and (
                getattr(trk, "is_activated", True)
                or trk.time_since_update <= self.tentative_max_age
            )
            if alive:
                surviving.append(trk)
        self.trackers = surviving

        if len(outputs) == 0:
            return self.empty_output(dtype=np.float32)
        return np.vstack(outputs)

flush_gta()

Return accumulated gap-fill entries and reset state.

Called once at the end of a sequence by the replay loop.

Returns:

Type Description
ndarray

np.ndarray: Interpolated gap entries in MOT format (9 cols).

Source code in boxmot/trackers/bbox/occluboost/occluboost.py
def flush_gta(self) -> np.ndarray:
    """Return accumulated gap-fill entries and reset state.

    Called once at the end of a sequence by the replay loop.

    Returns:
        np.ndarray: Interpolated gap entries in MOT format (9 cols).
    """
    if not self._gta_gap_entries:
        return np.empty((0, 9))

    entries = list(self._gta_gap_entries)

    # Apply GP smoothing to interpolated segments
    if self.gta_smooth_tau > 0:
        entries = self._gta_smooth_all(entries)

    self._gta_gap_entries = []
    self._gta_graveyard = {}
    return np.vstack(entries)