scene.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. #include "portcv/scene.hpp"
  2. #include <cctype>
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <map>
  6. namespace portcv {
  7. namespace {
  8. constexpr int kUnknown = static_cast<int>(SceneState::UNKNOWN);
  9. std::string fmt(const char* pattern, double a) {
  10. char buf[128];
  11. std::snprintf(buf, sizeof(buf), pattern, a);
  12. return std::string(buf);
  13. }
  14. } // namespace
  15. SceneClassifier::SceneClassifier(const SceneParams& params) : p_(params) {
  16. auto norm_list = [](const std::vector<std::string>& in) {
  17. std::vector<std::string> out;
  18. for (const std::string& name : in) {
  19. const std::string n = SceneClassifier::normalize(name);
  20. if (!n.empty()) { out.push_back(n); }
  21. }
  22. return out;
  23. };
  24. container_ = norm_list(p_.container_names);
  25. bed_ = norm_list(p_.bed_names);
  26. flatbed_ = norm_list(p_.flatbed_names);
  27. ignore_ = norm_list(p_.ignore_names);
  28. std::map<std::string, int> direct;
  29. for (const auto& kv : p_.direct_map) { direct[normalize(kv.first)] = kv.second; }
  30. // 与 Python 一致:三个标准标签始终可用
  31. if (direct.find("not_on_train") == direct.end()) { direct["not_on_train"] = 0; }
  32. if (direct.find("bed") == direct.end()) { direct["bed"] = 1; }
  33. if (direct.find("flatbed") == direct.end()) { direct["flatbed"] = 2; }
  34. p_.direct_map = direct;
  35. }
  36. std::string SceneClassifier::normalize(const std::string& name) {
  37. std::string out;
  38. out.reserve(name.size());
  39. for (char ch : name) {
  40. if (ch == '-' || ch == ' ') {
  41. out.push_back('_');
  42. } else {
  43. out.push_back(static_cast<char>(std::tolower(static_cast<unsigned char>(ch))));
  44. }
  45. }
  46. // 去首尾空白(简单实现,覆盖 config 手写场景)
  47. std::size_t begin = out.find_first_not_of(" \t\r\n");
  48. if (begin == std::string::npos) { return std::string(); }
  49. std::size_t end = out.find_last_not_of(" \t\r\n");
  50. return out.substr(begin, end - begin + 1);
  51. }
  52. std::string SceneClassifier::group_of(const std::string& class_name) const {
  53. const std::string name = normalize(class_name);
  54. auto has = [&name](const std::vector<std::string>& list) {
  55. return std::find(list.begin(), list.end(), name) != list.end();
  56. };
  57. if (has(container_)) { return "container"; }
  58. if (has(bed_)) { return "bed"; }
  59. if (has(flatbed_)) { return "flatbed"; }
  60. if (has(ignore_)) { return "ignore"; }
  61. return "unknown";
  62. }
  63. std::vector<Point> SceneClassifier::roi_polygon(int width, int height) const {
  64. return normalized_to_pixel_polygon(p_.roi, width, height);
  65. }
  66. Observation SceneClassifier::classify(const std::vector<Box>& detections, int width, int height,
  67. double ts, long frame_id) const {
  68. std::vector<Box> boxes;
  69. boxes.reserve(detections.size());
  70. for (const Box& box : detections) {
  71. if (static_cast<double>(box.score) >= p_.min_class_conf) { boxes.push_back(box); }
  72. }
  73. if (p_.mode == "direct") { return classify_direct(boxes, width, height, ts, frame_id); }
  74. return classify_composed(boxes, width, height, ts, frame_id);
  75. }
  76. double SceneClassifier::overlap_x1d(double a1, double a2, double b1, double b2) {
  77. const double inter = (a2 < b2 ? a2 : b2) - (a1 > b1 ? a1 : b1);
  78. if (inter <= 0.0) { return 0.0; }
  79. const double shorter = (a2 - a1) < (b2 - b1) ? (a2 - a1) : (b2 - b1);
  80. return shorter > 0.0 ? inter / shorter : 0.0;
  81. }
  82. bool SceneClassifier::support_quality(const Box& container, const Box& wagon, double* ov_x,
  83. double* quality) const {
  84. if (container.height() <= 0.0f) { return false; }
  85. if (static_cast<double>(wagon.score) < p_.support_score_ratio * container.score) { return false; }
  86. // 车厢顶边不应明显高于集装箱顶边(否则多半是别的车厢/背景)
  87. if (static_cast<double>(wagon.top()) <
  88. static_cast<double>(container.top()) - 0.05 * container.height()) {
  89. return false;
  90. }
  91. const double ov = overlap_x1d(container.x1, container.x2, wagon.x1, wagon.x2);
  92. if (ov < p_.support_overlap) { return false; }
  93. const double dy_ratio =
  94. std::fabs(static_cast<double>(wagon.top()) - container.bottom()) / container.height();
  95. if (dy_ratio > p_.support_dy_ratio) { return false; }
  96. const double tol = p_.support_dy_ratio > 1e-6 ? p_.support_dy_ratio : 1e-6;
  97. *ov_x = ov;
  98. *quality = ov * std::fmax(0.2, 1.0 - 0.5 * (dy_ratio / tol));
  99. return true;
  100. }
  101. bool SceneClassifier::best_support(const Box& container,
  102. const std::vector<std::pair<Box, double>>& wagons,
  103. Box* wagon_out, double* score_out, double* ovx_out) const {
  104. bool found = false;
  105. double best_score = 0.0;
  106. for (const auto& item : wagons) {
  107. double ov_x = 0.0;
  108. double quality = 0.0;
  109. if (!support_quality(container, item.first, &ov_x, &quality)) { continue; }
  110. const double score = static_cast<double>(item.first.score) * quality;
  111. if (!found || score > best_score) {
  112. found = true;
  113. best_score = score;
  114. *wagon_out = item.first;
  115. *score_out = score;
  116. *ovx_out = ov_x;
  117. }
  118. }
  119. return found;
  120. }
  121. Observation SceneClassifier::classify_direct(std::vector<Box>& boxes, int width, int height, double ts,
  122. long frame_id) const {
  123. Observation obs;
  124. obs.ts = ts;
  125. obs.frame_id = frame_id;
  126. obs.boxes = boxes;
  127. const std::vector<Point> poly = roi_polygon(width, height);
  128. bool found = false;
  129. Box best_box;
  130. int best_state = kUnknown;
  131. double best_score = 0.0;
  132. for (const Box& box : boxes) {
  133. const std::string name = normalize(box.class_name);
  134. const auto it = p_.direct_map.find(name);
  135. if (it == p_.direct_map.end()) { continue; }
  136. const double ratio = box_in_polygon_ratio(box, poly);
  137. if (ratio < p_.roi_min_ratio) { continue; }
  138. const double score = static_cast<double>(box.score) * (0.5 + 0.5 * ratio);
  139. if (!found || score > best_score) {
  140. found = true;
  141. best_box = box;
  142. best_state = it->second;
  143. best_score = score;
  144. }
  145. }
  146. if (!found) {
  147. obs.reason = "no_direct_hit";
  148. if (p_.unknown_on_no_detection) {
  149. obs.state = kUnknown;
  150. obs.confidence = 0.0;
  151. } else {
  152. obs.state = static_cast<int>(SceneState::NOT_ON_TRAIN);
  153. obs.confidence = p_.no_container_conf;
  154. }
  155. return obs;
  156. }
  157. char buf[128];
  158. std::snprintf(buf, sizeof(buf), "direct:%s=%.2f", best_box.class_name.c_str(),
  159. static_cast<double>(best_box.score));
  160. obs.state = best_state;
  161. obs.confidence = std::fmin(1.0, static_cast<double>(best_box.score));
  162. obs.reason = buf;
  163. return obs;
  164. }
  165. Observation SceneClassifier::classify_composed(std::vector<Box>& boxes, int width, int height,
  166. double ts, long frame_id) const {
  167. Observation obs;
  168. obs.ts = ts;
  169. obs.frame_id = frame_id;
  170. obs.boxes = boxes;
  171. if (boxes.empty()) {
  172. obs.reason = "no_detection";
  173. if (p_.unknown_on_no_detection) {
  174. obs.state = kUnknown;
  175. obs.confidence = 0.0;
  176. } else {
  177. obs.state = static_cast<int>(SceneState::NOT_ON_TRAIN);
  178. obs.confidence = p_.no_container_conf;
  179. }
  180. return obs;
  181. }
  182. const std::vector<Point> poly = roi_polygon(width, height);
  183. std::vector<std::pair<Box, double>> containers;
  184. std::vector<std::pair<Box, double>> beds;
  185. std::vector<std::pair<Box, double>> flats;
  186. for (const Box& box : boxes) {
  187. const std::string group = group_of(box.class_name);
  188. if (group == "ignore" || group == "unknown") { continue; }
  189. const double ratio = box_in_polygon_ratio(box, poly);
  190. if (ratio < p_.roi_min_ratio) { continue; }
  191. if (group == "container") {
  192. containers.push_back({box, ratio});
  193. } else if (group == "bed") {
  194. beds.push_back({box, ratio});
  195. } else {
  196. flats.push_back({box, ratio});
  197. }
  198. }
  199. if (containers.empty()) {
  200. // ROI 内没有集装箱 → "集装箱不在车上"
  201. double wagon_score = 0.0;
  202. for (const auto& item : beds) { wagon_score = std::fmax(wagon_score, item.first.score); }
  203. for (const auto& item : flats) { wagon_score = std::fmax(wagon_score, item.first.score); }
  204. obs.state = static_cast<int>(SceneState::NOT_ON_TRAIN);
  205. obs.confidence = std::fmin(1.0, 0.55 + 0.35 * wagon_score);
  206. std::string reason = "no_container";
  207. if (wagon_score > 0.0) {
  208. char buf[64];
  209. std::snprintf(buf, sizeof(buf), "_wagon_seen=%.2f", wagon_score);
  210. reason += buf;
  211. }
  212. obs.reason = reason;
  213. return obs;
  214. }
  215. // 主箱:得分 × (0.5 + 0.5 × ROI 占比) 最大者
  216. Box container = containers[0].first;
  217. double best_container = -1.0;
  218. for (const auto& item : containers) {
  219. const double score = static_cast<double>(item.first.score) * (0.5 + 0.5 * item.second);
  220. if (score > best_container) {
  221. best_container = score;
  222. container = item.first;
  223. }
  224. }
  225. Box bed_wagon;
  226. Box flat_wagon;
  227. double bed_score = 0.0;
  228. double bed_ov = 0.0;
  229. double flat_score = 0.0;
  230. double flat_ov = 0.0;
  231. const bool has_bed = best_support(container, beds, &bed_wagon, &bed_score, &bed_ov);
  232. const bool has_flat = best_support(container, flats, &flat_wagon, &flat_score, &flat_ov);
  233. if (!has_bed && !has_flat) {
  234. // 有箱,但底下既不是车斗也不是平板车(吊起来/在卡车上/堆场)
  235. obs.state = static_cast<int>(SceneState::NOT_ON_TRAIN);
  236. obs.confidence = std::fmin(0.75, 0.40 + 0.25 * container.score);
  237. char buf[128];
  238. std::snprintf(buf, sizeof(buf), "container_without_wagon(c=%.2f)",
  239. static_cast<double>(container.score));
  240. obs.reason = buf;
  241. return obs;
  242. }
  243. int state = static_cast<int>(SceneState::BED);
  244. Box wagon = bed_wagon;
  245. double ov_x = bed_ov;
  246. const char* tag = "bed";
  247. if (has_bed && has_flat) {
  248. if (flat_score > bed_score) { // 平票时保持 bed(与 Python 的 max 语义一致)
  249. state = static_cast<int>(SceneState::FLATBED);
  250. wagon = flat_wagon;
  251. ov_x = flat_ov;
  252. tag = "flatbed";
  253. }
  254. } else if (has_flat) {
  255. state = static_cast<int>(SceneState::FLATBED);
  256. wagon = flat_wagon;
  257. ov_x = flat_ov;
  258. tag = "flatbed";
  259. }
  260. double conf =
  261. std::sqrt(static_cast<double>(container.score) * wagon.score) * (0.55 + 0.45 * ov_x);
  262. bool ambiguous = false;
  263. if (has_bed && has_flat) {
  264. const double hi = std::fmax(bed_score, flat_score);
  265. const double lo = std::fmin(bed_score, flat_score);
  266. ambiguous = hi < 1.10 * lo;
  267. }
  268. if (ambiguous) { conf *= 0.85; } // 两种车厢都像 → 降权,交给时序滤波去稳定
  269. char buf[160];
  270. std::snprintf(buf, sizeof(buf), "c=%.2f %s=%.2f ov=%.2f%s",
  271. static_cast<double>(container.score), tag, static_cast<double>(wagon.score), ov_x,
  272. ambiguous ? " ambiguous" : "");
  273. obs.state = state;
  274. obs.confidence = std::fmin(1.0, conf);
  275. obs.reason = buf;
  276. return obs;
  277. }
  278. } // namespace portcv