Sync frame-based zone labeling changes
Browse filesFiles changed (21)
- README.md+24-14
- configs/zones/MVI_40191.yamlAdded+61
- configs/zones/MVI_40244.yamlAdded+59
- 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.mdAdded+65
- scripts/calibrate_camera.py+11-3
- scripts/run_trafficvision.py+1-1
- src/trafficvision/cli.py+2
- src/trafficvision/evaluation/tracking_metrics.py+6-2
- src/trafficvision/geometry/homography.py+15
- src/trafficvision/pipeline/detection_tracking.py-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.pyAdded+78
- tests/test_speed_estimator.py+4-2
- tests/test_training.py+3-1
- tests/test_zone_labeler.pyAdded+40
19 unmodified lines2021222324252651 unmodified lines787980818283848586878889909192939495962 unmodified lines991001011021031041051061071089 unmodified lines1181191201211221231242 unmodified lines1271281291301311327 unmodified lines1401411421431441451461471481491 unmodified line1511521531541551561572 unmodified lines16016116216316416516618 unmodified lines18518618718819 unmodified lines# Ultralytics có thể cài opencv-python; cài contrib cuối để Selective Search có ximgproc.python -m pip install --force-reinstall --no-deps opencv-contrib-python-headless==4.10.0.84python scripts/utils.py --helppython -m pytest -q```51 unmodified linesSử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ó.```bashpython scripts/utils.py train --model faster_rcnn --init random \--config configs/experiments/faster_rcnn_scratch.yamlpython scripts/utils.py train --model fast_rcnn --init random \--config configs/experiments/fast_rcnn_scratch.yamlpython scripts/utils.py train --model rcnn --init random \--config configs/experiments/rcnn_scratch.yamlpython scripts/utils.py train --model rtdetr --init random \--config configs/experiments/rtdetr_scratch.yamlpython scripts/utils.py train --model yolov8 --init pretrained \--config configs/experiments/yolov8_baseline.yaml```2 unmodified linesCustom 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:```bashpython scripts/utils.py train --config configs/experiments/faster_rcnn_scratch.yaml \--resume outputs/faster_rcnn/last.ptpython scripts/utils.py evaluate --model faster_rcnn \--checkpoint outputs/faster_rcnn/best.pt --split test \--config configs/evaluation/ua_detrac.yaml --output outputs/evaluation/faster_rcnn.json```9 unmodified linesĐể đo tracking trên **toàn split**, không cần ghép ảnh thành MP4:```bashpython scripts/utils.py track-dataset --model faster_rcnn \--checkpoint outputs/faster_rcnn/best.pt --tracker bytetrack --split test \--config configs/evaluation/ua_detrac.yaml --output outputs/evaluation/faster_bytetrack.csv```2 unmodified linesPolygon 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.## 5. Phase 4 — Calibration và vận tốcVớ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.7 unmodified linesDesktop 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.Speed estimator hồi quy vị trí thế giới theo timestamp trong cửa sổ, trả `N/A` khi thiếu quan sát, thời gian trùng/ngược, gap dài, bước nhảy quá lớn hoặc chưa có homography. 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.```bashpython scripts/utils.py evaluate-speed --pairs /path/to/matched_speed_pairs.csv```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.1 unmodified line## 6. Phase 5 — Video demo```bashpython scripts/utils.py demo --source /path/to/traffic.mp4 \--model faster_rcnn --checkpoint outputs/faster_rcnn/best.pt --tracker bytetrack \--camera-config configs/cameras/MVI_20011.yaml --zone-config configs/zones/MVI_20011.yaml \--output outputs/demo/faster_bytetrack.mp42 unmodified linesCó thể bỏ camera/zone config để xem detection + tracking, speed `N/A`. Video pretrained chưa fine-tune:```bashpython scripts/utils.py demo --source /path/to/traffic.mp4 --model yolov8 \--config configs/models/yolov8.yaml --tracker bytetrack --output outputs/demo/yolo_coco.mp4```18 unmodified lines| `pipeline/`, `visualization/` | Điều phối, video và export || `configs/`, `scripts/`, `tests/` | Thí nghiệm, công cụ và regression tests |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`. Workspace chưa được khởi tạo Git; nhóm tự kết nối repository của mình.19 unmodified lines2021222324252651 unmodified lines787980818283848586878889909192939495962 unmodified lines991001011021031041051061071089 unmodified lines1181191201211221231242 unmodified lines1271281291301311321331341351361371381391401411427 unmodified lines1501511521531541551561571581591 unmodified line1611621631641651661672 unmodified lines17017117217317417517618 unmodified lines19519619719819 unmodified lines# Ultralytics có thể cài opencv-python; cài contrib cuối để Selective Search có ximgproc.python -m pip install --force-reinstall --no-deps opencv-contrib-python-headless==4.10.0.84python scripts/run_trafficvision.py --helppython -m pytest -q```51 unmodified linesSử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ó.```bashpython scripts/run_trafficvision.py train --model faster_rcnn --init random \--config configs/experiments/faster_rcnn_scratch.yamlpython scripts/run_trafficvision.py train --model fast_rcnn --init random \--config configs/experiments/fast_rcnn_scratch.yamlpython scripts/run_trafficvision.py train --model rcnn --init random \--config configs/experiments/rcnn_scratch.yamlpython scripts/run_trafficvision.py train --model rtdetr --init random \--config configs/experiments/rtdetr_scratch.yamlpython scripts/run_trafficvision.py train --model yolov8 --init pretrained \--config configs/experiments/yolov8_baseline.yaml```2 unmodified linesCustom 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:```bashpython scripts/run_trafficvision.py train --config configs/experiments/faster_rcnn_scratch.yaml \--resume outputs/faster_rcnn/last.ptpython scripts/run_trafficvision.py evaluate --model faster_rcnn \--checkpoint outputs/faster_rcnn/best.pt --split test \--config configs/evaluation/ua_detrac.yaml --output outputs/evaluation/faster_rcnn.json```9 unmodified linesĐể đo tracking trên **toàn split**, không cần ghép ảnh thành MP4:```bashpython scripts/run_trafficvision.py track-dataset --model faster_rcnn \--checkpoint outputs/faster_rcnn/best.pt --tracker bytetrack --split test \--config configs/evaluation/ua_detrac.yaml --output outputs/evaluation/faster_bytetrack.csv```2 unmodified linesPolygon 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.Có thể chạy zone labeler không cần tham số. Chương trình liệt kê các video trong`data/ua_detrac`; video đã có `configs/zones/<VIDEO_ID>.yaml` sẽ được đánh dấu`--done`. Sau khi chọn, chương trình chỉ đọc frame đầu tiên để kẻ polygon:```bashpython data-labelling/zone_labeler.py```Mỗi video được lưu zone riêng theo ID để dễ kiểm tra tiến độ.## 5. Phase 4 — Calibration và vận tốcVớ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.7 unmodified linesDesktop 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.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.```bashpython scripts/run_trafficvision.py evaluate-speed --pairs /path/to/matched_speed_pairs.csv```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.1 unmodified line## 6. Phase 5 — Video demo```bashpython scripts/run_trafficvision.py demo --source /path/to/traffic.mp4 \--model faster_rcnn --checkpoint outputs/faster_rcnn/best.pt --tracker bytetrack \--camera-config configs/cameras/MVI_20011.yaml --zone-config configs/zones/MVI_20011.yaml \--output outputs/demo/faster_bytetrack.mp42 unmodified linesCó thể bỏ camera/zone config để xem detection + tracking, speed `N/A`. Video pretrained chưa fine-tune:```bashpython scripts/run_trafficvision.py demo --source /path/to/traffic.mp4 --model yolov8 \--config configs/models/yolov8.yaml --tracker bytetrack --output outputs/demo/yolo_coco.mp4```18 unmodified lines| `pipeline/`, `visualization/` | Điều phối, video và export || `configs/`, `scripts/`, `tests/` | Thí nghiệm, công cụ và regression tests |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.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061camera_id: MVI_40191frame_size:- 960- 540roi_only: truedefault_threshold: 0.25zones: far_zone: polygon: - - 384 - 69 - - 511 - 71 - - 475 - 207 - - 195 - 172 confidence_threshold: 0.05 inference_scale: 1.0 measure_speed: true far_zone_lane2: polygon: - - 549 - 74 - - 708 - 77 - - 957 - 211 - - 574 - 210 confidence_threshold: 0.05 inference_scale: 1.0 measure_speed: true near_zone: polygon: - - 191 - 173 - - 473 - 208 - - 382 - 535 - - 2 - 537 - - 0 - 274 confidence_threshold: 0.05 inference_scale: 1.0 measure_speed: true near_zone2: polygon: - - 575 - 210 - - 959 - 210 - - 958 - 536 - - 632 - 536 confidence_threshold: 0.05 inference_scale: 1.0 measure_speed: true1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859camera_id: MVI_40244frame_size:- 960- 540roi_only: truedefault_threshold: 0.25zones: far_zone1: polygon: - - 662 - 57 - - 770 - 54 - - 629 - 121 - - 509 - 102 confidence_threshold: 0.05 inference_scale: 1.0 measure_speed: true far_zone2: polygon: - - 796 - 56 - - 958 - 57 - - 959 - 148 - - 700 - 132 confidence_threshold: 0.05 inference_scale: 1.0 measure_speed: true near_zone1: polygon: - - 508 - 104 - - 627 - 123 - - 0 - 471 - - 0 - 279 confidence_threshold: 0.05 inference_scale: 1.0 measure_speed: true near_zone2: polygon: - - 703 - 132 - - 959 - 149 - - 959 - 533 - - 141 - 539 confidence_threshold: 0.05 inference_scale: 1.0 measure_speed: true1 unmodified line23456789101112136 unmodified lines20212223241 unmodified line## Create polygon zonesRun the GUI from the repository root:```bashpython data-labelling/zone_labeler.py \--source /path/to/MVI_20011.mp4 \--output configs/zones/MVI_20011.yaml```Controls:6 unmodified lines- `Q` or `Esc`: quitThe generated file includes the source frame size and is compatible with`--zone-config` in the TrafficVision demo command. Create one output YAML pervideo/camera.1 unmodified line2345678910111213146 unmodified lines21222324251 unmodified line## Create polygon zonesRun the GUI from the repository root. It lists every camera sequence under`data/ua_detrac/raw/DETRAC/DETRAC-Images/DETRAC-Images`, opens the first imagein the selected sequence as its representative frame, and marks cameras withsaved zones as `--done`:```bashpython data-labelling/zone_labeler.py```Controls:6 unmodified lines- `Q` or `Esc`: quitThe generated file includes the source frame size and is compatible with`--zone-config` in the TrafficVision demo command. It creates one output YAMLper camera.
12345 unmodified lines10111213141556 unmodified lines7273747576777879808182838413 unmodified lines98991001011021031041051061071081091108 unmodified lines119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158"""Interactive polygon-zone labeler for TrafficVision video files."""import argparsefrom pathlib import Path5 unmodified linesWINDOW_NAME = "TrafficVision zone labeler"COLORS = ((0, 180, 255), (0, 230, 90), (255, 180, 0), (220, 80, 220))class ZoneLabeler:56 unmodified lines)def to_frame_point(self, x, y):return [round(x / self.display_scale), round(y / self.display_scale)]def on_click(self, event, x, y, _flags, _param):if event == cv2.EVENT_LBUTTONDOWN:self.current.append(self.to_frame_point(x, y))def save(self):config = {"camera_id": self.camera_id,"frame_size": [self.width, self.height],13 unmodified linesself.output.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8")print(f"Saved {len(self.zones)} zones to {self.output}")def run(self):cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)cv2.setMouseCallback(WINDOW_NAME, self.on_click)print("Click points; Enter=finish zone, U=undo, C=clear current, ""S=save, Q/Esc=quit.")while True:cv2.imshow(WINDOW_NAME, self.display_frame())key = cv2.waitKey(30) & 0xFF8 unmodified linesprint("A zone needs at least 3 points.")continuename = input(f"Zone name ({len(self.zones) + 1}): ").strip()if not name:print("Zone name cannot be empty.")continueif name in {zone["name"] for zone in self.zones}:print(f"Zone already exists: {name}")continueself.zones.append({"name": name, "polygon": self.current.copy()})self.current.clear()elif key == ord("s"):self.save()cv2.destroyAllWindows()def parse_args():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--source", required=True, help="Video file used for labelling")parser.add_argument("--output", required=True, help="Output zone YAML path")parser.add_argument("--camera-id", help="Camera ID; defaults to the video filename stem")return parser.parse_args()def main():args = parse_args()source = Path(args.source)capture = cv2.VideoCapture(str(source))if not capture.isOpened():raise FileNotFoundError(f"Cannot open video source: {source}")try:ok, frame = capture.read()finally:capture.release()if not ok:raise ValueError(f"Video has no readable frames: {source}")ZoneLabeler(frame, args.camera_id or source.stem, args.output).run()if __name__ == "__main__":12345 unmodified lines1011121314151617181920212256 unmodified lines798081828384858687888990919293949596979813 unmodified lines1121131141151161171181191201211221231241251261271281291301311321331341358 unmodified lines144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228"""Interactive polygon-zone labeler for UA-DETRAC camera frames."""import argparsefrom pathlib import Path5 unmodified linesWINDOW_NAME = "TrafficVision zone labeler"COLORS = ((0, 180, 255), (0, 230, 90), (255, 180, 0), (220, 80, 220))REPO_ROOT = Path(__file__).resolve().parents[1]DEFAULT_FRAME_DIR = (REPO_ROOT / "data" / "ua_detrac" / "raw" / "DETRAC" / "DETRAC-Images"/ "DETRAC-Images")DEFAULT_OUTPUT_DIR = REPO_ROOT / "configs" / "zones"IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp"}class ZoneLabeler:56 unmodified lines)def to_frame_point(self, x, y):return [min(max(round(x / self.display_scale), 0), self.width - 1),min(max(round(y / self.display_scale), 0), self.height - 1),]def on_click(self, event, x, y, _flags, _param):if event == cv2.EVENT_LBUTTONDOWN:self.current.append(self.to_frame_point(x, y))def save(self):if self.current:raise ValueError("Finish the current polygon with Enter before saving.")if not self.zones:raise ValueError("Create at least one zone before saving.")config = {"camera_id": self.camera_id,"frame_size": [self.width, self.height],13 unmodified linesself.output.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8")print(f"Saved {len(self.zones)} zones to {self.output}")def finish_zone(self, name):name = name.strip()if not name or name in {zone["name"] for zone in self.zones}:raise ValueError("Zone name must be nonempty and unique.")points = np.asarray(self.current, dtype=np.float32).reshape(-1, 2)if (len(points) < 3or len(np.unique(points, axis=0)) != len(points)or abs(cv2.contourArea(points)) < 1e-6):raise ValueError("A zone needs >=3 distinct points with nonzero area.")self.zones.append({"name": name, "polygon": self.current.copy()})self.current.clear()def run(self):cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)cv2.setMouseCallback(WINDOW_NAME, self.on_click)print("Click points; Enter=finish zone, U=undo, C=clear current, " "S=save, Q/Esc=quit.")while True:cv2.imshow(WINDOW_NAME, self.display_frame())key = cv2.waitKey(30) & 0xFF8 unmodified linesprint("A zone needs at least 3 points.")continuename = input(f"Zone name ({len(self.zones) + 1}): ").strip()try:self.finish_zone(name)except ValueError as exc:print(exc)elif key == ord("s"):try:self.save()except ValueError as exc:print(exc)cv2.destroyAllWindows()def parse_args():parser = argparse.ArgumentParser(description=__doc__)return parser.parse_args()def discover_frames(frame_dir):"""Pick the first available image from each camera sequence directory."""frame_dir = Path(frame_dir)if not frame_dir.is_dir():raise FileNotFoundError(f"Frame directory does not exist: {frame_dir}")frames = []for camera_dir in sorted(path for path in frame_dir.iterdir() if path.is_dir()):images = sorted(path for path in camera_dir.iterdir()if path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS)if images:frames.append(images[0])return framesdef has_zones(config_path):"""Return whether a saved zone config contains at least one zone."""config_path = Path(config_path)if not config_path.is_file():return Falsetry:config = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}except (OSError, yaml.YAMLError):return Falseif not isinstance(config, dict):return Falsezones = config.get("zones")return isinstance(zones, dict) and bool(zones)def choose_frame(frame_dir, output_dir):frames = discover_frames(frame_dir)if not frames:raise FileNotFoundError(f"No camera frames found in: {frame_dir}")print("Chọn camera/frame đại diện để kẻ zone:")for index, frame in enumerate(frames, 1):status = " --done" if has_zones(Path(output_dir) / f"{frame.parent.name}.yaml") else ""print(f" {index}. {frame.parent.name}{status}")while True:answer = input(f"Nhập số camera (1-{len(frames)}): ").strip()try:index = int(answer)except ValueError:print("Vui lòng nhập một số hợp lệ.")continueif 1 <= index <= len(frames):return frames[index - 1]print(f"Số camera phải nằm trong khoảng 1-{len(frames)}.")def main():parse_args()source = choose_frame(DEFAULT_FRAME_DIR, DEFAULT_OUTPUT_DIR)camera_id = source.parent.nameoutput = DEFAULT_OUTPUT_DIR / f"{camera_id}.yaml"print(f"Dùng frame đại diện: {source}")print(f"File zone sẽ lưu tại: {output}")frame = cv2.imread(str(source))if frame is None:raise ValueError(f"Cannot read image frame: {source}")ZoneLabeler(frame, camera_id, output).run()if __name__ == "__main__":
17 unmodified lines1819202122232441 unmodified lines66676869707172737417 unmodified linesannotation + CSV/JSON```Dataset không biết model. Detector không biết tracker. Tracker không biết calibration. Speed estimator chỉ nhận ID, tọa độ mét và timestamp giây. Pipeline điều phối các module này.## Interface chung41 unmodified lines## Speed và timestampHomography 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. Hồi quy tuyến tính tọa độ 2D theo timestamp trong cửa sổ giúp giảm nhiễu; độ lớn vector vận tốc nhân 3.6 ra km/h. Quỹ đạo rẽ gấp trong cửa sổ có thể bị đánh giá thấp nên cần kiểm chứng với camera thực.Gap dài, timestamp không tăng hoặc vận tốc bước nhảy vượt giới hạn làm reset history, không cắt số về một mức tốc độ trông hợp lý. `max_gap_seconds`, `max_reasonable_kmh` và window chỉ là kiểm soát đầu vào, không chứng minh một track không có ID switch.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.17 unmodified lines1819202122232441 unmodified lines66676869707172737417 unmodified linesannotation + CSV/JSON```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.## Interface chung41 unmodified lines## Speed và timestampHomography 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.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.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.
63 unmodified lines64656667686970717263 unmodified lines## 3. Train, evaluate, demo```python!python scripts/utils.py train --config outputs/colab.yaml!python scripts/utils.py evaluate --model faster_rcnn --checkpoint outputs/faster_rcnn/best.pt --config outputs/colab.yaml --device cuda --split test --output outputs/evaluation/detection.json!python scripts/utils.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```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.63 unmodified lines64656667686970717263 unmodified lines## 3. Train, evaluate, demo```python!python scripts/run_trafficvision.py train --config outputs/colab.yaml!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!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```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.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465# Review và sửa chữa sau cập nhật của leader
Ngày: 2026-11-06. Base: `main` tại commit `db13bd6`.Branch: `fix/kalman-speed-and-review-tools`.
## Phạm vi review
Đã đọ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.
## Những vấn đề đã sửa
| Vấn đề | Thay đổi | Tác dụng ||---|---|---|| 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 || 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 || 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 || 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 || 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 || 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ẽ || 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 || 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 || 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ũ |
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.
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ố.
## Kiểm chứng
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.
- Trước sửa: **35 passed, 1 failed**; lỗi là test LR hard-code. Ruff báo 9 lỗi.- 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.- `ruff check src scripts tests data-labelling --no-cache`: đạt.- `ruff format --check --no-cache src scripts tests data-labelling`: 87 file đạt.- `git diff --check`: đạt.- `python scripts/run_trafficvision.py --help`: chạy được.- Labeler được kiểm tra logic và YAML headless; chưa kiểm tra thao tác cửa sổ desktop trên WSL.
### Đo riêng Jacobian
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:
| Cách tính | Thời gian ||---|---|| Sai phân cũ, bốn phép chiếu | 0.3246 giây || Jacobian giải tích | 0.0869 giây |
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.
### Chạy lại video giao thông thật
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.
- Xử lý và decode lại đủ **538/538 frame**.- CSV và JSON đều có **1455 observation**, **17 tracking IDs**.- 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ũ.- Không có calibration nên speed là `N/A`/null trong toàn bộ export.- Artifacts local: `outputs/review/real_video.mp4`, `.csv`, `.json`, `.summary.json`, `validation.json`, `preview_400.jpg`; được gitignore.
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.
## Phần nhóm cần kiểm chứng tiếp
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.9 unmodified lines101112131415161746 unmodified lines64656667686970719 unmodified linesimport cv2import yamlsys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))from trafficvision.geometry.homography import Homographydef main():46 unmodified linescalibration=dict(image_points=points, world_points=world, reprojection_error_m=homography.reprojection_error_m),speed=dict(sigma_px=1.0, accel_std=2.0, gate_chi2=16.0, min_observations=8,max_speed_std_kmh=4.0, max_gap_seconds=0.5, max_reasonable_kmh=160),)output = Path(args.output)output.parent.mkdir(parents=True, exist_ok=True)9 unmodified lines10111213141516171846 unmodified lines6566676869707172737475767778799 unmodified linesimport cv2import yamlsys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))from trafficvision.geometry.homography import Homography # noqa: E402def main():46 unmodified linescalibration=dict(image_points=points, world_points=world, reprojection_error_m=homography.reprojection_error_m),speed=dict(sigma_px=1.0,accel_std=2.0,gate_chi2=16.0,min_observations=8,max_speed_std_kmh=4.0,max_gap_seconds=0.5,max_reasonable_kmh=160,),)output = Path(args.output)output.parent.mkdir(parents=True, exist_ok=True)
7 unmodified lines8910111213147 unmodified linesSRC_DIR = REPO_ROOT / "src"sys.path.insert(0, str(SRC_DIR))from trafficvision.cli import main # noqa: E402if __name__ == "__main__":7 unmodified lines8910111213147 unmodified linesSRC_DIR = REPO_ROOT / "src"sys.path.insert(0, str(SRC_DIR))from trafficvision.cli import mainif __name__ == "__main__":
137 unmodified lines138139140141142137 unmodified linesspeed_metrics([float(r["gt_kmh"]) for r in rows], [float(r["predicted_kmh"]) for r in rows]),args.output,)if __name__ == "__main__":main()137 unmodified lines138139140141142143144137 unmodified linesspeed_metrics([float(r["gt_kmh"]) for r in rows], [float(r["predicted_kmh"]) for r in rows]),args.output,)if __name__ == "__main__":main()
36 unmodified lines3738394041424343 unmodified lines8788899091929336 unmodified linesraise ValueError("Predictions contain frames absent from ground truth")gt_maps, pred_maps = {}, {}gt_ids, tracker_ids, similarities = [], [], []for frame_id in tqdm(range(1, max(ground_truth) + 1), desc="Aligning sequence", unit="frame", leave=False):row = ground_truth.get(frame_id, dict(boxes=[], labels=[], track_ids=[], ignored_regions=[]))records = predictions.get(frame_id, [])boxes = np.array([r["box"] for r in records], dtype=float).reshape(-1, 4)43 unmodified linesif row["split"] == split:gt[row["video_id"]].append(row)with open(prediction_csv) as handle:predictions = tqdm(csv.DictReader(handle), desc="Loading tracking predictions", unit="record", leave=False)for row in predictions:if row["video_id"] not in gt:raise ValueError(f"Prediction video outside {split} split: {row['video_id']}")36 unmodified lines37383940414243444543 unmodified lines89909192939495969736 unmodified linesraise ValueError("Predictions contain frames absent from ground truth")gt_maps, pred_maps = {}, {}gt_ids, tracker_ids, similarities = [], [], []for frame_id in tqdm(range(1, max(ground_truth) + 1), desc="Aligning sequence", unit="frame", leave=False):row = ground_truth.get(frame_id, dict(boxes=[], labels=[], track_ids=[], ignored_regions=[]))records = predictions.get(frame_id, [])boxes = np.array([r["box"] for r in records], dtype=float).reshape(-1, 4)43 unmodified linesif row["split"] == split:gt[row["video_id"]].append(row)with open(prediction_csv) as handle:predictions = tqdm(csv.DictReader(handle), desc="Loading tracking predictions", unit="record", leave=False)for row in predictions:if row["video_id"] not in gt:raise ValueError(f"Prediction video outside {split} split: {row['video_id']}")
43 unmodified lines44454643 unmodified linesif np.any(abs(homogeneous[..., 2]) < 1e-8):raise ValueError("Point lies on the homography horizon")return homogeneous[..., :2] / homogeneous[..., 2:]43 unmodified lines44454647484950515253545556575859606143 unmodified linesif np.any(abs(homogeneous[..., 2]) < 1e-8):raise ValueError("Point lies on the homography horizon")return homogeneous[..., :2] / homogeneous[..., 2:]def jacobian(self, point):"""Analytic derivative of the perspective division at one image point."""point = np.asarray(point, dtype=float)if point.shape != (2,) or not np.isfinite(point).all():raise ValueError("Jacobian needs one finite 2D point")homogeneous = self.matrix @ np.r_[point, 1.0]denominator = homogeneous[2]if abs(denominator) < 1e-8:raise ValueError("Point lies on the homography horizon")world = homogeneous[:2] / denominatorresult = (self.matrix[:2, :2] - world[:, None] * self.matrix[2, :2]) / denominatorif not np.isfinite(result).all():raise ValueError("Non-finite homography Jacobian")return result
12345from ..geometry.coordinates import bottom_centerfrom ..speed.estimator import SpeedEstimatorfrom ..speed.kalman_speed import KalmanSpeedEstimator, pixel_jacobianfrom ..zones.zone_manager import ZoneManager1234from ..geometry.coordinates import bottom_centerfrom ..speed.kalman_speed import KalmanSpeedEstimator, pixel_jacobianfrom ..zones.zone_manager import ZoneManager
55 unmodified lines56575859606162636465663 unmodified lines7071727374757655 unmodified linesok, frame = cap.read()if not ok:breaktimestamp = cap.get(cv2.CAP_PROP_POS_MSEC) / 1000 if timestamp_mode == "pts" else frame_id / fpsif not math.isfinite(timestamp) or (previous_timestamp is not None and timestamp <= previous_timestamp):raise ValueError("Non-monotonic/missing PTS; use --timestamp-mode fps for constant-FPS video")previous_timestamp = timestampframe_id += 1rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)3 unmodified lineswriter.write(annotate(frame, results, pipeline.zones, processing_fps))exporter.write(video_id or Path(str(source)).stem, frame_id, timestamp, results)progress.update(1)progress.set_postfix(fps=f"{processing_fps:.1f}")if frame_id == 0:raise ValueError("Source has no readable video frames")summary = dict(55 unmodified lines5657585960616263646566676869703 unmodified lines7475767778798055 unmodified linesok, frame = cap.read()if not ok:breaktimestamp = (cap.get(cv2.CAP_PROP_POS_MSEC) / 1000 if timestamp_mode == "pts" else frame_id / fps)if not math.isfinite(timestamp) or (previous_timestamp is not None and timestamp <= previous_timestamp):raise ValueError("Non-monotonic/missing PTS; use --timestamp-mode fps for constant-FPS video")previous_timestamp = timestampframe_id += 1rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)3 unmodified lineswriter.write(annotate(frame, results, pipeline.zones, processing_fps))exporter.write(video_id or Path(str(source)).stem, frame_id, timestamp, results)progress.update(1)progress.set_postfix(fps=f"{processing_fps:.1f}", refresh=False)if frame_id == 0:raise ValueError("Source has no readable video frames")summary = dict(
3 unmodified lines456789101112131415163 unmodified lines20212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768693 unmodified linesfar-away (noisy) observations are automatically down-weighted. Gating is done on theMahalanobis distance of the innovation, not on instantaneous speed."""import mathimport numpy as npclass KalmanSpeedEstimator:def __init__(self, sigma_px=1.0, accel_std=2.0, gate_chi2=16.0, min_observations=8,max_speed_std_kmh=4.0, max_gap_seconds=0.5, max_reasonable_kmh=160, max_rejects=3):self.sigma_px, self.q = sigma_px, accel_stdself.gate, self.min_obs, self.max_std = gate_chi2, min_observations, max_speed_std_kmh / 3.6self.max_gap, self.vmax, self.max_rejects = max_gap_seconds, max_reasonable_kmh / 3.6, max_rejects3 unmodified linesself.state.clear() if track_id is None else self.state.pop(track_id, None)def prune(self, timestamp):for k in [k for k, s in self.state.items() if timestamp - s["t"] > self.max_gap]:self.state.pop(k)def _init(self, z, R, t):x = np.array([z[0], z[1], 0.0, 0.0])P = np.zeros((4, 4)); P[:2, :2] = R; P[2:, 2:] = np.eye(2) * (self.vmax / 2) ** 2return dict(x=x, P=P, t=t, n=1, rejects=0)def update(self, track_id, world, timestamp, jacobian=None):z = np.asarray(world, float)if z.shape != (2,) or not np.isfinite(z).all() or not math.isfinite(timestamp):self.reset(track_id); return NoneJ = np.eye(2) if jacobian is None else np.asarray(jacobian, float)R = (self.sigma_px ** 2) * J @ J.Ts = self.state.get(track_id)if s is None or not (0 < timestamp - s["t"] <= self.max_gap):self.state[track_id] = self._init(z, R, timestamp); return Nonedt = timestamp - s["t"]F = np.eye(4); F[0, 2] = F[1, 3] = dtG = np.array([[dt**2 / 2, 0], [0, dt**2 / 2], [dt, 0], [0, dt]])Q = (self.q ** 2) * G @ G.Tx, P = F @ s["x"], F @ s["P"] @ F.T + QHm = np.eye(2, 4); S = Hm @ P @ Hm.T + Rinnov = z - Hm @ xif innov @ np.linalg.solve(S, innov) > self.gate: # outlier / ID jumps.update(x=x, P=P, t=timestamp, rejects=s["rejects"] + 1)if s["rejects"] >= self.max_rejects:self.state[track_id] = self._init(z, R, timestamp)return NoneK = P @ Hm.T @ np.linalg.inv(S)x = x + K @ innov; P = (np.eye(4) - K @ Hm) @ Ps.update(x=x, P=P, t=timestamp, n=s["n"] + 1, rejects=0)v = x[2:]; speed = float(np.linalg.norm(v))vstd = math.sqrt(max(P[2, 2], P[3, 3]))if s["n"] < self.min_obs or vstd > self.max_std or speed > self.vmax:return Nonereturn speed * 3.6def pixel_jacobian(homography, point, eps=0.5):"""2x2 Jacobian d(world_xy)/d(pixel_uv) at `point`, via central differences (metres per pixel)."""p = np.asarray(point, float)du = (homography.project(p + [eps, 0]) - homography.project(p - [eps, 0])) / (2 * eps)dv = (homography.project(p + [0, eps]) - homography.project(p - [0, eps])) / (2 * eps)return np.stack([du, dv], axis=1)3 unmodified lines456789101112131415161718192021222324252627282930313233343536373 unmodified lines41424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021033 unmodified linesfar-away (noisy) observations are automatically down-weighted. Gating is done on theMahalanobis distance of the innovation, not on instantaneous speed."""import mathimport numpy as npclass KalmanSpeedEstimator:def __init__(self,sigma_px=1.0,accel_std=2.0,gate_chi2=16.0,min_observations=8,max_speed_std_kmh=4.0,max_gap_seconds=0.5,max_reasonable_kmh=160,max_rejects=3,):positive = (sigma_px, gate_chi2, max_speed_std_kmh, max_gap_seconds, max_reasonable_kmh)if not all(math.isfinite(value) and value > 0 for value in positive):raise ValueError("Noise, gate, uncertainty, gap and speed limits must be finite and positive")if not math.isfinite(accel_std) or accel_std < 0:raise ValueError("accel_std must be finite and nonnegative")for name, value, minimum in (("min_observations", min_observations, 2),("max_rejects", max_rejects, 1),):if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or value < minimum:raise ValueError(f"{name} must be an integer >= {minimum}")self.sigma_px, self.q = sigma_px, accel_stdself.gate, self.min_obs, self.max_std = gate_chi2, min_observations, max_speed_std_kmh / 3.6self.max_gap, self.vmax, self.max_rejects = max_gap_seconds, max_reasonable_kmh / 3.6, max_rejects3 unmodified linesself.state.clear() if track_id is None else self.state.pop(track_id, None)def prune(self, timestamp):for k in [k for k, s in self.state.items() if timestamp - s["observed_t"] > self.max_gap]:self.state.pop(k)def _init(self, z, R, t):x = np.array([z[0], z[1], 0.0, 0.0])P = np.zeros((4, 4))P[:2, :2] = RP[2:, 2:] = np.eye(2) * (self.vmax / 2) ** 2return dict(x=x, P=P, t=t, observed_t=t, n=1, rejects=0)def update(self, track_id, world, timestamp, jacobian=None):z = np.asarray(world, float)if z.shape != (2,) or not np.isfinite(z).all() or not math.isfinite(timestamp):self.reset(track_id)return NoneJ = np.eye(2) if jacobian is None else np.asarray(jacobian, float)if J.shape != (2, 2) or not np.isfinite(J).all() or np.linalg.matrix_rank(J) < 2:self.reset(track_id)raise ValueError("Jacobian must be a finite, nonsingular 2x2 matrix")R = (self.sigma_px**2) * J @ J.Ts = self.state.get(track_id)if (s is Noneor not (0 < timestamp - s["t"] <= self.max_gap)or timestamp - s["observed_t"] > self.max_gap):self.state[track_id] = self._init(z, R, timestamp)return Nonedt = timestamp - s["t"]F = np.eye(4)F[0, 2] = F[1, 3] = dtG = np.array([[dt**2 / 2, 0], [0, dt**2 / 2], [dt, 0], [0, dt]])Q = (self.q**2) * G @ G.Tx, P = F @ s["x"], F @ s["P"] @ F.T + QHm = np.eye(2, 4)S = Hm @ P @ Hm.T + Rinnov = z - Hm @ xif innov @ np.linalg.solve(S, innov) > self.gate: # outlier / ID jumps.update(x=x, P=P, t=timestamp, rejects=s["rejects"] + 1)if s["rejects"] >= self.max_rejects:self.state[track_id] = self._init(z, R, timestamp)return NoneK = np.linalg.solve(S, Hm @ P).Tx = x + K @ innovresidual = np.eye(4) - K @ Hm# Joseph form preserves positive semidefiniteness under rounding.P = residual @ P @ residual.T + K @ R @ K.TP = (P + P.T) / 2s.update(x=x, P=P, t=timestamp, observed_t=timestamp, n=s["n"] + 1, rejects=0)speed = float(np.linalg.norm(x[2:]))# Correlated axes can have larger uncertainty than either diagonal alone.vstd = math.sqrt(max(float(np.linalg.eigvalsh(P[2:, 2:])[-1]), 0.0))if s["n"] < self.min_obs or vstd > self.max_std or speed > self.vmax:return Nonereturn speed * 3.6def pixel_jacobian(homography, point):"""Exact 2x2 d(world_xy)/d(pixel_uv), in metres per pixel."""return homography.jacobian(point)
149 unmodified lines150151152153154155156149 unmodified linescurrent = metrics["map"]improved = current > bestbest = max(current, best)record = dict(epoch=epoch, loss=losses / steps, lr=optimizer.param_groups[0]["lr"], metrics=metrics)epoch_progress.set_postfix(loss=f"{record['loss']:.4f}", val_map=f"{current:.4f}")with (output / "metrics.jsonl").open("a") as handle:handle.write(json.dumps(record) + "\n")149 unmodified lines150151152153154155156157158149 unmodified linescurrent = metrics["map"]improved = current > bestbest = max(current, best)record = dict(epoch=epoch, loss=losses / steps, lr=optimizer.param_groups[0]["lr"], metrics=metrics)epoch_progress.set_postfix(loss=f"{record['loss']:.4f}", val_map=f"{current:.4f}")with (output / "metrics.jsonl").open("a") as handle:handle.write(json.dumps(record) + "\n")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import numpy as npimport pytestfrom trafficvision.geometry.homography import Homographyfrom trafficvision.speed.kalman_speed import KalmanSpeedEstimator, pixel_jacobian
@pytest.mark.parametrize( "params", [ dict(sigma_px=0), dict(sigma_px=float("nan")), dict(accel_std=-1), dict(gate_chi2=0), dict(max_gap_seconds=0), dict(min_observations=1), dict(max_rejects=0), dict(max_speed_std_kmh=float("inf")), dict(max_reasonable_kmh=-1), dict(min_observations=2.5), ],)def test_invalid_config_fails_early(params): with pytest.raises(ValueError): KalmanSpeedEstimator(**params)
@pytest.mark.parametrize("jacobian", [np.zeros((2, 2)), np.ones((3, 2)), [[1, 0], [0, float("nan")]]])def test_bad_jacobian_resets_track(jacobian): estimator = KalmanSpeedEstimator() estimator.update(1, [0, 0], 0) with pytest.raises(ValueError, match="Jacobian"): estimator.update(1, [1, 0], 0.04, jacobian) assert 1 not in estimator.state
def test_perspective_jacobian_matches_small_step_difference(): h = Homography([[0.3, 0.1, 2], [0.05, 0.5, 4], [0.001, 0.002, 1]]) point = np.array([200.0, 100.0]) epsilon = 1e-4 expected = np.column_stack( [ (h.project(point + axis * epsilon) - h.project(point - axis * epsilon)) / (2 * epsilon) for axis in np.eye(2) ] ) np.testing.assert_allclose(pixel_jacobian(h, point), expected, rtol=1e-7, atol=1e-8) with pytest.raises(ValueError, match="horizon"): Homography([[1, 0, 0], [0, 1, 0], [1, 0, 1]]).jacobian([-1, 0])
def test_covariance_remains_symmetric_psd_with_correlated_noise(): estimator = KalmanSpeedEstimator(sigma_px=0.2) J = np.array([[0.1, 0.04], [0.04, 0.2]]) for i in range(150): estimator.update(1, [i * 0.08, i * 0.16], i * 0.04, J) covariance = estimator.state[1]["P"] np.testing.assert_allclose(covariance, covariance.T, atol=1e-12) assert np.linalg.eigvalsh(covariance).min() >= -1e-12
def test_rejected_observations_do_not_keep_old_track_alive(): estimator = KalmanSpeedEstimator(max_rejects=100, max_gap_seconds=0.15) for i in range(30): estimator.update(1, [i * 0.4, 0], i * 0.04) for i in range(30, 33): assert estimator.update(1, [1000, 0], i * 0.04) is None estimator.prune(1.32) assert 1 not in estimator.state
def test_gap_and_duplicate_timestamp_restart_warmup(): estimator = KalmanSpeedEstimator(sigma_px=0.1) for i in range(30): estimator.update(1, [i * 0.4, 0], i * 0.04) assert estimator.update(1, [11.6, 0], 1.16) is None assert estimator.state[1]["n"] == 1 assert estimator.update(1, [30, 0], 3) is None assert estimator.state[1]["n"] == 117 unmodified lines1819202122232425262717 unmodified linesresult = speed_metrics([0, 10], [1, 12])assert result["mae"] == 1.5 and result["mape"] == 20def test_kalman_constant_speed_and_jump_rejection():from trafficvision.speed.kalman_speed import KalmanSpeedEstimatorest = KalmanSpeedEstimator(sigma_px=0.1)out = [est.update(1, [0.0, 10.0 * i / 25], i / 25) for i in range(30)] # 10 m/sassert out[2] is None # chưa đủ quan sátassert out[-1] == pytest.approx(36, abs=0.5)assert est.update(1, [0.0, 500.0], 30 / 25) is None # nhảy ID bị loại17 unmodified lines18192021222324252627282917 unmodified linesresult = speed_metrics([0, 10], [1, 12])assert result["mae"] == 1.5 and result["mape"] == 20def test_kalman_constant_speed_and_jump_rejection():from trafficvision.speed.kalman_speed import KalmanSpeedEstimatorest = KalmanSpeedEstimator(sigma_px=0.1)out = [est.update(1, [0.0, 10.0 * i / 25], i / 25) for i in range(30)] # 10 m/sassert out[2] is None # chưa đủ quan sátassert out[-1] == pytest.approx(36, abs=0.5)assert est.update(1, [0.0, 500.0], 30 / 25) is None # nhảy ID bị loại
37 unmodified lines3839404137 unmodified linesdef test_config_inheritance():config = load_config("configs/experiments/faster_rcnn_scratch.yaml")assert config["model"]["name"] == "faster_rcnn" and config["training"]["lr"] == 0.000137 unmodified lines38394041424337 unmodified linesdef test_config_inheritance():config = load_config("configs/experiments/faster_rcnn_scratch.yaml")base = load_config("configs/experiments/base.yaml")assert config["model"]["name"] == "faster_rcnn"assert config["training"]["lr"] == base["training"]["lr"]
12345678910111213141516171819202122232425262728293031323334353637383940import importlib.utilfrom pathlib import Pathimport numpy as npimport pytestimport yamlfrom trafficvision.zones.zone_manager import ZoneManager
spec = importlib.util.spec_from_file_location( "zone_labeler", Path(__file__).parents[1] / "data-labelling/zone_labeler.py")module = importlib.util.module_from_spec(spec)spec.loader.exec_module(module)
def test_labeler_rejects_invalid_polygons_and_incomplete_save(tmp_path): labeler = module.ZoneLabeler(np.zeros((540, 960, 3), np.uint8), "test", tmp_path / "zones.yaml") with pytest.raises(ValueError, match="at least one"): labeler.save() labeler.current = [[1, 1], [2, 2], [3, 3]] with pytest.raises(ValueError, match="nonzero area"): labeler.finish_zone("road") with pytest.raises(ValueError, match="Finish"): labeler.save() labeler.current = [[0, 0], [100, 0], [100, 100]] labeler.finish_zone("road") labeler.save() config = yaml.safe_load(labeler.output.read_text()) manager = ZoneManager(config) manager.validate_frame(960, 540) assert manager.zones[0].contains([50, 25]) labeler.current = [[0, 0], [10, 0], [10, 10]] with pytest.raises(ValueError, match="unique"): labeler.finish_zone("road")
def test_display_coordinates_scale_and_clip(tmp_path): labeler = module.ZoneLabeler(np.zeros((2160, 3840, 3), np.uint8), "test", tmp_path / "zones.yaml") labeler.display_frame() assert labeler.to_frame_point(700, 350) == [1920, 960] assert labeler.to_frame_point(-10, 5000) == [0, 2159]README.md+24-14
configs/zones/MVI_40191.yamlAdded+61
configs/zones/MVI_40244.yamlAdded+59
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.mdAdded+65
scripts/calibrate_camera.py+11-3
scripts/run_trafficvision.py+1-1
src/trafficvision/cli.py+2
src/trafficvision/evaluation/tracking_metrics.py+6-2
src/trafficvision/geometry/homography.py+15
src/trafficvision/pipeline/detection_tracking.py-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.pyAdded+78
tests/test_speed_estimator.py+4-2
tests/test_training.py+3-1
tests/test_zone_labeler.pyAdded+40