detector.hpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // 检测器接口 + Mock 实现。
  2. //
  3. // 真机上 Box 来自 TensorRT/ONNXRuntime/RKNN 后端(见 docs/technical_route.md §5);
  4. // 这个骨架里用 MockDetector 走"脚本化的检测结果",目的是**在没有模型、没有相机的情况下
  5. // 也能把 判决 → 时序滤波 → Modbus/TCP → PLC 整条链路联调通**(现场先对寄存器再上模型)。
  6. #pragma once
  7. #include <cstddef>
  8. #include <string>
  9. #include <utility>
  10. #include <vector>
  11. #include "portcv/edge_image.hpp"
  12. #include "portcv/schema.hpp"
  13. namespace portcv {
  14. /// 一帧图像:骨架里只保留算法需要的元信息;真机上换成 GPU 缓冲 / cv::Mat。
  15. struct Frame {
  16. int width = 1920;
  17. int height = 1080;
  18. long index = 0;
  19. double ts = 0.0;
  20. bool valid = true; ///< false 表示取帧失败(相机掉线/超时)
  21. /// 可选的整帧灰度图:**只有** `edge` 后端(2D 边缘几何证据)需要;
  22. /// 真机上由取流线程填(硬件解码 → 灰度转换),其它后端留 nullptr。
  23. /// 加这一个可选字段,就能在不改动既有 Detector 契约的前提下接入证据后端(§10)。
  24. const GrayImage* gray = nullptr;
  25. };
  26. /// 检测器接口。
  27. class Detector {
  28. public:
  29. virtual ~Detector() = default;
  30. /// 后端名(日志用)。
  31. virtual std::string name() const = 0;
  32. /// 单帧推理,返回像素坐标框。
  33. virtual std::vector<Box> infer(const Frame& frame) = 0;
  34. /// 加载/预热(真机后端在这里建 engine、跑一次空推理);失败返回 false。
  35. virtual bool warmup(std::string* error = nullptr) {
  36. if (error) { error->clear(); }
  37. return true;
  38. }
  39. };
  40. /// 脚本化 mock:每帧取脚本里的下一组框,用完后停在最后一组(模拟"车停稳了")。
  41. class MockDetector : public Detector {
  42. public:
  43. explicit MockDetector(std::vector<std::vector<Box>> script) : script_(std::move(script)) {}
  44. std::string name() const override { return "mock"; }
  45. std::vector<Box> infer(const Frame& frame) override {
  46. (void)frame;
  47. if (script_.empty()) { return {}; }
  48. const std::size_t index = index_ < script_.size() ? index_ : script_.size() - 1;
  49. const std::vector<Box> out = script_[index];
  50. if (index_ + 1 < script_.size()) { ++index_; }
  51. return out;
  52. }
  53. void reset() { index_ = 0; }
  54. private:
  55. std::vector<std::vector<Box>> script_;
  56. std::size_t index_ = 0;
  57. };
  58. /// 造框小工具(脚本/自检用)。
  59. inline Box make_box(const char* class_name, float x1, float y1, float x2, float y2, float score,
  60. int class_id = 0) {
  61. return Box(x1, y1, x2, y2, score, class_id, class_name);
  62. }
  63. } // namespace portcv