Sync frame-based zone labeling changes
Browse files- README.md +24 -14
- configs/zones/MVI_40191.yaml +61 -0
- configs/zones/MVI_40244.yaml +59 -0
- data-labelling/README.md +7 -6
- data-labelling/zone_labeler.py +100 -30
- docs/ARCHITECTURE.md +3 -3
- docs/COLAB.md +3 -3
- docs/REVIEW_FIXES_2026-11-06.md +65 -0
- scripts/calibrate_camera.py +11 -3
- scripts/run_trafficvision.py +1 -1
- src/trafficvision/cli.py +2 -0
- src/trafficvision/evaluation/tracking_metrics.py +6 -2
- src/trafficvision/geometry/homography.py +15 -0
- src/trafficvision/pipeline/detection_tracking.py +0 -1
- src/trafficvision/pipeline/video_pipeline.py +7 -3
- src/trafficvision/speed/kalman_speed.py +60 -26
- src/trafficvision/training/trainer.py +3 -1
- tests/test_kalman_robustness.py +78 -0
- tests/test_speed_estimator.py +4 -2
- tests/test_training.py +3 -1
- tests/test_zone_labeler.py +40 -0
README.md
CHANGED
|
@@ -20,7 +20,7 @@ python -m pip install -e ".[train,tracking-eval,dev]"
|
|
| 20 |
# Ultralytics có thể cài opencv-python; cài contrib cuối để Selective Search có ximgproc.
|
| 21 |
python -m pip install --force-reinstall --no-deps opencv-contrib-python-headless==4.10.0.84
|
| 22 |
|
| 23 |
-
python scripts/
|
| 24 |
python -m pytest -q
|
| 25 |
```
|
| 26 |
|
|
@@ -78,19 +78,19 @@ data:
|
|
| 78 |
Sửa `data.manifest`, `training.device` (`cpu`/`cuda`), batch size và đường dẫn output trong YAML. Tất cả đường dẫn dữ liệu/output tính từ thư mục repo; `extends` tính tương đối với file YAML đang chứa nó.
|
| 79 |
|
| 80 |
```bash
|
| 81 |
-
python scripts/
|
| 82 |
--config configs/experiments/faster_rcnn_scratch.yaml
|
| 83 |
|
| 84 |
-
python scripts/
|
| 85 |
--config configs/experiments/fast_rcnn_scratch.yaml
|
| 86 |
|
| 87 |
-
python scripts/
|
| 88 |
--config configs/experiments/rcnn_scratch.yaml
|
| 89 |
|
| 90 |
-
python scripts/
|
| 91 |
--config configs/experiments/rtdetr_scratch.yaml
|
| 92 |
|
| 93 |
-
python scripts/
|
| 94 |
--config configs/experiments/yolov8_baseline.yaml
|
| 95 |
```
|
| 96 |
|
|
@@ -99,10 +99,10 @@ Custom detectors tự lắp kiến trúc; mặc định CNN nhỏ train từ ran
|
|
| 99 |
Custom runs lưu `config.yaml`, `metrics.jsonl`, `last.pt`, `best.pt` (chọn theo validation COCO mAP). Checkpoint gồm model params, state, optimizer, scheduler, epoch, seed/config và RNG; resume tại ranh giới epoch:
|
| 100 |
|
| 101 |
```bash
|
| 102 |
-
python scripts/
|
| 103 |
--resume outputs/faster_rcnn/last.pt
|
| 104 |
|
| 105 |
-
python scripts/
|
| 106 |
--checkpoint outputs/faster_rcnn/best.pt --split test \
|
| 107 |
--config configs/evaluation/ua_detrac.yaml --output outputs/evaluation/faster_rcnn.json
|
| 108 |
```
|
|
@@ -118,7 +118,7 @@ Tracker config ở `configs/trackers/`: `sort`, `bytetrack`, `botsort`. Đổi t
|
|
| 118 |
Để đo tracking trên **toàn split**, không cần ghép ảnh thành MP4:
|
| 119 |
|
| 120 |
```bash
|
| 121 |
-
python scripts/
|
| 122 |
--checkpoint outputs/faster_rcnn/best.pt --tracker bytetrack --split test \
|
| 123 |
--config configs/evaluation/ua_detrac.yaml --output outputs/evaluation/faster_bytetrack.csv
|
| 124 |
```
|
|
@@ -127,6 +127,16 @@ Lệnh reset tracker giữa các video, kiểm tra thứ tự frame, xuất traj
|
|
| 127 |
|
| 128 |
Polygon mẫu `configs/zones/MVI_20011.yaml` chưa phải calibration thật. Vẽ lại cho video rồi chỉnh `frame_size`, `confidence_threshold`, `inference_scale`, `measure_speed`. Dùng bottom-center để gán vùng; crop lượt riêng cho vùng có scale >1 rồi đưa box về frame gốc và NMS theo class. Threshold vùng thấp giữ candidate cho association; `new_track_thresh` vẫn kiểm soát việc sinh ID mới.
|
| 129 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
## 5. Phase 4 — Calibration và vận tốc
|
| 131 |
|
| 132 |
Với mỗi sequence, lưu tọa độ thực đã đo bằng **mét** tại `data/ua_detrac/world_points/world_points_<VIDEO_ID>.json`. Các điểm ảnh và điểm thực phải có cùng thứ tự, gồm ít nhất 4 điểm không thẳng hàng trên mặt đường. Không tự suy ra khoảng cách thực từ bbox.
|
|
@@ -140,10 +150,10 @@ python scripts/calibrate_camera.py \
|
|
| 140 |
|
| 141 |
Desktop có OpenCV GUI có thể thay `--image-points` bằng `--interactive`. Colab/headless dùng JSON. Không cài đồng thời nhiều biến thể OpenCV khi muốn dùng GUI; xem hướng dẫn môi trường. Kiểm tra phép chiếu trên điểm độc lập: reprojection thấp ở đúng bốn điểm fit không chứng minh calibration chính xác.
|
| 142 |
|
| 143 |
-
|
| 144 |
|
| 145 |
```bash
|
| 146 |
-
python scripts/
|
| 147 |
```
|
| 148 |
|
| 149 |
CSV cần cặp đã đối chiếu cùng phương tiện/thời gian: `gt_kmh,predicted_kmh`. Chỉ báo cáo MAE/RMSE/MAPE thực khi có GT speed; MAPE bỏ các GT bằng 0.
|
|
@@ -151,7 +161,7 @@ CSV cần cặp đã đối chiếu cùng phương tiện/thời gian: `gt_kmh,p
|
|
| 151 |
## 6. Phase 5 — Video demo
|
| 152 |
|
| 153 |
```bash
|
| 154 |
-
python scripts/
|
| 155 |
--model faster_rcnn --checkpoint outputs/faster_rcnn/best.pt --tracker bytetrack \
|
| 156 |
--camera-config configs/cameras/MVI_20011.yaml --zone-config configs/zones/MVI_20011.yaml \
|
| 157 |
--output outputs/demo/faster_bytetrack.mp4
|
|
@@ -160,7 +170,7 @@ python scripts/utils.py demo --source /path/to/traffic.mp4 \
|
|
| 160 |
Có thể bỏ camera/zone config để xem detection + tracking, speed `N/A`. Video pretrained chưa fine-tune:
|
| 161 |
|
| 162 |
```bash
|
| 163 |
-
python scripts/
|
| 164 |
--config configs/models/yolov8.yaml --tracker bytetrack --output outputs/demo/yolo_coco.mp4
|
| 165 |
```
|
| 166 |
|
|
@@ -185,4 +195,4 @@ python scripts/compare_runs.py outputs/evaluation/faster_rcnn.json \
|
|
| 185 |
| `pipeline/`, `visualization/` | Điều phối, video và export |
|
| 186 |
| `configs/`, `scripts/`, `tests/` | Thí nghiệm, công cụ và regression tests |
|
| 187 |
|
| 188 |
-
Nhóm có thể chia theo các hàng trên; mỗi model/tracker phải giữ interface chung. Không commit dataset, checkpoint, token, output hoặc `.venv`.
|
|
|
|
| 20 |
# Ultralytics có thể cài opencv-python; cài contrib cuối để Selective Search có ximgproc.
|
| 21 |
python -m pip install --force-reinstall --no-deps opencv-contrib-python-headless==4.10.0.84
|
| 22 |
|
| 23 |
+
python scripts/run_trafficvision.py --help
|
| 24 |
python -m pytest -q
|
| 25 |
```
|
| 26 |
|
|
|
|
| 78 |
Sửa `data.manifest`, `training.device` (`cpu`/`cuda`), batch size và đường dẫn output trong YAML. Tất cả đường dẫn dữ liệu/output tính từ thư mục repo; `extends` tính tương đối với file YAML đang chứa nó.
|
| 79 |
|
| 80 |
```bash
|
| 81 |
+
python scripts/run_trafficvision.py train --model faster_rcnn --init random \
|
| 82 |
--config configs/experiments/faster_rcnn_scratch.yaml
|
| 83 |
|
| 84 |
+
python scripts/run_trafficvision.py train --model fast_rcnn --init random \
|
| 85 |
--config configs/experiments/fast_rcnn_scratch.yaml
|
| 86 |
|
| 87 |
+
python scripts/run_trafficvision.py train --model rcnn --init random \
|
| 88 |
--config configs/experiments/rcnn_scratch.yaml
|
| 89 |
|
| 90 |
+
python scripts/run_trafficvision.py train --model rtdetr --init random \
|
| 91 |
--config configs/experiments/rtdetr_scratch.yaml
|
| 92 |
|
| 93 |
+
python scripts/run_trafficvision.py train --model yolov8 --init pretrained \
|
| 94 |
--config configs/experiments/yolov8_baseline.yaml
|
| 95 |
```
|
| 96 |
|
|
|
|
| 99 |
Custom runs lưu `config.yaml`, `metrics.jsonl`, `last.pt`, `best.pt` (chọn theo validation COCO mAP). Checkpoint gồm model params, state, optimizer, scheduler, epoch, seed/config và RNG; resume tại ranh giới epoch:
|
| 100 |
|
| 101 |
```bash
|
| 102 |
+
python scripts/run_trafficvision.py train --config configs/experiments/faster_rcnn_scratch.yaml \
|
| 103 |
--resume outputs/faster_rcnn/last.pt
|
| 104 |
|
| 105 |
+
python scripts/run_trafficvision.py evaluate --model faster_rcnn \
|
| 106 |
--checkpoint outputs/faster_rcnn/best.pt --split test \
|
| 107 |
--config configs/evaluation/ua_detrac.yaml --output outputs/evaluation/faster_rcnn.json
|
| 108 |
```
|
|
|
|
| 118 |
Để đo tracking trên **toàn split**, không cần ghép ảnh thành MP4:
|
| 119 |
|
| 120 |
```bash
|
| 121 |
+
python scripts/run_trafficvision.py track-dataset --model faster_rcnn \
|
| 122 |
--checkpoint outputs/faster_rcnn/best.pt --tracker bytetrack --split test \
|
| 123 |
--config configs/evaluation/ua_detrac.yaml --output outputs/evaluation/faster_bytetrack.csv
|
| 124 |
```
|
|
|
|
| 127 |
|
| 128 |
Polygon mẫu `configs/zones/MVI_20011.yaml` chưa phải calibration thật. Vẽ lại cho video rồi chỉnh `frame_size`, `confidence_threshold`, `inference_scale`, `measure_speed`. Dùng bottom-center để gán vùng; crop lượt riêng cho vùng có scale >1 rồi đưa box về frame gốc và NMS theo class. Threshold vùng thấp giữ candidate cho association; `new_track_thresh` vẫn kiểm soát việc sinh ID mới.
|
| 129 |
|
| 130 |
+
Có thể chạy zone labeler không cần tham số. Chương trình liệt kê các video trong
|
| 131 |
+
`data/ua_detrac`; video đã có `configs/zones/<VIDEO_ID>.yaml` sẽ được đánh dấu
|
| 132 |
+
`--done`. Sau khi chọn, chương trình chỉ đọc frame đầu tiên để kẻ polygon:
|
| 133 |
+
|
| 134 |
+
```bash
|
| 135 |
+
python data-labelling/zone_labeler.py
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
Mỗi video được lưu zone riêng theo ID để dễ kiểm tra tiến độ.
|
| 139 |
+
|
| 140 |
## 5. Phase 4 — Calibration và vận tốc
|
| 141 |
|
| 142 |
Với mỗi sequence, lưu tọa độ thực đã đo bằng **mét** tại `data/ua_detrac/world_points/world_points_<VIDEO_ID>.json`. Các điểm ảnh và điểm thực phải có cùng thứ tự, gồm ít nhất 4 điểm không thẳng hàng trên mặt đường. Không tự suy ra khoảng cách thực từ bbox.
|
|
|
|
| 150 |
|
| 151 |
Desktop có OpenCV GUI có thể thay `--image-points` bằng `--interactive`. Colab/headless dùng JSON. Không cài đồng thời nhiều biến thể OpenCV khi muốn dùng GUI; xem hướng dẫn môi trường. Kiểm tra phép chiếu trên điểm độc lập: reprojection thấp ở đúng bốn điểm fit không chứng minh calibration chính xác.
|
| 152 |
|
| 153 |
+
Pipeline dùng Kalman constant-velocity trên tọa độ mét; Jacobian homography truyền nhiễu pixel sang world coordinates. Speed trả `N/A` khi chưa đủ quan sát, uncertainty cao, timestamp lỗi, gap dài, innovation bị loại hoặc chưa có homography. Các tham số nằm trong `speed` của camera YAML; module hồi quy cũ vẫn được giữ để đối chiếu. Chỉ dùng quan sát detection hiện tại; không lấy vị trí track dự đoán qua occlusion làm phép đo.
|
| 154 |
|
| 155 |
```bash
|
| 156 |
+
python scripts/run_trafficvision.py evaluate-speed --pairs /path/to/matched_speed_pairs.csv
|
| 157 |
```
|
| 158 |
|
| 159 |
CSV cần cặp đã đối chiếu cùng phương tiện/thời gian: `gt_kmh,predicted_kmh`. Chỉ báo cáo MAE/RMSE/MAPE thực khi có GT speed; MAPE bỏ các GT bằng 0.
|
|
|
|
| 161 |
## 6. Phase 5 — Video demo
|
| 162 |
|
| 163 |
```bash
|
| 164 |
+
python scripts/run_trafficvision.py demo --source /path/to/traffic.mp4 \
|
| 165 |
--model faster_rcnn --checkpoint outputs/faster_rcnn/best.pt --tracker bytetrack \
|
| 166 |
--camera-config configs/cameras/MVI_20011.yaml --zone-config configs/zones/MVI_20011.yaml \
|
| 167 |
--output outputs/demo/faster_bytetrack.mp4
|
|
|
|
| 170 |
Có thể bỏ camera/zone config để xem detection + tracking, speed `N/A`. Video pretrained chưa fine-tune:
|
| 171 |
|
| 172 |
```bash
|
| 173 |
+
python scripts/run_trafficvision.py demo --source /path/to/traffic.mp4 --model yolov8 \
|
| 174 |
--config configs/models/yolov8.yaml --tracker bytetrack --output outputs/demo/yolo_coco.mp4
|
| 175 |
```
|
| 176 |
|
|
|
|
| 195 |
| `pipeline/`, `visualization/` | Điều phối, video và export |
|
| 196 |
| `configs/`, `scripts/`, `tests/` | Thí nghiệm, công cụ và regression tests |
|
| 197 |
|
| 198 |
+
Nhóm có thể chia theo các hàng trên; mỗi model/tracker phải giữ interface chung. Không commit dataset, checkpoint, token, output hoặc `.venv`. Làm việc trên branch riêng và gửi pull request để nhóm review trước khi merge.
|
configs/zones/MVI_40191.yaml
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
camera_id: MVI_40191
|
| 2 |
+
frame_size:
|
| 3 |
+
- 960
|
| 4 |
+
- 540
|
| 5 |
+
roi_only: true
|
| 6 |
+
default_threshold: 0.25
|
| 7 |
+
zones:
|
| 8 |
+
far_zone:
|
| 9 |
+
polygon:
|
| 10 |
+
- - 384
|
| 11 |
+
- 69
|
| 12 |
+
- - 511
|
| 13 |
+
- 71
|
| 14 |
+
- - 475
|
| 15 |
+
- 207
|
| 16 |
+
- - 195
|
| 17 |
+
- 172
|
| 18 |
+
confidence_threshold: 0.05
|
| 19 |
+
inference_scale: 1.0
|
| 20 |
+
measure_speed: true
|
| 21 |
+
far_zone_lane2:
|
| 22 |
+
polygon:
|
| 23 |
+
- - 549
|
| 24 |
+
- 74
|
| 25 |
+
- - 708
|
| 26 |
+
- 77
|
| 27 |
+
- - 957
|
| 28 |
+
- 211
|
| 29 |
+
- - 574
|
| 30 |
+
- 210
|
| 31 |
+
confidence_threshold: 0.05
|
| 32 |
+
inference_scale: 1.0
|
| 33 |
+
measure_speed: true
|
| 34 |
+
near_zone:
|
| 35 |
+
polygon:
|
| 36 |
+
- - 191
|
| 37 |
+
- 173
|
| 38 |
+
- - 473
|
| 39 |
+
- 208
|
| 40 |
+
- - 382
|
| 41 |
+
- 535
|
| 42 |
+
- - 2
|
| 43 |
+
- 537
|
| 44 |
+
- - 0
|
| 45 |
+
- 274
|
| 46 |
+
confidence_threshold: 0.05
|
| 47 |
+
inference_scale: 1.0
|
| 48 |
+
measure_speed: true
|
| 49 |
+
near_zone2:
|
| 50 |
+
polygon:
|
| 51 |
+
- - 575
|
| 52 |
+
- 210
|
| 53 |
+
- - 959
|
| 54 |
+
- 210
|
| 55 |
+
- - 958
|
| 56 |
+
- 536
|
| 57 |
+
- - 632
|
| 58 |
+
- 536
|
| 59 |
+
confidence_threshold: 0.05
|
| 60 |
+
inference_scale: 1.0
|
| 61 |
+
measure_speed: true
|
configs/zones/MVI_40244.yaml
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
camera_id: MVI_40244
|
| 2 |
+
frame_size:
|
| 3 |
+
- 960
|
| 4 |
+
- 540
|
| 5 |
+
roi_only: true
|
| 6 |
+
default_threshold: 0.25
|
| 7 |
+
zones:
|
| 8 |
+
far_zone1:
|
| 9 |
+
polygon:
|
| 10 |
+
- - 662
|
| 11 |
+
- 57
|
| 12 |
+
- - 770
|
| 13 |
+
- 54
|
| 14 |
+
- - 629
|
| 15 |
+
- 121
|
| 16 |
+
- - 509
|
| 17 |
+
- 102
|
| 18 |
+
confidence_threshold: 0.05
|
| 19 |
+
inference_scale: 1.0
|
| 20 |
+
measure_speed: true
|
| 21 |
+
far_zone2:
|
| 22 |
+
polygon:
|
| 23 |
+
- - 796
|
| 24 |
+
- 56
|
| 25 |
+
- - 958
|
| 26 |
+
- 57
|
| 27 |
+
- - 959
|
| 28 |
+
- 148
|
| 29 |
+
- - 700
|
| 30 |
+
- 132
|
| 31 |
+
confidence_threshold: 0.05
|
| 32 |
+
inference_scale: 1.0
|
| 33 |
+
measure_speed: true
|
| 34 |
+
near_zone1:
|
| 35 |
+
polygon:
|
| 36 |
+
- - 508
|
| 37 |
+
- 104
|
| 38 |
+
- - 627
|
| 39 |
+
- 123
|
| 40 |
+
- - 0
|
| 41 |
+
- 471
|
| 42 |
+
- - 0
|
| 43 |
+
- 279
|
| 44 |
+
confidence_threshold: 0.05
|
| 45 |
+
inference_scale: 1.0
|
| 46 |
+
measure_speed: true
|
| 47 |
+
near_zone2:
|
| 48 |
+
polygon:
|
| 49 |
+
- - 703
|
| 50 |
+
- 132
|
| 51 |
+
- - 959
|
| 52 |
+
- 149
|
| 53 |
+
- - 959
|
| 54 |
+
- 533
|
| 55 |
+
- - 141
|
| 56 |
+
- 539
|
| 57 |
+
confidence_threshold: 0.05
|
| 58 |
+
inference_scale: 1.0
|
| 59 |
+
measure_speed: true
|
data-labelling/README.md
CHANGED
|
@@ -2,12 +2,13 @@
|
|
| 2 |
|
| 3 |
## Create polygon zones
|
| 4 |
|
| 5 |
-
Run the GUI from the repository root
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
```bash
|
| 8 |
-
python data-labelling/zone_labeler.py
|
| 9 |
-
--source /path/to/MVI_20011.mp4 \
|
| 10 |
-
--output configs/zones/MVI_20011.yaml
|
| 11 |
```
|
| 12 |
|
| 13 |
Controls:
|
|
@@ -20,5 +21,5 @@ Controls:
|
|
| 20 |
- `Q` or `Esc`: quit
|
| 21 |
|
| 22 |
The generated file includes the source frame size and is compatible with
|
| 23 |
-
`--zone-config` in the TrafficVision demo command.
|
| 24 |
-
|
|
|
|
| 2 |
|
| 3 |
## Create polygon zones
|
| 4 |
|
| 5 |
+
Run the GUI from the repository root. It lists every camera sequence under
|
| 6 |
+
`data/ua_detrac/raw/DETRAC/DETRAC-Images/DETRAC-Images`, opens the first image
|
| 7 |
+
in the selected sequence as its representative frame, and marks cameras with
|
| 8 |
+
saved zones as `--done`:
|
| 9 |
|
| 10 |
```bash
|
| 11 |
+
python data-labelling/zone_labeler.py
|
|
|
|
|
|
|
| 12 |
```
|
| 13 |
|
| 14 |
Controls:
|
|
|
|
| 21 |
- `Q` or `Esc`: quit
|
| 22 |
|
| 23 |
The generated file includes the source frame size and is compatible with
|
| 24 |
+
`--zone-config` in the TrafficVision demo command. It creates one output YAML
|
| 25 |
+
per camera.
|
data-labelling/zone_labeler.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
"""Interactive polygon-zone labeler for
|
| 2 |
|
| 3 |
import argparse
|
| 4 |
from pathlib import Path
|
|
@@ -10,6 +10,13 @@ import yaml
|
|
| 10 |
|
| 11 |
WINDOW_NAME = "TrafficVision zone labeler"
|
| 12 |
COLORS = ((0, 180, 255), (0, 230, 90), (255, 180, 0), (220, 80, 220))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
class ZoneLabeler:
|
|
@@ -72,13 +79,20 @@ class ZoneLabeler:
|
|
| 72 |
)
|
| 73 |
|
| 74 |
def to_frame_point(self, x, y):
|
| 75 |
-
return [
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
def on_click(self, event, x, y, _flags, _param):
|
| 78 |
if event == cv2.EVENT_LBUTTONDOWN:
|
| 79 |
self.current.append(self.to_frame_point(x, y))
|
| 80 |
|
| 81 |
def save(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
config = {
|
| 83 |
"camera_id": self.camera_id,
|
| 84 |
"frame_size": [self.width, self.height],
|
|
@@ -98,13 +112,24 @@ class ZoneLabeler:
|
|
| 98 |
self.output.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8")
|
| 99 |
print(f"Saved {len(self.zones)} zones to {self.output}")
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
def run(self):
|
| 102 |
cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)
|
| 103 |
cv2.setMouseCallback(WINDOW_NAME, self.on_click)
|
| 104 |
-
print(
|
| 105 |
-
"Click points; Enter=finish zone, U=undo, C=clear current, "
|
| 106 |
-
"S=save, Q/Esc=quit."
|
| 107 |
-
)
|
| 108 |
while True:
|
| 109 |
cv2.imshow(WINDOW_NAME, self.display_frame())
|
| 110 |
key = cv2.waitKey(30) & 0xFF
|
|
@@ -119,40 +144,85 @@ class ZoneLabeler:
|
|
| 119 |
print("A zone needs at least 3 points.")
|
| 120 |
continue
|
| 121 |
name = input(f"Zone name ({len(self.zones) + 1}): ").strip()
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
print(f"Zone already exists: {name}")
|
| 127 |
-
continue
|
| 128 |
-
self.zones.append({"name": name, "polygon": self.current.copy()})
|
| 129 |
-
self.current.clear()
|
| 130 |
elif key == ord("s"):
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
| 132 |
cv2.destroyAllWindows()
|
| 133 |
|
| 134 |
|
| 135 |
def parse_args():
|
| 136 |
parser = argparse.ArgumentParser(description=__doc__)
|
| 137 |
-
parser.add_argument("--source", required=True, help="Video file used for labelling")
|
| 138 |
-
parser.add_argument("--output", required=True, help="Output zone YAML path")
|
| 139 |
-
parser.add_argument("--camera-id", help="Camera ID; defaults to the video filename stem")
|
| 140 |
return parser.parse_args()
|
| 141 |
|
| 142 |
|
| 143 |
-
def
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
try:
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
if not
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
|
| 158 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
"""Interactive polygon-zone labeler for UA-DETRAC camera frames."""
|
| 2 |
|
| 3 |
import argparse
|
| 4 |
from pathlib import Path
|
|
|
|
| 10 |
|
| 11 |
WINDOW_NAME = "TrafficVision zone labeler"
|
| 12 |
COLORS = ((0, 180, 255), (0, 230, 90), (255, 180, 0), (220, 80, 220))
|
| 13 |
+
REPO_ROOT = Path(__file__).resolve().parents[1]
|
| 14 |
+
DEFAULT_FRAME_DIR = (
|
| 15 |
+
REPO_ROOT / "data" / "ua_detrac" / "raw" / "DETRAC" / "DETRAC-Images"
|
| 16 |
+
/ "DETRAC-Images"
|
| 17 |
+
)
|
| 18 |
+
DEFAULT_OUTPUT_DIR = REPO_ROOT / "configs" / "zones"
|
| 19 |
+
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp"}
|
| 20 |
|
| 21 |
|
| 22 |
class ZoneLabeler:
|
|
|
|
| 79 |
)
|
| 80 |
|
| 81 |
def to_frame_point(self, x, y):
|
| 82 |
+
return [
|
| 83 |
+
min(max(round(x / self.display_scale), 0), self.width - 1),
|
| 84 |
+
min(max(round(y / self.display_scale), 0), self.height - 1),
|
| 85 |
+
]
|
| 86 |
|
| 87 |
def on_click(self, event, x, y, _flags, _param):
|
| 88 |
if event == cv2.EVENT_LBUTTONDOWN:
|
| 89 |
self.current.append(self.to_frame_point(x, y))
|
| 90 |
|
| 91 |
def save(self):
|
| 92 |
+
if self.current:
|
| 93 |
+
raise ValueError("Finish the current polygon with Enter before saving.")
|
| 94 |
+
if not self.zones:
|
| 95 |
+
raise ValueError("Create at least one zone before saving.")
|
| 96 |
config = {
|
| 97 |
"camera_id": self.camera_id,
|
| 98 |
"frame_size": [self.width, self.height],
|
|
|
|
| 112 |
self.output.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8")
|
| 113 |
print(f"Saved {len(self.zones)} zones to {self.output}")
|
| 114 |
|
| 115 |
+
def finish_zone(self, name):
|
| 116 |
+
name = name.strip()
|
| 117 |
+
if not name or name in {zone["name"] for zone in self.zones}:
|
| 118 |
+
raise ValueError("Zone name must be nonempty and unique.")
|
| 119 |
+
points = np.asarray(self.current, dtype=np.float32).reshape(-1, 2)
|
| 120 |
+
if (
|
| 121 |
+
len(points) < 3
|
| 122 |
+
or len(np.unique(points, axis=0)) != len(points)
|
| 123 |
+
or abs(cv2.contourArea(points)) < 1e-6
|
| 124 |
+
):
|
| 125 |
+
raise ValueError("A zone needs >=3 distinct points with nonzero area.")
|
| 126 |
+
self.zones.append({"name": name, "polygon": self.current.copy()})
|
| 127 |
+
self.current.clear()
|
| 128 |
+
|
| 129 |
def run(self):
|
| 130 |
cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)
|
| 131 |
cv2.setMouseCallback(WINDOW_NAME, self.on_click)
|
| 132 |
+
print("Click points; Enter=finish zone, U=undo, C=clear current, " "S=save, Q/Esc=quit.")
|
|
|
|
|
|
|
|
|
|
| 133 |
while True:
|
| 134 |
cv2.imshow(WINDOW_NAME, self.display_frame())
|
| 135 |
key = cv2.waitKey(30) & 0xFF
|
|
|
|
| 144 |
print("A zone needs at least 3 points.")
|
| 145 |
continue
|
| 146 |
name = input(f"Zone name ({len(self.zones) + 1}): ").strip()
|
| 147 |
+
try:
|
| 148 |
+
self.finish_zone(name)
|
| 149 |
+
except ValueError as exc:
|
| 150 |
+
print(exc)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
elif key == ord("s"):
|
| 152 |
+
try:
|
| 153 |
+
self.save()
|
| 154 |
+
except ValueError as exc:
|
| 155 |
+
print(exc)
|
| 156 |
cv2.destroyAllWindows()
|
| 157 |
|
| 158 |
|
| 159 |
def parse_args():
|
| 160 |
parser = argparse.ArgumentParser(description=__doc__)
|
|
|
|
|
|
|
|
|
|
| 161 |
return parser.parse_args()
|
| 162 |
|
| 163 |
|
| 164 |
+
def discover_frames(frame_dir):
|
| 165 |
+
"""Pick the first available image from each camera sequence directory."""
|
| 166 |
+
frame_dir = Path(frame_dir)
|
| 167 |
+
if not frame_dir.is_dir():
|
| 168 |
+
raise FileNotFoundError(f"Frame directory does not exist: {frame_dir}")
|
| 169 |
+
frames = []
|
| 170 |
+
for camera_dir in sorted(path for path in frame_dir.iterdir() if path.is_dir()):
|
| 171 |
+
images = sorted(
|
| 172 |
+
path for path in camera_dir.iterdir()
|
| 173 |
+
if path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS
|
| 174 |
+
)
|
| 175 |
+
if images:
|
| 176 |
+
frames.append(images[0])
|
| 177 |
+
return frames
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def has_zones(config_path):
|
| 181 |
+
"""Return whether a saved zone config contains at least one zone."""
|
| 182 |
+
config_path = Path(config_path)
|
| 183 |
+
if not config_path.is_file():
|
| 184 |
+
return False
|
| 185 |
try:
|
| 186 |
+
config = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
|
| 187 |
+
except (OSError, yaml.YAMLError):
|
| 188 |
+
return False
|
| 189 |
+
if not isinstance(config, dict):
|
| 190 |
+
return False
|
| 191 |
+
zones = config.get("zones")
|
| 192 |
+
return isinstance(zones, dict) and bool(zones)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def choose_frame(frame_dir, output_dir):
|
| 196 |
+
frames = discover_frames(frame_dir)
|
| 197 |
+
if not frames:
|
| 198 |
+
raise FileNotFoundError(f"No camera frames found in: {frame_dir}")
|
| 199 |
+
print("Chọn camera/frame đại diện để kẻ zone:")
|
| 200 |
+
for index, frame in enumerate(frames, 1):
|
| 201 |
+
status = " --done" if has_zones(Path(output_dir) / f"{frame.parent.name}.yaml") else ""
|
| 202 |
+
print(f" {index}. {frame.parent.name}{status}")
|
| 203 |
+
while True:
|
| 204 |
+
answer = input(f"Nhập số camera (1-{len(frames)}): ").strip()
|
| 205 |
+
try:
|
| 206 |
+
index = int(answer)
|
| 207 |
+
except ValueError:
|
| 208 |
+
print("Vui lòng nhập một số hợp lệ.")
|
| 209 |
+
continue
|
| 210 |
+
if 1 <= index <= len(frames):
|
| 211 |
+
return frames[index - 1]
|
| 212 |
+
print(f"Số camera phải nằm trong khoảng 1-{len(frames)}.")
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def main():
|
| 216 |
+
parse_args()
|
| 217 |
+
source = choose_frame(DEFAULT_FRAME_DIR, DEFAULT_OUTPUT_DIR)
|
| 218 |
+
camera_id = source.parent.name
|
| 219 |
+
output = DEFAULT_OUTPUT_DIR / f"{camera_id}.yaml"
|
| 220 |
+
print(f"Dùng frame đại diện: {source}")
|
| 221 |
+
print(f"File zone sẽ lưu tại: {output}")
|
| 222 |
+
frame = cv2.imread(str(source))
|
| 223 |
+
if frame is None:
|
| 224 |
+
raise ValueError(f"Cannot read image frame: {source}")
|
| 225 |
+
ZoneLabeler(frame, camera_id, output).run()
|
| 226 |
|
| 227 |
|
| 228 |
if __name__ == "__main__":
|
docs/ARCHITECTURE.md
CHANGED
|
@@ -18,7 +18,7 @@ XML + frames → parser → canonical JSONL / TAR shards
|
|
| 18 |
annotation + CSV/JSON
|
| 19 |
```
|
| 20 |
|
| 21 |
-
Dataset không biết model. Detector không biết tracker. Tracker không biết calibration. Speed estimator
|
| 22 |
|
| 23 |
## Interface chung
|
| 24 |
|
|
@@ -66,9 +66,9 @@ Không thể đảm bảo bitwise reproducibility giữa phần cứng/PyTorch k
|
|
| 66 |
|
| 67 |
## Speed và timestamp
|
| 68 |
|
| 69 |
-
Homography kiểm tra finite, nonsingular, điểm trùng/thẳng hàng và fit error. Khi chiếu gần horizon, pipeline bỏ quan sát và reset history.
|
| 70 |
|
| 71 |
-
Gap dài
|
| 72 |
|
| 73 |
Video mặc định timestamp `frame_index/FPS`. Mode PTS đọc `CAP_PROP_POS_MSEC` và từ chối timestamp không đơn điệu. Output MP4 là constant-FPS theo nguồn, CSV giữ timestamp đã dùng để tính. FPS và frame size calibration phải khớp video, không tự scale homography mà không có xác nhận hình học.
|
| 74 |
|
|
|
|
| 18 |
annotation + CSV/JSON
|
| 19 |
```
|
| 20 |
|
| 21 |
+
Dataset không biết model. Detector không biết tracker. Tracker không biết calibration. Speed estimator nhận ID, tọa độ mét, timestamp giây và Jacobian truyền nhiễu pixel sang hệ tọa độ thế giới. Pipeline điều phối các module này.
|
| 22 |
|
| 23 |
## Interface chung
|
| 24 |
|
|
|
|
| 66 |
|
| 67 |
## Speed và timestamp
|
| 68 |
|
| 69 |
+
Homography kiểm tra finite, nonsingular, điểm trùng/thẳng hàng và fit error. Khi chiếu gần horizon, pipeline bỏ quan sát và reset history. Pipeline dùng Kalman constant-velocity 2D; độ lớn vector vận tốc nhân 3.6 ra km/h. Jacobian giải tích thay bốn phép chiếu sai phân; covariance cập nhật Joseph và gain tính bằng solve. Uncertainty dùng trị riêng lớn nhất của velocity covariance, có tính tương quan hai trục. Chuyển động rẽ gấp cần kiểm chứng với camera thực.
|
| 70 |
|
| 71 |
+
Gap dài hoặc timestamp không tăng khởi tạo lại trạng thái; innovation outlier trả N/A và reset sau `max_rejects`. Timeout tính từ observation cuối được chấp nhận, không từ lần predict/reject. `max_reasonable_kmh` và uncertainty gate kiểm soát việc xuất tốc độ, không chứng minh một track không có ID switch.
|
| 72 |
|
| 73 |
Video mặc định timestamp `frame_index/FPS`. Mode PTS đọc `CAP_PROP_POS_MSEC` và từ chối timestamp không đơn điệu. Output MP4 là constant-FPS theo nguồn, CSV giữ timestamp đã dùng để tính. FPS và frame size calibration phải khớp video, không tự scale homography mà không có xác nhận hình học.
|
| 74 |
|
docs/COLAB.md
CHANGED
|
@@ -64,9 +64,9 @@ Cache tải shard của split đang được sử dụng, chưa bảo đảm to
|
|
| 64 |
## 3. Train, evaluate, demo
|
| 65 |
|
| 66 |
```python
|
| 67 |
-
!python scripts/
|
| 68 |
-
!python scripts/
|
| 69 |
-
!python scripts/
|
| 70 |
```
|
| 71 |
|
| 72 |
Với video riêng, tải lên runtime hoặc truyền đường dẫn trực tiếp được OpenCV hỗ trợ rồi chạy `demo` như README. Chọn calibration points bằng JSON; Colab không hỗ trợ cửa sổ click OpenCV desktop.
|
|
|
|
| 64 |
## 3. Train, evaluate, demo
|
| 65 |
|
| 66 |
```python
|
| 67 |
+
!python scripts/run_trafficvision.py train --config outputs/colab.yaml
|
| 68 |
+
!python scripts/run_trafficvision.py evaluate --model faster_rcnn --checkpoint outputs/faster_rcnn/best.pt --config outputs/colab.yaml --device cuda --split test --output outputs/evaluation/detection.json
|
| 69 |
+
!python scripts/run_trafficvision.py track-dataset --model faster_rcnn --checkpoint outputs/faster_rcnn/best.pt --config outputs/colab.yaml --device cuda --tracker bytetrack --output outputs/evaluation/tracks.csv
|
| 70 |
```
|
| 71 |
|
| 72 |
Với video riêng, tải lên runtime hoặc truyền đường dẫn trực tiếp được OpenCV hỗ trợ rồi chạy `demo` như README. Chọn calibration points bằng JSON; Colab không hỗ trợ cửa sổ click OpenCV desktop.
|
docs/REVIEW_FIXES_2026-11-06.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Review và sửa chữa sau cập nhật của leader
|
| 2 |
+
|
| 3 |
+
Ngày: 2026-11-06. Base: `main` tại commit `db13bd6`.
|
| 4 |
+
Branch: `fix/kalman-speed-and-review-tools`.
|
| 5 |
+
|
| 6 |
+
## Phạm vi review
|
| 7 |
+
|
| 8 |
+
Đã đọc các cập nhật về camera YAML, Kalman speed estimator, polygon labeler, progress bars, training và CLI. Giữ hướng Kalman và các giá trị calibration/hyperparameter mà nhóm đang dùng. Chưa train hoặc tuning lại detector.
|
| 9 |
+
|
| 10 |
+
## Những vấn đề đã sửa
|
| 11 |
+
|
| 12 |
+
| Vấn đề | Thay đổi | Tác dụng |
|
| 13 |
+
|---|---|---|
|
| 14 |
+
| Kalman nhận noise bằng 0, giá trị NaN hoặc Jacobian suy biến | Kiểm tra tham số ngay khi khởi tạo; kiểm tra shape/finite/rank Jacobian, reset track lỗi | Báo lỗi rõ ràng, tránh truyền dữ liệu hỏng vào phép giải hệ tuyến tính |
|
| 15 |
+
| Covariance cập nhật bằng dạng rút gọn; gain dùng inverse | Joseph form, đối xứng hóa covariance; dùng `solve` cho gain | Cải thiện ổn định số của Kalman |
|
| 16 |
+
| Uncertainty chỉ nhìn hai phần tử đường chéo | Dùng trị riêng lớn nhất của velocity covariance | Gate theo hướng bất định lớn nhất, tính cả tương quan hai trục |
|
| 17 |
+
| Observation bị reject vẫn cập nhật thời gian dùng cho timeout | Tách `observed_t` và thời gian predict | Chuỗi outlier không giữ trạng thái cũ sống quá thời gian cho phép |
|
| 18 |
+
| Mỗi track cần bốn phép chiếu để xấp xỉ Jacobian | Thêm `Homography.jacobian()` giải tích; helper gọi công thức này | Giảm chi phí tính và bỏ sai số do bước sai phân 0.5 pixel |
|
| 19 |
+
| GUI cho phép lưu polygon chưa hoàn tất, rỗng hoặc suy biến | Chặn save không hợp lệ; kiểm tra điểm phân biệt/diện tích/tên; clamp tọa độ click vào frame | YAML tạo ra dùng được với zone manager, giảm việc vô tình bỏ mất polygon đang vẽ |
|
| 20 |
+
| README/Colab gọi `scripts/utils.py` không tồn tại | Đổi sang `scripts/run_trafficvision.py` | Copy lệnh từ tài liệu có thể chạy được |
|
| 21 |
+
| Tài liệu còn mô tả regression speed cũ | Đồng bộ README và architecture với Kalman hiện tại | Người đọc hiểu đúng thuật toán và giới hạn |
|
| 22 |
+
| Test inheritance hard-code LR 0.0001 trong khi base đã là 0.001 | So sánh với config base | Kiểm tra đúng inheritance, không ép nhóm quay lại LR cũ |
|
| 23 |
+
|
| 24 |
+
Ngoài ra, progress bar video cập nhật postfix với `refresh=False` để không ép redraw mỗi frame. Sửa unused import, đánh dấu bootstrap import của script và chuẩn hóa format. Các thay đổi trong CLI, tracking metrics và trainer chỉ là format.
|
| 25 |
+
|
| 26 |
+
Helper `pixel_jacobian` hiện nhận `(homography, point)`; tham số bước sai phân `eps` của bản cũ không còn cần thiết. Các caller trong repo đã dùng dạng hai tham số.
|
| 27 |
+
|
| 28 |
+
## Kiểm chứng
|
| 29 |
+
|
| 30 |
+
Môi trường: Python 3.12.3, PyTorch 2.5.1+cpu, Torchvision 0.20.1+cpu. Dùng môi trường đã có ở workspace, nhưng import source của checkout mới; không dựa vào package cũ để chạy demo.
|
| 31 |
+
|
| 32 |
+
- Trước sửa: **35 passed, 1 failed**; lỗi là test LR hard-code. Ruff báo 9 lỗi.
|
| 33 |
+
- Sau sửa: **55 passed**. Thêm 19 case cho tham số/Jacobian lỗi, covariance symmetric/PSD, gap/timestamp trùng, reject timeout, derivative perspective và polygon labeler.
|
| 34 |
+
- `ruff check src scripts tests data-labelling --no-cache`: đạt.
|
| 35 |
+
- `ruff format --check --no-cache src scripts tests data-labelling`: 87 file đạt.
|
| 36 |
+
- `git diff --check`: đạt.
|
| 37 |
+
- `python scripts/run_trafficvision.py --help`: chạy được.
|
| 38 |
+
- Labeler được kiểm tra logic và YAML headless; chưa kiểm tra thao tác cửa sổ desktop trên WSL.
|
| 39 |
+
|
| 40 |
+
### Đo riêng Jacobian
|
| 41 |
+
|
| 42 |
+
Cùng một homography perspective và một điểm, chạy 5.000 lần mỗi cách, lấy thời gian nhỏ nhất trong 3 lượt:
|
| 43 |
+
|
| 44 |
+
| Cách tính | Thời gian |
|
| 45 |
+
|---|---|
|
| 46 |
+
| Sai phân cũ, bốn phép chiếu | 0.3246 giây |
|
| 47 |
+
| Jacobian giải tích | 0.0869 giây |
|
| 48 |
+
|
| 49 |
+
Khoảng **3,74 lần** cho riêng Jacobian trên CPU này. Không suy ra FPS toàn pipeline tăng cùng tỷ lệ; validation rank/eigenvalue và detector vẫn có chi phí riêng.
|
| 50 |
+
|
| 51 |
+
### Chạy lại video giao thông thật
|
| 52 |
+
|
| 53 |
+
Dùng lại clip `vehicles.mp4` từ [Supervision assets](https://supervision.roboflow.com/assets/), đã tải ở workspace; bản 720p dài 21,52 giây, 25 FPS. Chạy source mới với YOLOv8n COCO pretrained + ByteTrack, không dùng calibration của camera khác.
|
| 54 |
+
|
| 55 |
+
- Xử lý và decode lại đủ **538/538 frame**.
|
| 56 |
+
- CSV và JSON đều có **1455 observation**, **17 tracking IDs**.
|
| 57 |
+
- Khoảng **9,15 FPS** trên CPU trong lượt này. Không coi đây là phép so sánh tốc độ có kiểm soát với lượt chạy cũ.
|
| 58 |
+
- Không có calibration nên speed là `N/A`/null trong toàn bộ export.
|
| 59 |
+
- Artifacts local: `outputs/review/real_video.mp4`, `.csv`, `.json`, `.summary.json`, `validation.json`, `preview_400.jpg`; được gitignore.
|
| 60 |
+
|
| 61 |
+
Lượt video kiểm tra inference/tracking/export. Kalman đã được kiểm tra trên quỹ đạo có tốc độ biết trước trong test; clip thật không có GT/calibration để xác minh sai số km/h. Số ID/observation không phải số xe ground-truth hay tracking accuracy.
|
| 62 |
+
|
| 63 |
+
## Phần nhóm cần kiểm chứng tiếp
|
| 64 |
+
|
| 65 |
+
Train/fine-tune và chấm UA-DETRAC cùng split; xác minh khoảng cách đo thực và calibration trên điểm độc lập; chấm tốc độ khi có GT; thử GUI trên desktop và runtime CUDA. Không thay các ma trận camera hoặc tự bổ sung khoảng cách giả trong PR này.
|
scripts/calibrate_camera.py
CHANGED
|
@@ -10,8 +10,9 @@ import sys
|
|
| 10 |
|
| 11 |
import cv2
|
| 12 |
import yaml
|
|
|
|
| 13 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
| 14 |
-
from trafficvision.geometry.homography import Homography
|
| 15 |
|
| 16 |
|
| 17 |
def main():
|
|
@@ -64,8 +65,15 @@ def main():
|
|
| 64 |
calibration=dict(
|
| 65 |
image_points=points, world_points=world, reprojection_error_m=homography.reprojection_error_m
|
| 66 |
),
|
| 67 |
-
speed=dict(
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
)
|
| 70 |
output = Path(args.output)
|
| 71 |
output.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 10 |
|
| 11 |
import cv2
|
| 12 |
import yaml
|
| 13 |
+
|
| 14 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
| 15 |
+
from trafficvision.geometry.homography import Homography # noqa: E402
|
| 16 |
|
| 17 |
|
| 18 |
def main():
|
|
|
|
| 65 |
calibration=dict(
|
| 66 |
image_points=points, world_points=world, reprojection_error_m=homography.reprojection_error_m
|
| 67 |
),
|
| 68 |
+
speed=dict(
|
| 69 |
+
sigma_px=1.0,
|
| 70 |
+
accel_std=2.0,
|
| 71 |
+
gate_chi2=16.0,
|
| 72 |
+
min_observations=8,
|
| 73 |
+
max_speed_std_kmh=4.0,
|
| 74 |
+
max_gap_seconds=0.5,
|
| 75 |
+
max_reasonable_kmh=160,
|
| 76 |
+
),
|
| 77 |
)
|
| 78 |
output = Path(args.output)
|
| 79 |
output.parent.mkdir(parents=True, exist_ok=True)
|
scripts/run_trafficvision.py
CHANGED
|
@@ -8,7 +8,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1]
|
|
| 8 |
SRC_DIR = REPO_ROOT / "src"
|
| 9 |
sys.path.insert(0, str(SRC_DIR))
|
| 10 |
|
| 11 |
-
from trafficvision.cli import main
|
| 12 |
|
| 13 |
|
| 14 |
if __name__ == "__main__":
|
|
|
|
| 8 |
SRC_DIR = REPO_ROOT / "src"
|
| 9 |
sys.path.insert(0, str(SRC_DIR))
|
| 10 |
|
| 11 |
+
from trafficvision.cli import main
|
| 12 |
|
| 13 |
|
| 14 |
if __name__ == "__main__":
|
src/trafficvision/cli.py
CHANGED
|
@@ -138,5 +138,7 @@ def main(argv=None):
|
|
| 138 |
speed_metrics([float(r["gt_kmh"]) for r in rows], [float(r["predicted_kmh"]) for r in rows]),
|
| 139 |
args.output,
|
| 140 |
)
|
|
|
|
|
|
|
| 141 |
if __name__ == "__main__":
|
| 142 |
main()
|
|
|
|
| 138 |
speed_metrics([float(r["gt_kmh"]) for r in rows], [float(r["predicted_kmh"]) for r in rows]),
|
| 139 |
args.output,
|
| 140 |
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
if __name__ == "__main__":
|
| 144 |
main()
|
src/trafficvision/evaluation/tracking_metrics.py
CHANGED
|
@@ -37,7 +37,9 @@ def sequence_data(ground_truth, predictions):
|
|
| 37 |
raise ValueError("Predictions contain frames absent from ground truth")
|
| 38 |
gt_maps, pred_maps = {}, {}
|
| 39 |
gt_ids, tracker_ids, similarities = [], [], []
|
| 40 |
-
for frame_id in tqdm(
|
|
|
|
|
|
|
| 41 |
row = ground_truth.get(frame_id, dict(boxes=[], labels=[], track_ids=[], ignored_regions=[]))
|
| 42 |
records = predictions.get(frame_id, [])
|
| 43 |
boxes = np.array([r["box"] for r in records], dtype=float).reshape(-1, 4)
|
|
@@ -87,7 +89,9 @@ def tracking_metrics(gt_manifest, prediction_csv, split="test"):
|
|
| 87 |
if row["split"] == split:
|
| 88 |
gt[row["video_id"]].append(row)
|
| 89 |
with open(prediction_csv) as handle:
|
| 90 |
-
predictions = tqdm(
|
|
|
|
|
|
|
| 91 |
for row in predictions:
|
| 92 |
if row["video_id"] not in gt:
|
| 93 |
raise ValueError(f"Prediction video outside {split} split: {row['video_id']}")
|
|
|
|
| 37 |
raise ValueError("Predictions contain frames absent from ground truth")
|
| 38 |
gt_maps, pred_maps = {}, {}
|
| 39 |
gt_ids, tracker_ids, similarities = [], [], []
|
| 40 |
+
for frame_id in tqdm(
|
| 41 |
+
range(1, max(ground_truth) + 1), desc="Aligning sequence", unit="frame", leave=False
|
| 42 |
+
):
|
| 43 |
row = ground_truth.get(frame_id, dict(boxes=[], labels=[], track_ids=[], ignored_regions=[]))
|
| 44 |
records = predictions.get(frame_id, [])
|
| 45 |
boxes = np.array([r["box"] for r in records], dtype=float).reshape(-1, 4)
|
|
|
|
| 89 |
if row["split"] == split:
|
| 90 |
gt[row["video_id"]].append(row)
|
| 91 |
with open(prediction_csv) as handle:
|
| 92 |
+
predictions = tqdm(
|
| 93 |
+
csv.DictReader(handle), desc="Loading tracking predictions", unit="record", leave=False
|
| 94 |
+
)
|
| 95 |
for row in predictions:
|
| 96 |
if row["video_id"] not in gt:
|
| 97 |
raise ValueError(f"Prediction video outside {split} split: {row['video_id']}")
|
src/trafficvision/geometry/homography.py
CHANGED
|
@@ -44,3 +44,18 @@ class Homography:
|
|
| 44 |
if np.any(abs(homogeneous[..., 2]) < 1e-8):
|
| 45 |
raise ValueError("Point lies on the homography horizon")
|
| 46 |
return homogeneous[..., :2] / homogeneous[..., 2:]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
if np.any(abs(homogeneous[..., 2]) < 1e-8):
|
| 45 |
raise ValueError("Point lies on the homography horizon")
|
| 46 |
return homogeneous[..., :2] / homogeneous[..., 2:]
|
| 47 |
+
|
| 48 |
+
def jacobian(self, point):
|
| 49 |
+
"""Analytic derivative of the perspective division at one image point."""
|
| 50 |
+
point = np.asarray(point, dtype=float)
|
| 51 |
+
if point.shape != (2,) or not np.isfinite(point).all():
|
| 52 |
+
raise ValueError("Jacobian needs one finite 2D point")
|
| 53 |
+
homogeneous = self.matrix @ np.r_[point, 1.0]
|
| 54 |
+
denominator = homogeneous[2]
|
| 55 |
+
if abs(denominator) < 1e-8:
|
| 56 |
+
raise ValueError("Point lies on the homography horizon")
|
| 57 |
+
world = homogeneous[:2] / denominator
|
| 58 |
+
result = (self.matrix[:2, :2] - world[:, None] * self.matrix[2, :2]) / denominator
|
| 59 |
+
if not np.isfinite(result).all():
|
| 60 |
+
raise ValueError("Non-finite homography Jacobian")
|
| 61 |
+
return result
|
src/trafficvision/pipeline/detection_tracking.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
from ..geometry.coordinates import bottom_center
|
| 2 |
-
from ..speed.estimator import SpeedEstimator
|
| 3 |
from ..speed.kalman_speed import KalmanSpeedEstimator, pixel_jacobian
|
| 4 |
from ..zones.zone_manager import ZoneManager
|
| 5 |
|
|
|
|
| 1 |
from ..geometry.coordinates import bottom_center
|
|
|
|
| 2 |
from ..speed.kalman_speed import KalmanSpeedEstimator, pixel_jacobian
|
| 3 |
from ..zones.zone_manager import ZoneManager
|
| 4 |
|
src/trafficvision/pipeline/video_pipeline.py
CHANGED
|
@@ -56,11 +56,15 @@ def run_video(
|
|
| 56 |
ok, frame = cap.read()
|
| 57 |
if not ok:
|
| 58 |
break
|
| 59 |
-
timestamp =
|
|
|
|
|
|
|
| 60 |
if not math.isfinite(timestamp) or (
|
| 61 |
previous_timestamp is not None and timestamp <= previous_timestamp
|
| 62 |
):
|
| 63 |
-
raise ValueError(
|
|
|
|
|
|
|
| 64 |
previous_timestamp = timestamp
|
| 65 |
frame_id += 1
|
| 66 |
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
|
@@ -70,7 +74,7 @@ def run_video(
|
|
| 70 |
writer.write(annotate(frame, results, pipeline.zones, processing_fps))
|
| 71 |
exporter.write(video_id or Path(str(source)).stem, frame_id, timestamp, results)
|
| 72 |
progress.update(1)
|
| 73 |
-
progress.set_postfix(fps=f"{processing_fps:.1f}")
|
| 74 |
if frame_id == 0:
|
| 75 |
raise ValueError("Source has no readable video frames")
|
| 76 |
summary = dict(
|
|
|
|
| 56 |
ok, frame = cap.read()
|
| 57 |
if not ok:
|
| 58 |
break
|
| 59 |
+
timestamp = (
|
| 60 |
+
cap.get(cv2.CAP_PROP_POS_MSEC) / 1000 if timestamp_mode == "pts" else frame_id / fps
|
| 61 |
+
)
|
| 62 |
if not math.isfinite(timestamp) or (
|
| 63 |
previous_timestamp is not None and timestamp <= previous_timestamp
|
| 64 |
):
|
| 65 |
+
raise ValueError(
|
| 66 |
+
"Non-monotonic/missing PTS; use --timestamp-mode fps for constant-FPS video"
|
| 67 |
+
)
|
| 68 |
previous_timestamp = timestamp
|
| 69 |
frame_id += 1
|
| 70 |
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
|
|
|
| 74 |
writer.write(annotate(frame, results, pipeline.zones, processing_fps))
|
| 75 |
exporter.write(video_id or Path(str(source)).stem, frame_id, timestamp, results)
|
| 76 |
progress.update(1)
|
| 77 |
+
progress.set_postfix(fps=f"{processing_fps:.1f}", refresh=False)
|
| 78 |
if frame_id == 0:
|
| 79 |
raise ValueError("Source has no readable video frames")
|
| 80 |
summary = dict(
|
src/trafficvision/speed/kalman_speed.py
CHANGED
|
@@ -4,13 +4,34 @@ Measurement noise is propagated from pixel noise through the homography Jacobian
|
|
| 4 |
far-away (noisy) observations are automatically down-weighted. Gating is done on the
|
| 5 |
Mahalanobis distance of the innovation, not on instantaneous speed.
|
| 6 |
"""
|
|
|
|
| 7 |
import math
|
| 8 |
import numpy as np
|
| 9 |
|
| 10 |
|
| 11 |
class KalmanSpeedEstimator:
|
| 12 |
-
def __init__(
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
self.sigma_px, self.q = sigma_px, accel_std
|
| 15 |
self.gate, self.min_obs, self.max_std = gate_chi2, min_observations, max_speed_std_kmh / 3.6
|
| 16 |
self.max_gap, self.vmax, self.max_rejects = max_gap_seconds, max_reasonable_kmh / 3.6, max_rejects
|
|
@@ -20,50 +41,63 @@ class KalmanSpeedEstimator:
|
|
| 20 |
self.state.clear() if track_id is None else self.state.pop(track_id, None)
|
| 21 |
|
| 22 |
def prune(self, timestamp):
|
| 23 |
-
for k in [k for k, s in self.state.items() if timestamp - s["
|
| 24 |
self.state.pop(k)
|
| 25 |
|
| 26 |
def _init(self, z, R, t):
|
| 27 |
x = np.array([z[0], z[1], 0.0, 0.0])
|
| 28 |
-
P = np.zeros((4, 4))
|
| 29 |
-
|
|
|
|
|
|
|
| 30 |
|
| 31 |
def update(self, track_id, world, timestamp, jacobian=None):
|
| 32 |
z = np.asarray(world, float)
|
| 33 |
if z.shape != (2,) or not np.isfinite(z).all() or not math.isfinite(timestamp):
|
| 34 |
-
self.reset(track_id)
|
|
|
|
| 35 |
J = np.eye(2) if jacobian is None else np.asarray(jacobian, float)
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
| 37 |
s = self.state.get(track_id)
|
| 38 |
-
if
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
dt = timestamp - s["t"]
|
| 41 |
-
F = np.eye(4)
|
|
|
|
| 42 |
G = np.array([[dt**2 / 2, 0], [0, dt**2 / 2], [dt, 0], [0, dt]])
|
| 43 |
-
Q = (self.q
|
| 44 |
x, P = F @ s["x"], F @ s["P"] @ F.T + Q
|
| 45 |
-
Hm = np.eye(2, 4)
|
|
|
|
| 46 |
innov = z - Hm @ x
|
| 47 |
-
if innov @ np.linalg.solve(S, innov) > self.gate:
|
| 48 |
s.update(x=x, P=P, t=timestamp, rejects=s["rejects"] + 1)
|
| 49 |
if s["rejects"] >= self.max_rejects:
|
| 50 |
self.state[track_id] = self._init(z, R, timestamp)
|
| 51 |
return None
|
| 52 |
-
K =
|
| 53 |
-
x = x + K @ innov
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
if s["n"] < self.min_obs or vstd > self.max_std or speed > self.vmax:
|
| 58 |
return None
|
| 59 |
return speed * 3.6
|
| 60 |
|
| 61 |
|
| 62 |
-
def pixel_jacobian(homography, point
|
| 63 |
-
"""2x2
|
| 64 |
-
|
| 65 |
-
du = (homography.project(p + [eps, 0]) - homography.project(p - [eps, 0])) / (2 * eps)
|
| 66 |
-
dv = (homography.project(p + [0, eps]) - homography.project(p - [0, eps])) / (2 * eps)
|
| 67 |
-
return np.stack([du, dv], axis=1)
|
| 68 |
-
|
| 69 |
-
|
|
|
|
| 4 |
far-away (noisy) observations are automatically down-weighted. Gating is done on the
|
| 5 |
Mahalanobis distance of the innovation, not on instantaneous speed.
|
| 6 |
"""
|
| 7 |
+
|
| 8 |
import math
|
| 9 |
import numpy as np
|
| 10 |
|
| 11 |
|
| 12 |
class KalmanSpeedEstimator:
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
sigma_px=1.0,
|
| 16 |
+
accel_std=2.0,
|
| 17 |
+
gate_chi2=16.0,
|
| 18 |
+
min_observations=8,
|
| 19 |
+
max_speed_std_kmh=4.0,
|
| 20 |
+
max_gap_seconds=0.5,
|
| 21 |
+
max_reasonable_kmh=160,
|
| 22 |
+
max_rejects=3,
|
| 23 |
+
):
|
| 24 |
+
positive = (sigma_px, gate_chi2, max_speed_std_kmh, max_gap_seconds, max_reasonable_kmh)
|
| 25 |
+
if not all(math.isfinite(value) and value > 0 for value in positive):
|
| 26 |
+
raise ValueError("Noise, gate, uncertainty, gap and speed limits must be finite and positive")
|
| 27 |
+
if not math.isfinite(accel_std) or accel_std < 0:
|
| 28 |
+
raise ValueError("accel_std must be finite and nonnegative")
|
| 29 |
+
for name, value, minimum in (
|
| 30 |
+
("min_observations", min_observations, 2),
|
| 31 |
+
("max_rejects", max_rejects, 1),
|
| 32 |
+
):
|
| 33 |
+
if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or value < minimum:
|
| 34 |
+
raise ValueError(f"{name} must be an integer >= {minimum}")
|
| 35 |
self.sigma_px, self.q = sigma_px, accel_std
|
| 36 |
self.gate, self.min_obs, self.max_std = gate_chi2, min_observations, max_speed_std_kmh / 3.6
|
| 37 |
self.max_gap, self.vmax, self.max_rejects = max_gap_seconds, max_reasonable_kmh / 3.6, max_rejects
|
|
|
|
| 41 |
self.state.clear() if track_id is None else self.state.pop(track_id, None)
|
| 42 |
|
| 43 |
def prune(self, timestamp):
|
| 44 |
+
for k in [k for k, s in self.state.items() if timestamp - s["observed_t"] > self.max_gap]:
|
| 45 |
self.state.pop(k)
|
| 46 |
|
| 47 |
def _init(self, z, R, t):
|
| 48 |
x = np.array([z[0], z[1], 0.0, 0.0])
|
| 49 |
+
P = np.zeros((4, 4))
|
| 50 |
+
P[:2, :2] = R
|
| 51 |
+
P[2:, 2:] = np.eye(2) * (self.vmax / 2) ** 2
|
| 52 |
+
return dict(x=x, P=P, t=t, observed_t=t, n=1, rejects=0)
|
| 53 |
|
| 54 |
def update(self, track_id, world, timestamp, jacobian=None):
|
| 55 |
z = np.asarray(world, float)
|
| 56 |
if z.shape != (2,) or not np.isfinite(z).all() or not math.isfinite(timestamp):
|
| 57 |
+
self.reset(track_id)
|
| 58 |
+
return None
|
| 59 |
J = np.eye(2) if jacobian is None else np.asarray(jacobian, float)
|
| 60 |
+
if J.shape != (2, 2) or not np.isfinite(J).all() or np.linalg.matrix_rank(J) < 2:
|
| 61 |
+
self.reset(track_id)
|
| 62 |
+
raise ValueError("Jacobian must be a finite, nonsingular 2x2 matrix")
|
| 63 |
+
R = (self.sigma_px**2) * J @ J.T
|
| 64 |
s = self.state.get(track_id)
|
| 65 |
+
if (
|
| 66 |
+
s is None
|
| 67 |
+
or not (0 < timestamp - s["t"] <= self.max_gap)
|
| 68 |
+
or timestamp - s["observed_t"] > self.max_gap
|
| 69 |
+
):
|
| 70 |
+
self.state[track_id] = self._init(z, R, timestamp)
|
| 71 |
+
return None
|
| 72 |
dt = timestamp - s["t"]
|
| 73 |
+
F = np.eye(4)
|
| 74 |
+
F[0, 2] = F[1, 3] = dt
|
| 75 |
G = np.array([[dt**2 / 2, 0], [0, dt**2 / 2], [dt, 0], [0, dt]])
|
| 76 |
+
Q = (self.q**2) * G @ G.T
|
| 77 |
x, P = F @ s["x"], F @ s["P"] @ F.T + Q
|
| 78 |
+
Hm = np.eye(2, 4)
|
| 79 |
+
S = Hm @ P @ Hm.T + R
|
| 80 |
innov = z - Hm @ x
|
| 81 |
+
if innov @ np.linalg.solve(S, innov) > self.gate: # outlier / ID jump
|
| 82 |
s.update(x=x, P=P, t=timestamp, rejects=s["rejects"] + 1)
|
| 83 |
if s["rejects"] >= self.max_rejects:
|
| 84 |
self.state[track_id] = self._init(z, R, timestamp)
|
| 85 |
return None
|
| 86 |
+
K = np.linalg.solve(S, Hm @ P).T
|
| 87 |
+
x = x + K @ innov
|
| 88 |
+
residual = np.eye(4) - K @ Hm
|
| 89 |
+
# Joseph form preserves positive semidefiniteness under rounding.
|
| 90 |
+
P = residual @ P @ residual.T + K @ R @ K.T
|
| 91 |
+
P = (P + P.T) / 2
|
| 92 |
+
s.update(x=x, P=P, t=timestamp, observed_t=timestamp, n=s["n"] + 1, rejects=0)
|
| 93 |
+
speed = float(np.linalg.norm(x[2:]))
|
| 94 |
+
# Correlated axes can have larger uncertainty than either diagonal alone.
|
| 95 |
+
vstd = math.sqrt(max(float(np.linalg.eigvalsh(P[2:, 2:])[-1]), 0.0))
|
| 96 |
if s["n"] < self.min_obs or vstd > self.max_std or speed > self.vmax:
|
| 97 |
return None
|
| 98 |
return speed * 3.6
|
| 99 |
|
| 100 |
|
| 101 |
+
def pixel_jacobian(homography, point):
|
| 102 |
+
"""Exact 2x2 d(world_xy)/d(pixel_uv), in metres per pixel."""
|
| 103 |
+
return homography.jacobian(point)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/trafficvision/training/trainer.py
CHANGED
|
@@ -150,7 +150,9 @@ def train(config, model_name=None, init=None, resume=None):
|
|
| 150 |
current = metrics["map"]
|
| 151 |
improved = current > best
|
| 152 |
best = max(current, best)
|
| 153 |
-
record = dict(
|
|
|
|
|
|
|
| 154 |
epoch_progress.set_postfix(loss=f"{record['loss']:.4f}", val_map=f"{current:.4f}")
|
| 155 |
with (output / "metrics.jsonl").open("a") as handle:
|
| 156 |
handle.write(json.dumps(record) + "\n")
|
|
|
|
| 150 |
current = metrics["map"]
|
| 151 |
improved = current > best
|
| 152 |
best = max(current, best)
|
| 153 |
+
record = dict(
|
| 154 |
+
epoch=epoch, loss=losses / steps, lr=optimizer.param_groups[0]["lr"], metrics=metrics
|
| 155 |
+
)
|
| 156 |
epoch_progress.set_postfix(loss=f"{record['loss']:.4f}", val_map=f"{current:.4f}")
|
| 157 |
with (output / "metrics.jsonl").open("a") as handle:
|
| 158 |
handle.write(json.dumps(record) + "\n")
|
tests/test_kalman_robustness.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
from trafficvision.geometry.homography import Homography
|
| 4 |
+
from trafficvision.speed.kalman_speed import KalmanSpeedEstimator, pixel_jacobian
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@pytest.mark.parametrize(
|
| 8 |
+
"params",
|
| 9 |
+
[
|
| 10 |
+
dict(sigma_px=0),
|
| 11 |
+
dict(sigma_px=float("nan")),
|
| 12 |
+
dict(accel_std=-1),
|
| 13 |
+
dict(gate_chi2=0),
|
| 14 |
+
dict(max_gap_seconds=0),
|
| 15 |
+
dict(min_observations=1),
|
| 16 |
+
dict(max_rejects=0),
|
| 17 |
+
dict(max_speed_std_kmh=float("inf")),
|
| 18 |
+
dict(max_reasonable_kmh=-1),
|
| 19 |
+
dict(min_observations=2.5),
|
| 20 |
+
],
|
| 21 |
+
)
|
| 22 |
+
def test_invalid_config_fails_early(params):
|
| 23 |
+
with pytest.raises(ValueError):
|
| 24 |
+
KalmanSpeedEstimator(**params)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@pytest.mark.parametrize("jacobian", [np.zeros((2, 2)), np.ones((3, 2)), [[1, 0], [0, float("nan")]]])
|
| 28 |
+
def test_bad_jacobian_resets_track(jacobian):
|
| 29 |
+
estimator = KalmanSpeedEstimator()
|
| 30 |
+
estimator.update(1, [0, 0], 0)
|
| 31 |
+
with pytest.raises(ValueError, match="Jacobian"):
|
| 32 |
+
estimator.update(1, [1, 0], 0.04, jacobian)
|
| 33 |
+
assert 1 not in estimator.state
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_perspective_jacobian_matches_small_step_difference():
|
| 37 |
+
h = Homography([[0.3, 0.1, 2], [0.05, 0.5, 4], [0.001, 0.002, 1]])
|
| 38 |
+
point = np.array([200.0, 100.0])
|
| 39 |
+
epsilon = 1e-4
|
| 40 |
+
expected = np.column_stack(
|
| 41 |
+
[
|
| 42 |
+
(h.project(point + axis * epsilon) - h.project(point - axis * epsilon)) / (2 * epsilon)
|
| 43 |
+
for axis in np.eye(2)
|
| 44 |
+
]
|
| 45 |
+
)
|
| 46 |
+
np.testing.assert_allclose(pixel_jacobian(h, point), expected, rtol=1e-7, atol=1e-8)
|
| 47 |
+
with pytest.raises(ValueError, match="horizon"):
|
| 48 |
+
Homography([[1, 0, 0], [0, 1, 0], [1, 0, 1]]).jacobian([-1, 0])
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_covariance_remains_symmetric_psd_with_correlated_noise():
|
| 52 |
+
estimator = KalmanSpeedEstimator(sigma_px=0.2)
|
| 53 |
+
J = np.array([[0.1, 0.04], [0.04, 0.2]])
|
| 54 |
+
for i in range(150):
|
| 55 |
+
estimator.update(1, [i * 0.08, i * 0.16], i * 0.04, J)
|
| 56 |
+
covariance = estimator.state[1]["P"]
|
| 57 |
+
np.testing.assert_allclose(covariance, covariance.T, atol=1e-12)
|
| 58 |
+
assert np.linalg.eigvalsh(covariance).min() >= -1e-12
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_rejected_observations_do_not_keep_old_track_alive():
|
| 62 |
+
estimator = KalmanSpeedEstimator(max_rejects=100, max_gap_seconds=0.15)
|
| 63 |
+
for i in range(30):
|
| 64 |
+
estimator.update(1, [i * 0.4, 0], i * 0.04)
|
| 65 |
+
for i in range(30, 33):
|
| 66 |
+
assert estimator.update(1, [1000, 0], i * 0.04) is None
|
| 67 |
+
estimator.prune(1.32)
|
| 68 |
+
assert 1 not in estimator.state
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_gap_and_duplicate_timestamp_restart_warmup():
|
| 72 |
+
estimator = KalmanSpeedEstimator(sigma_px=0.1)
|
| 73 |
+
for i in range(30):
|
| 74 |
+
estimator.update(1, [i * 0.4, 0], i * 0.04)
|
| 75 |
+
assert estimator.update(1, [11.6, 0], 1.16) is None
|
| 76 |
+
assert estimator.state[1]["n"] == 1
|
| 77 |
+
assert estimator.update(1, [30, 0], 3) is None
|
| 78 |
+
assert estimator.state[1]["n"] == 1
|
tests/test_speed_estimator.py
CHANGED
|
@@ -18,10 +18,12 @@ def test_speed_metric_zero_ground_truth():
|
|
| 18 |
result = speed_metrics([0, 10], [1, 12])
|
| 19 |
assert result["mae"] == 1.5 and result["mape"] == 20
|
| 20 |
|
|
|
|
| 21 |
def test_kalman_constant_speed_and_jump_rejection():
|
| 22 |
from trafficvision.speed.kalman_speed import KalmanSpeedEstimator
|
|
|
|
| 23 |
est = KalmanSpeedEstimator(sigma_px=0.1)
|
| 24 |
out = [est.update(1, [0.0, 10.0 * i / 25], i / 25) for i in range(30)] # 10 m/s
|
| 25 |
-
assert out[2] is None
|
| 26 |
assert out[-1] == pytest.approx(36, abs=0.5)
|
| 27 |
-
assert est.update(1, [0.0, 500.0], 30 / 25) is None # nhảy ID bị loại
|
|
|
|
| 18 |
result = speed_metrics([0, 10], [1, 12])
|
| 19 |
assert result["mae"] == 1.5 and result["mape"] == 20
|
| 20 |
|
| 21 |
+
|
| 22 |
def test_kalman_constant_speed_and_jump_rejection():
|
| 23 |
from trafficvision.speed.kalman_speed import KalmanSpeedEstimator
|
| 24 |
+
|
| 25 |
est = KalmanSpeedEstimator(sigma_px=0.1)
|
| 26 |
out = [est.update(1, [0.0, 10.0 * i / 25], i / 25) for i in range(30)] # 10 m/s
|
| 27 |
+
assert out[2] is None # chưa đủ quan sát
|
| 28 |
assert out[-1] == pytest.approx(36, abs=0.5)
|
| 29 |
+
assert est.update(1, [0.0, 500.0], 30 / 25) is None # nhảy ID bị loại
|
tests/test_training.py
CHANGED
|
@@ -38,4 +38,6 @@ def test_train_save_resume_evaluate(prepared, tmp_path, model_name):
|
|
| 38 |
|
| 39 |
def test_config_inheritance():
|
| 40 |
config = load_config("configs/experiments/faster_rcnn_scratch.yaml")
|
| 41 |
-
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
def test_config_inheritance():
|
| 40 |
config = load_config("configs/experiments/faster_rcnn_scratch.yaml")
|
| 41 |
+
base = load_config("configs/experiments/base.yaml")
|
| 42 |
+
assert config["model"]["name"] == "faster_rcnn"
|
| 43 |
+
assert config["training"]["lr"] == base["training"]["lr"]
|
tests/test_zone_labeler.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
import yaml
|
| 6 |
+
from trafficvision.zones.zone_manager import ZoneManager
|
| 7 |
+
|
| 8 |
+
spec = importlib.util.spec_from_file_location(
|
| 9 |
+
"zone_labeler", Path(__file__).parents[1] / "data-labelling/zone_labeler.py"
|
| 10 |
+
)
|
| 11 |
+
module = importlib.util.module_from_spec(spec)
|
| 12 |
+
spec.loader.exec_module(module)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_labeler_rejects_invalid_polygons_and_incomplete_save(tmp_path):
|
| 16 |
+
labeler = module.ZoneLabeler(np.zeros((540, 960, 3), np.uint8), "test", tmp_path / "zones.yaml")
|
| 17 |
+
with pytest.raises(ValueError, match="at least one"):
|
| 18 |
+
labeler.save()
|
| 19 |
+
labeler.current = [[1, 1], [2, 2], [3, 3]]
|
| 20 |
+
with pytest.raises(ValueError, match="nonzero area"):
|
| 21 |
+
labeler.finish_zone("road")
|
| 22 |
+
with pytest.raises(ValueError, match="Finish"):
|
| 23 |
+
labeler.save()
|
| 24 |
+
labeler.current = [[0, 0], [100, 0], [100, 100]]
|
| 25 |
+
labeler.finish_zone("road")
|
| 26 |
+
labeler.save()
|
| 27 |
+
config = yaml.safe_load(labeler.output.read_text())
|
| 28 |
+
manager = ZoneManager(config)
|
| 29 |
+
manager.validate_frame(960, 540)
|
| 30 |
+
assert manager.zones[0].contains([50, 25])
|
| 31 |
+
labeler.current = [[0, 0], [10, 0], [10, 10]]
|
| 32 |
+
with pytest.raises(ValueError, match="unique"):
|
| 33 |
+
labeler.finish_zone("road")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_display_coordinates_scale_and_clip(tmp_path):
|
| 37 |
+
labeler = module.ZoneLabeler(np.zeros((2160, 3840, 3), np.uint8), "test", tmp_path / "zones.yaml")
|
| 38 |
+
labeler.display_frame()
|
| 39 |
+
assert labeler.to_frame_point(700, 350) == [1920, 960]
|
| 40 |
+
assert labeler.to_frame_point(-10, 5000) == [0, 2159]
|