image.vision\video\video_tracking2.mbt

84.1% · 69 / 82 points · 388 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

  1. 1///|
  2. 2/// # 视频跟踪2 video/video_tracking2
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 视频跟踪 — 多目标/长程/关联
  7. 7// Video tracking: multi-object / long-term / association
  8. 8//
  9. 9// Phase 17 v400: 视频处理大扩展 — 视频跟踪。
  10. 10
  11. 11///|
  12. 12/// 跟踪方法。
  13. 13/// 跟踪方法 Tracking method.
  14. 14/// `#non_exhaustive` 表示未来可能添加新构造器
  15. 15#derive(Eq, @debug.Debug)
  16. 16#non_exhaustive
  17. 17pub(all) enum MultiTrackingMethod {
  18. 18 Centroid // 质心跟踪
  19. 19 KalmanFilter // 卡尔曼滤波
  20. 20 MeanShift // 均值漂移
  21. 21}
  22. 22
  23. 23///|
  24. 24pub extend MultiTrackingMethod with @debug.Debug::{to_repr}
  25. 25
  26. 26///|
  27. 27pub extend MultiTrackingMethod with Eq::{not_equal, equal}
  28. 28
  29. 29///|
  30. 30/// 跟踪对象状态。
  31. 31/// 跟踪目标状态 Tracked object state.
  32. 32/// `#non_exhaustive` 表示未来可能添加新构造器
  33. 33#derive(Eq, @debug.Debug)
  34. 34#non_exhaustive
  35. 35pub(all) enum MultiTrackState {
  36. 36 Active // 活跃
  37. 37 Lost // 丢失
  38. 38 Terminated // 终止
  39. 39}
  40. 40
  41. 41///|
  42. 42pub extend MultiTrackState with @debug.Debug::{to_repr}
  43. 43
  44. 44///|
  45. 45pub extend MultiTrackState with Eq::{not_equal, equal}
  46. 46
  47. 47///|
  48. 48/// 跟踪对象。
  49. 49/// 跟踪目标 Tracked object.
  50. 50#derive(Eq, @debug.Debug)
  51. 51pub(all) struct MultiTrackedObject {
  52. 52 id : Int32
  53. 53 x : Double // 中心 x
  54. 54 y : Double // 中心 y
  55. 55 width : Double
  56. 56 height : Double
  57. 57 state : MultiTrackState
  58. 58 age : Int32 // 存活帧数
  59. 59 lost_count : Int32 // 连续丢失计数
  60. 60}
  61. 61
  62. 62///|
  63. 63pub extend MultiTrackedObject with @debug.Debug::{to_repr}
  64. 64
  65. 65///|
  66. 66pub extend MultiTrackedObject with Eq::{not_equal, equal}
  67. 67
  68. 68///|
  69. 69/// 检测对象。
  70. 70/// 检测目标 Detected object.
  71. 71#derive(Eq, @debug.Debug)
  72. 72pub(all) struct MultiDetectedObject {
  73. 73 x : Double
  74. 74 y : Double
  75. 75 width : Double
  76. 76 height : Double
  77. 77 confidence : Double
  78. 78}
  79. 79
  80. 80///|
  81. 81pub extend MultiDetectedObject with @debug.Debug::{to_repr}
  82. 82
  83. 83///|
  84. 84pub extend MultiDetectedObject with Eq::{not_equal, equal}
  85. 85
  86. 86///|
  87. 87/// 跟踪配置。
  88. 88/// 跟踪配置 Tracking configuration.
  89. 89#derive(Eq, @debug.Debug)
  90. 90pub(all) struct MultiTrackingConfig {
  91. 91 track_method : MultiTrackingMethod
  92. 92 max_lost_frames : Int32 // 最大丢失帧数
  93. 93 association_threshold : Double // 关联距离阈值
  94. 94 min_confidence : Double // 最小检测置信度
  95. 95}
  96. 96
  97. 97///|
  98. 98pub extend MultiTrackingConfig with @debug.Debug::{to_repr}
  99. 99
  100. 100///|
  101. 101pub extend MultiTrackingConfig with Eq::{not_equal, equal}
  102. 102
  103. 103///|
  104. 104/// 默认跟踪配置。
  105. 105/// 默认跟踪配置 Default tracking configuration.
  106. 106pub fn default_tracking_config() -> MultiTrackingConfig {
  107. 107● {
  108. 108 track_method: Centroid,
  109. 109 max_lost_frames: 5,
  110. 110 association_threshold: 50.0,
  111. 111 min_confidence: 0.5,
  112. 112 }
  113. 113}
  114. 114
  115. 115///|
  116. 116/// 计算两个对象间的中心距离。
  117. 117/// 计算两目标质心距离 Compute centroid distance between two objects.
  118. 118fn centroid_distance(
  119. 119 obj1 : MultiTrackedObject,
  120. 120 obj2 : MultiDetectedObject,
  121. 121) -> Double {
  122. 122● let dx = obj1.x - obj2.x
  123. 123 let dy = obj1.y - obj2.y
  124. 124● (dx * dx + dy * dy).sqrt()
  125. 125}
  126. 126
  127. 127///|
  128. 128/// 计算 IoU(交并比)。
  129. 129/// 计算 IoU(交并比) Compute IoU (Intersection over Union).
  130. 130fn compute_iou(obj1 : MultiTrackedObject, obj2 : MultiDetectedObject) -> Double {
  131. 131● let x1 = obj1.x - obj1.width / 2.0
  132. 132 let y1 = obj1.y - obj1.height / 2.0
  133. 133 let x2 = obj1.x + obj1.width / 2.0
  134. 134 let y2 = obj1.y + obj1.height / 2.0
  135. 135 let x3 = obj2.x - obj2.width / 2.0
  136. 136 let y3 = obj2.y - obj2.height / 2.0
  137. 137 let x4 = obj2.x + obj2.width / 2.0
  138. 138 let y4 = obj2.y + obj2.height / 2.0
  139. 139◐ let ix1 = if x1 > x3 { x1 } else { x3 }
  140. 140◐ let iy1 = if y1 > y3 { y1 } else { y3 }
  141. 141◐ let ix2 = if x2 < x4 { x2 } else { x4 }
  142. 142◐ let iy2 = if y2 < y4 { y2 } else { y4 }
  143. 143 let inter_w = ix2 - ix1
  144. 144 let inter_h = iy2 - iy1
  145. 145 if inter_w <= 0.0 || inter_h <= 0.0 {
  146. 146● return 0.0
  147. 147 }
  148. 148 let inter = inter_w * inter_h
  149. 149 let area1 = obj1.width * obj1.height
  150. 150 let area2 = obj2.width * obj2.height
  151. 151 let union = area1 + area2 - inter
  152. 152 if union <= 0.0 {
  153. 153○ return 0.0
  154. 154 }
  155. 155 inter / union
  156. 156}
  157. 157
  158. 158///|
  159. 159/// 关联检测对象与跟踪对象。
  160. 160/// 关联检测目标与跟踪目标 Associate detected objects with tracked objects.
  161. 161pub fn associate_objects(
  162. 162 tracked : Array[MultiTrackedObject],
  163. 163 detected : Array[MultiDetectedObject],
  164. 164 config : MultiTrackingConfig,
  165. 165) -> Array[(Int32, Int32)] {
  166. 166 // 返回 (tracked_idx, detected_idx) 配对
  167. 167● let pairs : Array[(Int32, Int32)] = []
  168. 168 let used_detected : Array[Bool] = []
  169. 169● for _ in 0..<detected.length() {
  170. 170● used_detected.push(false)
  171. 171 }
  172. 172● for i in 0..<tracked.length() {
  173. 173● if tracked[i].state is Terminated {
  174. 174○ continue
  175. 175 }
  176. 176 let mut best_j = -1
  177. 177 let mut best_dist = config.association_threshold
  178. 178● for j in 0..<detected.length() {
  179. 179● if used_detected[j] {
  180. 180○ continue
  181. 181 }
  182. 182● let dist = centroid_distance(tracked[i], detected[j])
  183. 183● let iou = compute_iou(tracked[i], detected[j])
  184. 184 let score = dist - iou * 50.0
  185. 185 if score < best_dist {
  186. 186● best_dist = score
  187. 187 best_j = j
  188. 188 }
  189. 189 }
  190. 190 if best_j >= 0 {
  191. 191● pairs.push((i, best_j))
  192. 192 used_detected[best_j] = true
  193. 193 }
  194. 194 }
  195. 195 pairs
  196. 196}
  197. 197
  198. 198///|
  199. 199/// 初始化跟踪器。
  200. 200/// 初始化跟踪器 Initialize tracker
  201. 201pub fn init_tracker(
  202. 202 detections : Array[MultiDetectedObject],
  203. 203 config : MultiTrackingConfig,
  204. 204) -> Array[MultiTrackedObject] {
  205. 205● let tracked : Array[MultiTrackedObject] = []
  206. 206 let mut id = 0
  207. 207 for det in detections {
  208. 208● if det.confidence < config.min_confidence {
  209. 209● continue
  210. 210 }
  211. 211● tracked.push({
  212. 212 id,
  213. 213 x: det.x,
  214. 214 y: det.y,
  215. 215 width: det.width,
  216. 216 height: det.height,
  217. 217 state: Active,
  218. 218 age: 1,
  219. 219 lost_count: 0,
  220. 220 })
  221. 221 id = id + 1
  222. 222 }
  223. 223 tracked
  224. 224}
  225. 225
  226. 226///|
  227. 227/// 更新跟踪器。
  228. 228/// 用新检测更新跟踪器 Update tracker with new detections.
  229. 229pub fn update_tracker(
  230. 230 tracked : Array[MultiTrackedObject],
  231. 231 detections : Array[MultiDetectedObject],
  232. 232 config : MultiTrackingConfig,
  233. 233) -> Array[MultiTrackedObject] {
  234. 234● let pairs = associate_objects(tracked, detections, config)
  235. 235 let used_detected : Array[Bool] = []
  236. 236● for _ in 0..<detections.length() {
  237. 237● used_detected.push(false)
  238. 238 }
  239. 239 let result : Array[MultiTrackedObject] = []
  240. 240 // 标记已关联的检测
  241. 241 for (_, j) in pairs {
  242. 242● used_detected[j] = true
  243. 243 }
  244. 244 // 更新已关联的跟踪对象
  245. 245● for i in 0..<tracked.length() {
  246. 246● let mut paired_j = -1
  247. 247 for (ti, dj) in pairs {
  248. 248● if ti == i {
  249. 249● paired_j = dj
  250. 250 }
  251. 251 }
  252. 252 if paired_j >= 0 {
  253. 253● let det = detections[paired_j]
  254. 254● result.push({
  255. 255 id: tracked[i].id,
  256. 256 x: det.x,
  257. 257 y: det.y,
  258. 258 width: det.width,
  259. 259 height: det.height,
  260. 260 state: Active,
  261. 261 age: tracked[i].age + 1,
  262. 262 lost_count: 0,
  263. 263 })
  264. 264 } else {
  265. 265 // 未关联:增加丢失计数
  266. 266● let new_lost = tracked[i].lost_count + 1
  267. 267 let new_state = if new_lost > config.max_lost_frames {
  268. 268○ Terminated
  269. 269 } else {
  270. 270● Lost
  271. 271 }
  272. 272● result.push({
  273. 273 id: tracked[i].id,
  274. 274 x: tracked[i].x,
  275. 275 y: tracked[i].y,
  276. 276 width: tracked[i].width,
  277. 277 height: tracked[i].height,
  278. 278 state: new_state,
  279. 279 age: tracked[i].age + 1,
  280. 280 lost_count: new_lost,
  281. 281 })
  282. 282 }
  283. 283 }
  284. 284 // 添加新检测到的对象
  285. 285 let mut max_id = 0
  286. 286 for t in tracked {
  287. 287● if t.id > max_id {
  288. 288○ max_id = t.id
  289. 289 }
  290. 290 }
  291. 291 let mut next_id = max_id + 1
  292. 292● for j in 0..<detections.length() {
  293. 293● if !used_detected[j] && detections[j].confidence >= config.min_confidence {
  294. 294○ result.push({
  295. 295 id: next_id,
  296. 296 x: detections[j].x,
  297. 297 y: detections[j].y,
  298. 298 width: detections[j].width,
  299. 299 height: detections[j].height,
  300. 300 state: Active,
  301. 301 age: 1,
  302. 302 lost_count: 0,
  303. 303 })
  304. 304 next_id = next_id + 1
  305. 305 }
  306. 306 }
  307. 307 result
  308. 308}
  309. 309
  310. 310///|
  311. 311/// 多目标跟踪。
  312. 312/// 跨帧多目标跟踪 Multi-object tracking across frames.
  313. 313pub fn multi_object_track(
  314. 314 detections_per_frame : Array[Array[MultiDetectedObject]],
  315. 315 config : MultiTrackingConfig,
  316. 316) -> Array[Array[MultiTrackedObject]] {
  317. 317● let results : Array[Array[MultiTrackedObject]] = []
  318. 318● let n = detections_per_frame.length()
  319. 319 if n == 0 {
  320. 320○ return results
  321. 321 }
  322. 322● let mut tracked = init_tracker(detections_per_frame[0], config)
  323. 323● results.push(tracked)
  324. 324 for i in 1..<n {
  325. 325● tracked = update_tracker(tracked, detections_per_frame[i], config)
  326. 326● results.push(tracked)
  327. 327 }
  328. 328 results
  329. 329}
  330. 330
  331. 331///|
  332. 332/// 计算跟踪长度。
  333. 333/// 计算轨迹长度(最长轨迹年龄) Compute track length (age of longest track).
  334. 334pub fn compute_track_length(tracked : Array[MultiTrackedObject]) -> Int32 {
  335. 335● let mut max_age = 0
  336. 336 for t in tracked {
  337. 337● if t.age > max_age {
  338. 338● max_age = t.age
  339. 339 }
  340. 340 }
  341. 341 max_age
  342. 342}
  343. 343
  344. 344///|
  345. 345/// 计算活跃跟踪数。
  346. 346/// 计算活跃轨迹数 Compute number of active tracks.
  347. 347pub fn count_active_tracks(tracked : Array[MultiTrackedObject]) -> Int32 {
  348. 348● let mut count = 0
  349. 349 for t in tracked {
  350. 350● if t.state is Active {
  351. 351● count = count + 1
  352. 352 }
  353. 353 }
  354. 354 count
  355. 355}
  356. 356
  357. 357///|
  358. 358/// 计算跟踪稳定性。
  359. 359/// 计算跟踪稳定性分 Compute tracking stability score.
  360. 360pub fn tracking_stability(tracked : Array[MultiTrackedObject]) -> Double {
  361. 361● let n = tracked.length()
  362. 362 if n == 0 {
  363. 363● return 0.0
  364. 364 }
  365. 365 let mut total_score = 0.0
  366. 366 for t in tracked {
  367. 367◐ let active_bonus = if t.state is Active { 1.0 } else { 0.0 }
  368. 368● let age_score = t.age.to_double() / (t.age.to_double() + 10.0)
  369. 369 total_score = total_score + active_bonus * age_score
  370. 370 }
  371. 371● total_score / n.to_double()
  372. 372}
  373. 373
  374. 374///|
  375. 375/// 过滤低置信度检测。
  376. 376/// 过滤低置信度检测 Filter low confidence detections.
  377. 377pub fn filter_detections(
  378. 378 detections : Array[MultiDetectedObject],
  379. 379 min_confidence : Double,
  380. 380) -> Array[MultiDetectedObject] {
  381. 381● let result : Array[MultiDetectedObject] = []
  382. 382 for det in detections {
  383. 383● if det.confidence >= min_confidence {
  384. 384● result.push(det)
  385. 385 }
  386. 386 }
  387. 387 result
  388. 388}