calib_record.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. """P0-5 标定记录生成/校验(现场用)。
  2. 生成(自动写入 sha256)::
  3. python scripts/calib_record.py create --site CT01 --camera front \\
  4. --reviewer "张工" --px-per-m 115.6 --box-height 2.591 \\
  5. --out configs/calib/ct01-front.json
  6. 校验(过期/哈希/复核/漂移;退出码 1 = CALIB_STALE)::
  7. python scripts/calib_record.py check configs/calib/ct01-front.json \\
  8. --max-age-days 180 --px-per-m 115.6 --box-height 2.591
  9. 说明:
  10. * 两份实现(Python `portcv/calibration.py` 与 C++ `cpp/src/calibration.cpp`)用**同一个**
  11. canonical JSON + sha256 口径;本脚本生成的记录 C++ 运行期同样能校验通过
  12. (跨语言契约由 `cpp/tests/selftest_calib.cpp` 与 `tests/test_calibration.py` 双向锁定)。
  13. * 放在 `scripts/` 而不是 `build/`:`build/` 在 `.gitignore` 里,交付版本拿不到脚本
  14. 就等于"记录无法生成/无法校验"。
  15. """
  16. from __future__ import annotations
  17. import argparse
  18. import json
  19. import os
  20. import sys
  21. from datetime import datetime, timezone
  22. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  23. if ROOT not in sys.path:
  24. sys.path.insert(0, ROOT)
  25. from portcv.calibration import evaluate, seal # noqa: E402
  26. from portcv.config import Config # noqa: E402
  27. def _force_utf8() -> None:
  28. """Windows 默认 GBK 控制台打印中文/符号会崩(UnicodeEncodeError),统一切 UTF-8。"""
  29. for stream in (sys.stdout, sys.stderr):
  30. try:
  31. stream.reconfigure(encoding="utf-8", errors="replace")
  32. except Exception: # pragma: no cover - 老 Python / 被重定向的流
  33. pass
  34. def cmd_create(args: argparse.Namespace) -> int:
  35. record = {
  36. "schema": "portcv.calib/1",
  37. "site": args.site,
  38. "camera_id": args.camera,
  39. "calibrated_at": args.date or datetime.now(timezone.utc).isoformat(timespec="seconds"),
  40. "reviewer": args.reviewer,
  41. "method": args.method,
  42. "px_per_m": float(args.px_per_m),
  43. "box_height_m": float(args.box_height),
  44. "intrinsics": {},
  45. "extrinsics": {},
  46. "roi": [],
  47. }
  48. record = seal(record)
  49. os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True)
  50. with open(args.out, "w", encoding="utf-8") as fh:
  51. json.dump(record, fh, ensure_ascii=False, indent=2)
  52. fh.write("\n")
  53. print(json.dumps({"written": args.out, "sha256": record["sha256"]}, ensure_ascii=False, indent=2))
  54. return 0
  55. def cmd_check(args: argparse.Namespace) -> int:
  56. cfg = Config(
  57. {
  58. "calibration": {
  59. "record": args.record,
  60. "max_age_days": args.max_age_days,
  61. },
  62. "evidence_v2": {
  63. "px_per_m": args.px_per_m or 0.0,
  64. "box_height_m": args.box_height or 0.0,
  65. },
  66. }
  67. )
  68. status = evaluate(cfg)
  69. print(json.dumps(status.to_dict(), ensure_ascii=False, indent=2))
  70. return 0 if not status.stale else 1
  71. def main(argv=None) -> int:
  72. _force_utf8()
  73. parser = argparse.ArgumentParser(description="P0-5 标定记录")
  74. sub = parser.add_subparsers(dest="cmd", required=True)
  75. create = sub.add_parser("create", help="生成并封存记录")
  76. create.add_argument("--site", required=True)
  77. create.add_argument("--camera", required=True)
  78. create.add_argument("--reviewer", required=True)
  79. create.add_argument("--method", default="")
  80. create.add_argument("--px-per-m", type=float, default=0.0)
  81. create.add_argument("--box-height", type=float, default=2.591)
  82. create.add_argument("--date", default="", help="ISO-8601;默认当前时间")
  83. create.add_argument("--out", required=True)
  84. create.set_defaults(func=cmd_create)
  85. check = sub.add_parser("check", help="校验记录(只读)")
  86. check.add_argument("record")
  87. check.add_argument("--max-age-days", type=float, default=180.0)
  88. check.add_argument("--px-per-m", type=float, default=0.0)
  89. check.add_argument("--box-height", type=float, default=0.0)
  90. check.set_defaults(func=cmd_check)
  91. args = parser.parse_args(argv)
  92. return int(args.func(args))
  93. if __name__ == "__main__":
  94. sys.exit(main())