image.process\detection\yolo_detection.mbt

93.6% · 161 / 172 points · 764 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/// # YOLO 检测 yolo detection
  3. 3///
  4. 4/// 图像处理算法模块
  5. 5/// 图像处理算法模块 Image processing algorithm module
  6. 6// 目标检测增强(v16.0.0)
  7. 7// YOLO 风格目标检测、边界框回归、非极大值抑制、目标跟踪、检测评估
  8. 8
  9. 9///|
  10. 10/// 边界框
  11. 11pub(all) struct YoloBoundingBox {
  12. 12 x : Double // 中心 X
  13. 13 y : Double // 中心 Y
  14. 14 width : Double
  15. 15 height : Double
  16. 16 confidence : Double
  17. 17 class_id : Int32
  18. 18 class_name : String
  19. 19}
  20. 20
  21. 21///|
  22. 22/// 检测结果
  23. 23pub(all) struct YoloDetectionResult {
  24. 24 boxes : Array[YoloBoundingBox]
  25. 25 num_detections : Int32
  26. 26 inference_time_ms : Double
  27. 27 input_width : Int32
  28. 28 input_height : Int32
  29. 29}
  30. 30
  31. 31///|
  32. 32/// YOLO 配置
  33. 33pub(all) struct YoloConfig {
  34. 34 model_version : String // "yolov3" / "yolov4" / "yolov5" / "yolov8"
  35. 35 input_size : Int32
  36. 36 num_classes : Int32
  37. 37 confidence_threshold : Double
  38. 38 iou_threshold : Double
  39. 39 max_detections : Int32
  40. 40 anchors : Array[(Double, Double)]
  41. 41 strides : Array[Int32]
  42. 42}
  43. 43
  44. 44///|
  45. 45/// 锚框
  46. 46pub(all) struct AnchorBox {
  47. 47 width : Double
  48. 48 height : Double
  49. 49 stride : Int32
  50. 50}
  51. 51
  52. 52///|
  53. 53/// 检测目标类型
  54. 54/// `#non_exhaustive` 表示未来可能添加新构造器
  55. 55#derive(Eq)
  56. 56#non_exhaustive
  57. 57pub(all) enum ObjectClass {
  58. 58 Person
  59. 59 Car
  60. 60 Bus
  61. 61 Truck
  62. 62 Motorcycle
  63. 63 Bicycle
  64. 64 Dog
  65. 65 Cat
  66. 66 Bird
  67. 67 Chair
  68. 68 Table
  69. 69 Bottle
  70. 70 Cup
  71. 71 Phone
  72. 72 Laptop
  73. 73 Tv
  74. 74 Book
  75. 75 Unknown
  76. 76}
  77. 77
  78. 78///|
  79. 79pub extend ObjectClass with Eq::{not_equal, equal}
  80. 80
  81. 81///|
  82. 82/// 跟踪目标
  83. 83pub(all) struct YoloTrackedObject {
  84. 84 id : Int32
  85. 85 class_id : Int32
  86. 86 class_name : String
  87. 87 bbox : YoloBoundingBox
  88. 88 age : Int32
  89. 89 visible_count : Int32
  90. 90 invisible_count : Int32
  91. 91 velocity_x : Double
  92. 92 velocity_y : Double
  93. 93 trajectory : Array[(Double, Double)]
  94. 94 color : (Int32, Int32, Int32)
  95. 95}
  96. 96
  97. 97///|
  98. 98/// 跟踪结果
  99. 99pub(all) struct YoloTrackingResult {
  100. 100 objects : Array[YoloTrackedObject]
  101. 101 num_objects : Int32
  102. 102 frame_index : Int32
  103. 103 tracking_time_ms : Double
  104. 104}
  105. 105
  106. 106///|
  107. 107/// 检测评估指标
  108. 108pub(all) struct YoloDetectionMetrics {
  109. 109 precision : Double
  110. 110 recall : Double
  111. 111 f1_score : Double
  112. 112 mAP : Double // mean Average Precision
  113. 113 mAP50 : Double
  114. 114 mAP50_95 : Double
  115. 115 true_positives : Int32
  116. 116 false_positives : Int32
  117. 117 false_negatives : Int32
  118. 118}
  119. 119
  120. 120///|
  121. 121/// 创建默认 YOLO 配置
  122. 122pub fn create_default_yolo_config() -> YoloConfig {
  123. 123● let anchors : Array[(Double, Double)] = [
  124. 124 (10.0, 13.0),
  125. 125 (16.0, 30.0),
  126. 126 (33.0, 23.0),
  127. 127 (30.0, 61.0),
  128. 128 (62.0, 45.0),
  129. 129 (59.0, 119.0),
  130. 130 (116.0, 90.0),
  131. 131 (156.0, 198.0),
  132. 132 (373.0, 326.0),
  133. 133 ]
  134. 134 let strides : Array[Int32] = [8, 16, 32]
  135. 135 YoloConfig::{
  136. 136 model_version: "yolov8",
  137. 137 input_size: 640,
  138. 138 num_classes: 80,
  139. 139 confidence_threshold: 0.25,
  140. 140 iou_threshold: 0.45,
  141. 141 max_detections: 300,
  142. 142 anchors,
  143. 143 strides,
  144. 144 }
  145. 145}
  146. 146
  147. 147///|
  148. 148/// 计算 IoU(交并比)
  149. 149pub fn calculate_iou(
  150. 150 box1 : YoloBoundingBox,
  151. 151 box2 : YoloBoundingBox,
  152. 152) -> Double raise @types.LoadError {
  153. 153 // 输入验证
  154. 154● if box1.width <= 0.0 || box1.height <= 0.0 {
  155. 155● raise @types.LoadError::DecodeFailed(
  156. 156 "calculate_iou: 检测框1的尺寸必须大于0",
  157. 157 )
  158. 158 }
  159. 159 if box2.width <= 0.0 || box2.height <= 0.0 {
  160. 160● raise @types.LoadError::DecodeFailed(
  161. 161 "calculate_iou: 检测框2的尺寸必须大于0",
  162. 162 )
  163. 163 }
  164. 164
  165. 165 let x1_min = box1.x - box1.width / 2.0
  166. 166 let x1_max = box1.x + box1.width / 2.0
  167. 167 let y1_min = box1.y - box1.height / 2.0
  168. 168 let y1_max = box1.y + box1.height / 2.0
  169. 169
  170. 170 let x2_min = box2.x - box2.width / 2.0
  171. 171 let x2_max = box2.x + box2.width / 2.0
  172. 172 let y2_min = box2.y - box2.height / 2.0
  173. 173 let y2_max = box2.y + box2.height / 2.0
  174. 174
  175. 175● let inter_x_min = if x1_min > x2_min { x1_min } else { x2_min }
  176. 176● let inter_x_max = if x1_max < x2_max { x1_max } else { x2_max }
  177. 177● let inter_y_min = if y1_min > y2_min { y1_min } else { y2_min }
  178. 178● let inter_y_max = if y1_max < y2_max { y1_max } else { y2_max }
  179. 179
  180. 180 let inter_width = if inter_x_max > inter_x_min {
  181. 181● inter_x_max - inter_x_min
  182. 182 } else {
  183. 183● 0.0
  184. 184 }
  185. 185 let inter_height = if inter_y_max > inter_y_min {
  186. 186● inter_y_max - inter_y_min
  187. 187 } else {
  188. 188● 0.0
  189. 189 }
  190. 190 let inter_area = inter_width * inter_height
  191. 191
  192. 192 let area1 = box1.width * box1.height
  193. 193 let area2 = box2.width * box2.height
  194. 194 let union_area = area1 + area2 - inter_area
  195. 195
  196. 196 if union_area > 0.0 {
  197. 197● inter_area / union_area
  198. 198 } else {
  199. 199○ 0.0
  200. 200 }
  201. 201}
  202. 202
  203. 203///|
  204. 204/// 非极大值抑制(NMS)
  205. 205pub fn non_max_suppression(
  206. 206 boxes : Array[YoloBoundingBox],
  207. 207 iou_threshold : Double,
  208. 208 max_detections : Int32,
  209. 209) -> Array[YoloBoundingBox] raise @types.LoadError {
  210. 210 // 输入验证
  211. 211● if boxes.length() == 0 {
  212. 212● raise @types.LoadError::DecodeFailed(
  213. 213 "non_max_suppression: 检测框列表不能为空",
  214. 214 )
  215. 215 }
  216. 216 if iou_threshold < 0.0 || iou_threshold > 1.0 {
  217. 217● raise @types.LoadError::DecodeFailed(
  218. 218 "non_max_suppression: iou_threshold必须在0-1之间",
  219. 219 )
  220. 220 }
  221. 221 if max_detections <= 0 {
  222. 222● raise @types.LoadError::DecodeFailed(
  223. 223 "non_max_suppression: max_detections必须大于0",
  224. 224 )
  225. 225 }
  226. 226
  227. 227● if boxes.length() == 0 {
  228. 228○ return []
  229. 229 }
  230. 230
  231. 231 // 按置信度排序(冒泡排序,降序)
  232. 232 let sorted = boxes
  233. 233● for i in 0..<sorted.length() {
  234. 234● for j in 0..<(sorted.length() - i - 1) {
  235. 235● if sorted[j].confidence < sorted[j + 1].confidence {
  236. 236● let temp = sorted[j]
  237. 237 sorted[j] = sorted[j + 1]
  238. 238 sorted[j + 1] = temp
  239. 239 }
  240. 240 }
  241. 241 }
  242. 242
  243. 243 // NMS
  244. 244 let result : Array[YoloBoundingBox] = []
  245. 245 let suppressed : Array[Bool] = []
  246. 246● for _ in 0..<sorted.length() {
  247. 247● suppressed.push(false)
  248. 248 }
  249. 249
  250. 250● for i in 0..<sorted.length() {
  251. 251● if suppressed[i] {
  252. 252● continue
  253. 253 }
  254. 254● if result.length() >= max_detections {
  255. 255● break
  256. 256 }
  257. 257● result.push(sorted[i])
  258. 258
  259. 259● for j in (i + 1)..<sorted.length() {
  260. 260● if suppressed[j] {
  261. 261○ continue
  262. 262 }
  263. 263● let iou = calculate_iou(sorted[i], sorted[j])
  264. 264 if iou > iou_threshold && sorted[i].class_id == sorted[j].class_id {
  265. 265● suppressed[j] = true
  266. 266 }
  267. 267 }
  268. 268 }
  269. 269
  270. 270 result
  271. 271}
  272. 272
  273. 273///|
  274. 274/// 边界框回归(简化版)
  275. 275pub fn refine_bounding_box(
  276. 276 box : YoloBoundingBox,
  277. 277 dx : Double,
  278. 278 dy : Double,
  279. 279 dw : Double,
  280. 280 dh : Double,
  281. 281) -> YoloBoundingBox raise @types.LoadError {
  282. 282 // 输入验证
  283. 283● if box.width <= 0.0 || box.height <= 0.0 {
  284. 284● raise @types.LoadError::DecodeFailed(
  285. 285 "refine_bounding_box: 检测框尺寸必须大于0",
  286. 286 )
  287. 287 }
  288. 288
  289. 289 let new_x = box.x + dx * box.width
  290. 290 let new_y = box.y + dy * box.height
  291. 291 let new_width = box.width * (dw * 1.0)
  292. 292 let new_height = box.height * (dh * 1.0)
  293. 293
  294. 294 YoloBoundingBox::{
  295. 295 x: new_x,
  296. 296 y: new_y,
  297. 297 width: new_width,
  298. 298 height: new_height,
  299. 299 confidence: box.confidence,
  300. 300 class_id: box.class_id,
  301. 301 class_name: box.class_name,
  302. 302 }
  303. 303}
  304. 304
  305. 305///|
  306. 306/// 简单目标检测(基于颜色/纹理的简化版)
  307. 307pub fn detect_objects_simple(
  308. 308 img : @types.Image,
  309. 309 config : YoloConfig,
  310. 310) -> YoloDetectionResult raise @types.LoadError {
  311. 311 // 输入验证
  312. 312● if img.width <= 0 || img.height <= 0 {
  313. 313● raise @types.LoadError::DecodeFailed(
  314. 314 "detect_objects_simple: 图像尺寸必须大于0",
  315. 315 )
  316. 316 }
  317. 317 if img.channels < 1 || img.channels > 4 {
  318. 318● raise @types.LoadError::DecodeFailed(
  319. 319 "detect_objects_simple: 通道数必须在1-4之间",
  320. 320 )
  321. 321 }
  322. 322 let expected_size = img.width * img.height * img.channels
  323. 323● if img.data.length() != expected_size {
  324. 324● raise @types.LoadError::DecodeFailed(
  325. 325 "detect_objects_simple: 数据大小不匹配,期望 " +
  326. 326● expected_size.to_string() +
  327. 327 ",实际 " +
  328. 328● img.data.length().to_string(),
  329. 329 )
  330. 330 }
  331. 331 if config.input_size <= 0 {
  332. 332● raise @types.LoadError::DecodeFailed(
  333. 333 "detect_objects_simple: input_size必须大于0",
  334. 334 )
  335. 335 }
  336. 336 if config.num_classes <= 0 {
  337. 337● raise @types.LoadError::DecodeFailed(
  338. 338 "detect_objects_simple: num_classes必须大于0",
  339. 339 )
  340. 340 }
  341. 341 if config.confidence_threshold < 0.0 || config.confidence_threshold > 1.0 {
  342. 342● raise @types.LoadError::DecodeFailed(
  343. 343 "detect_objects_simple: confidence_threshold必须在0-1之间",
  344. 344 )
  345. 345 }
  346. 346 if config.iou_threshold < 0.0 || config.iou_threshold > 1.0 {
  347. 347● raise @types.LoadError::DecodeFailed(
  348. 348 "detect_objects_simple: iou_threshold必须在0-1之间",
  349. 349 )
  350. 350 }
  351. 351 if config.max_detections <= 0 {
  352. 352● raise @types.LoadError::DecodeFailed(
  353. 353 "detect_objects_simple: max_detections必须大于0",
  354. 354 )
  355. 355 }
  356. 356
  357. 357 let w = img.width
  358. 358 let h = img.height
  359. 359 let boxes : Array[YoloBoundingBox] = []
  360. 360
  361. 361 // 简化版:滑动窗口检测
  362. 362 let window_sizes = [64, 128, 256]
  363. 363 let stride = 32
  364. 364
  365. 365 for window_size in window_sizes {
  366. 366● let mut y = 0
  367. 367 while y + window_size <= h {
  368. 368● let mut x = 0
  369. 369 while x + window_size <= w {
  370. 370 // 计算窗口内的平均颜色方差作为检测分数
  371. 371● let mut sum = 0.0
  372. 372 let mut sum_sq = 0.0
  373. 373 let mut count = 0
  374. 374 for py in y..<(y + window_size) {
  375. 375● for px in x..<(x + window_size) {
  376. 376● let pixel = img.data[py * w + px].to_double()
  377. 377 sum += pixel
  378. 378 sum_sq += pixel * pixel
  379. 379 count += 1
  380. 380 }
  381. 381 }
  382. 382 if count > 0 {
  383. 383● let mean = sum / count.to_double()
  384. 384● let variance = sum_sq / count.to_double() - mean * mean
  385. 385 let confidence = if variance > 100.0 {
  386. 386● variance / 1000.0
  387. 387 } else {
  388. 388● 0.0
  389. 389 }
  390. 390 if confidence > config.confidence_threshold {
  391. 391● boxes.push(YoloBoundingBox::{
  392. 392● x: (x + window_size / 2).to_double(),
  393. 393● y: (y + window_size / 2).to_double(),
  394. 394● width: window_size.to_double(),
  395. 395● height: window_size.to_double(),
  396. 396 confidence,
  397. 397 class_id: 0,
  398. 398 class_name: "object",
  399. 399 })
  400. 400 }
  401. 401 }
  402. 402 x += stride
  403. 403 }
  404. 404 y += stride
  405. 405 }
  406. 406 }
  407. 407
  408. 408 // NMS
  409. 409● let final_boxes = non_max_suppression(
  410. 410 boxes,
  411. 411 config.iou_threshold,
  412. 412 config.max_detections,
  413. 413 )
  414. 414
  415. 415 YoloDetectionResult::{
  416. 416 boxes: final_boxes,
  417. 417● num_detections: final_boxes.length(),
  418. 418 inference_time_ms: 0.0,
  419. 419 input_width: w,
  420. 420 input_height: h,
  421. 421 }
  422. 422}
  423. 423
  424. 424///|
  425. 425/// 目标跟踪初始化
  426. 426pub fn initialize_object_tracking(
  427. 427 detection : YoloDetectionResult,
  428. 428) -> Array[YoloTrackedObject] raise @types.LoadError {
  429. 429 // 输入验证
  430. 430● if detection.boxes.length() == 0 {
  431. 431● raise @types.LoadError::DecodeFailed(
  432. 432 "initialize_object_tracking: 检测框列表不能为空",
  433. 433 )
  434. 434 }
  435. 435
  436. 436 let objects : Array[YoloTrackedObject] = []
  437. 437 let colors = [
  438. 438 (255, 0, 0),
  439. 439 (0, 255, 0),
  440. 440 (0, 0, 255),
  441. 441 (255, 255, 0),
  442. 442 (255, 0, 255),
  443. 443 (0, 255, 255),
  444. 444 ]
  445. 445
  446. 446● for i in 0..<detection.boxes.length() {
  447. 447● let box = detection.boxes[i]
  448. 448 let trajectory : Array[(Double, Double)] = [(box.x, box.y)]
  449. 449● let color_idx = i % colors.length()
  450. 450● objects.push(YoloTrackedObject::{
  451. 451 id: i,
  452. 452 class_id: box.class_id,
  453. 453 class_name: box.class_name,
  454. 454 bbox: box,
  455. 455 age: 0,
  456. 456 visible_count: 1,
  457. 457 invisible_count: 0,
  458. 458 velocity_x: 0.0,
  459. 459 velocity_y: 0.0,
  460. 460 trajectory,
  461. 461 color: colors[color_idx],
  462. 462 })
  463. 463 }
  464. 464
  465. 465 objects
  466. 466}
  467. 467
  468. 468///|
  469. 469/// 目标跟踪更新(基于 IoU 匹配)
  470. 470pub fn update_object_tracking(
  471. 471 tracked_objects : Array[YoloTrackedObject],
  472. 472 detection : YoloDetectionResult,
  473. 473 max_age : Int32,
  474. 474) -> Array[YoloTrackedObject] raise @types.LoadError {
  475. 475 // 输入验证
  476. 476● if tracked_objects.length() == 0 {
  477. 477● raise @types.LoadError::DecodeFailed(
  478. 478 "update_object_tracking: 跟踪目标列表不能为空",
  479. 479 )
  480. 480 }
  481. 481 if max_age <= 0 {
  482. 482● raise @types.LoadError::DecodeFailed(
  483. 483 "update_object_tracking: max_age必须大于0",
  484. 484 )
  485. 485 }
  486. 486
  487. 487 let updated : Array[YoloTrackedObject] = []
  488. 488 let matched_detections : Array[Bool] = []
  489. 489● for _ in 0..<detection.boxes.length() {
  490. 490● matched_detections.push(false)
  491. 491 }
  492. 492
  493. 493 // 匹配已有目标
  494. 494 for obj in tracked_objects {
  495. 495● let mut best_iou = 0.0
  496. 496 let mut best_idx = -1
  497. 497
  498. 498● for i in 0..<detection.boxes.length() {
  499. 499● if matched_detections[i] {
  500. 500○ continue
  501. 501 }
  502. 502● let iou = calculate_iou(obj.bbox, detection.boxes[i])
  503. 503 if iou > best_iou && iou > 0.3 {
  504. 504● best_iou = iou
  505. 505 best_idx = i
  506. 506 }
  507. 507 }
  508. 508
  509. 509 if best_idx >= 0 {
  510. 510 // 匹配成功,更新目标
  511. 511● matched_detections[best_idx] = true
  512. 512 let new_box = detection.boxes[best_idx]
  513. 513 let velocity_x = new_box.x - obj.bbox.x
  514. 514 let velocity_y = new_box.y - obj.bbox.y
  515. 515 let mut new_trajectory = obj.trajectory
  516. 516● new_trajectory.push((new_box.x, new_box.y))
  517. 517● if new_trajectory.length() > 50 {
  518. 518○ let trimmed : Array[(Double, Double)] = []
  519. 519○ for i in (new_trajectory.length() - 50)..<new_trajectory.length() {
  520. 520○ trimmed.push(new_trajectory[i])
  521. 521 }
  522. 522 new_trajectory = trimmed
  523. 523 }
  524. 524
  525. 525● updated.push(YoloTrackedObject::{
  526. 526 id: obj.id,
  527. 527 class_id: new_box.class_id,
  528. 528 class_name: new_box.class_name,
  529. 529 bbox: new_box,
  530. 530 age: obj.age + 1,
  531. 531 visible_count: obj.visible_count + 1,
  532. 532 invisible_count: 0,
  533. 533 velocity_x,
  534. 534 velocity_y,
  535. 535 trajectory: new_trajectory,
  536. 536 color: obj.color,
  537. 537 })
  538. 538 // 匹配失败,目标不可见
  539. 539● } else if obj.invisible_count < max_age {
  540. 540● updated.push(YoloTrackedObject::{
  541. 541 id: obj.id,
  542. 542 class_id: obj.class_id,
  543. 543 class_name: obj.class_name,
  544. 544 bbox: obj.bbox,
  545. 545 age: obj.age + 1,
  546. 546 visible_count: obj.visible_count,
  547. 547 invisible_count: obj.invisible_count + 1,
  548. 548 velocity_x: obj.velocity_x,
  549. 549 velocity_y: obj.velocity_y,
  550. 550 trajectory: obj.trajectory,
  551. 551 color: obj.color,
  552. 552 })
  553. 553 }
  554. 554 }
  555. 555
  556. 556 // 添加新目标
  557. 557● let mut next_id = tracked_objects.length()
  558. 558● for i in 0..<detection.boxes.length() {
  559. 559● if !matched_detections[i] {
  560. 560● let box = detection.boxes[i]
  561. 561 let trajectory : Array[(Double, Double)] = [(box.x, box.y)]
  562. 562 let colors = [
  563. 563 (255, 0, 0),
  564. 564 (0, 255, 0),
  565. 565 (0, 0, 255),
  566. 566 (255, 255, 0),
  567. 567 (255, 0, 255),
  568. 568 (0, 255, 255),
  569. 569 ]
  570. 570● updated.push(YoloTrackedObject::{
  571. 571 id: next_id,
  572. 572 class_id: box.class_id,
  573. 573 class_name: box.class_name,
  574. 574 bbox: box,
  575. 575 age: 0,
  576. 576 visible_count: 1,
  577. 577 invisible_count: 0,
  578. 578 velocity_x: 0.0,
  579. 579 velocity_y: 0.0,
  580. 580 trajectory,
  581. 581● color: colors[next_id % colors.length()],
  582. 582 })
  583. 583 next_id += 1
  584. 584 }
  585. 585 }
  586. 586
  587. 587 updated
  588. 588}
  589. 589
  590. 590///|
  591. 591/// 计算检测评估指标
  592. 592pub fn calculate_detection_metrics(
  593. 593 predictions : Array[YoloBoundingBox],
  594. 594 ground_truth : Array[YoloBoundingBox],
  595. 595 iou_threshold : Double,
  596. 596) -> YoloDetectionMetrics raise @types.LoadError {
  597. 597 // 输入验证
  598. 598● if predictions.length() == 0 {
  599. 599● raise @types.LoadError::DecodeFailed(
  600. 600 "calculate_detection_metrics: 预测框列表不能为空",
  601. 601 )
  602. 602 }
  603. 603● if ground_truth.length() == 0 {
  604. 604● raise @types.LoadError::DecodeFailed(
  605. 605 "calculate_detection_metrics: 真实框列表不能为空",
  606. 606 )
  607. 607 }
  608. 608 if iou_threshold < 0.0 || iou_threshold > 1.0 {
  609. 609● raise @types.LoadError::DecodeFailed(
  610. 610 "calculate_detection_metrics: iou_threshold必须在0-1之间",
  611. 611 )
  612. 612 }
  613. 613
  614. 614 let mut tp = 0
  615. 615 let mut fp = 0
  616. 616 let matched_gt : Array[Bool] = []
  617. 617● for _ in 0..<ground_truth.length() {
  618. 618● matched_gt.push(false)
  619. 619 }
  620. 620
  621. 621 // 按置信度排序
  622. 622 let sorted_pred = predictions
  623. 623● for i in 0..<sorted_pred.length() {
  624. 624● for j in 0..<(sorted_pred.length() - i - 1) {
  625. 625● if sorted_pred[j].confidence < sorted_pred[j + 1].confidence {
  626. 626● let temp = sorted_pred[j]
  627. 627 sorted_pred[j] = sorted_pred[j + 1]
  628. 628 sorted_pred[j + 1] = temp
  629. 629 }
  630. 630 }
  631. 631 }
  632. 632
  633. 633 for pred in sorted_pred {
  634. 634● let mut best_iou = 0.0
  635. 635 let mut best_gt_idx = -1
  636. 636
  637. 637● for i in 0..<ground_truth.length() {
  638. 638● if matched_gt[i] {
  639. 639● continue
  640. 640 }
  641. 641● let iou = calculate_iou(pred, ground_truth[i])
  642. 642 if iou > best_iou && pred.class_id == ground_truth[i].class_id {
  643. 643● best_iou = iou
  644. 644 best_gt_idx = i
  645. 645 }
  646. 646 }
  647. 647
  648. 648 if best_gt_idx >= 0 && best_iou >= iou_threshold {
  649. 649● tp += 1
  650. 650 matched_gt[best_gt_idx] = true
  651. 651 } else {
  652. 652● fp += 1
  653. 653 }
  654. 654 }
  655. 655
  656. 656● let false_neg = ground_truth.length() - tp
  657. 657
  658. 658 let precision = if tp + fp > 0 {
  659. 659● tp.to_double() / (tp + fp).to_double()
  660. 660 } else {
  661. 661○ 0.0
  662. 662 }
  663. 663 let recall = if tp + false_neg > 0 {
  664. 664● tp.to_double() / (tp + false_neg).to_double()
  665. 665 } else {
  666. 666○ 0.0
  667. 667 }
  668. 668 let f1 = if precision + recall > 0 {
  669. 669● 2.0 * precision * recall / (precision + recall)
  670. 670 } else {
  671. 671● 0.0
  672. 672 }
  673. 673
  674. 674 YoloDetectionMetrics::{
  675. 675 precision,
  676. 676 recall,
  677. 677 f1_score: f1,
  678. 678 mAP: f1,
  679. 679 mAP50: f1,
  680. 680 mAP50_95: f1 * 0.8,
  681. 681 true_positives: tp,
  682. 682 false_positives: fp,
  683. 683 false_negatives: false_neg,
  684. 684 }
  685. 685}
  686. 686
  687. 687///|
  688. 688/// 生成检测报告
  689. 689pub fn detection_report_to_string(
  690. 690 result : YoloDetectionResult,
  691. 691 metrics : YoloDetectionMetrics,
  692. 692) -> String {
  693. 693● let mut report = "## 目标检测报告\n\n"
  694. 694 report = report + "### 检测结果\n\n"
  695. 695 report = report + "| 指标 | 值 |\n|------|------|\n"
  696. 696 report = report +
  697. 697 "| 检测目标数 | " +
  698. 698● result.num_detections.to_string() +
  699. 699 " |\n"
  700. 700 report = report +
  701. 701 "| 输入尺寸 | " +
  702. 702● result.input_width.to_string() +
  703. 703 "x" +
  704. 704● result.input_height.to_string() +
  705. 705 " |\n"
  706. 706 report = report +
  707. 707 "| 推理耗时 | " +
  708. 708● result.inference_time_ms.to_string() +
  709. 709 "ms |\n\n"
  710. 710
  711. 711● if result.boxes.length() > 0 {
  712. 712● report = report + "### 检测目标列表\n\n"
  713. 713 report = report +
  714. 714 "| ID | 类别 | 置信度 | 位置(X,Y) | 尺寸(WxH) |\n"
  715. 715 report = report + "|----|------|--------|-----------|------------|\n"
  716. 716● for i in 0..<result.boxes.length() {
  717. 717● let box = result.boxes[i]
  718. 718 report = report +
  719. 719 "| " +
  720. 720● i.to_string() +
  721. 721 " | " +
  722. 722 box.class_name +
  723. 723 " | " +
  724. 724● (box.confidence * 100.0).to_string() +
  725. 725 "% | " +
  726. 726● box.x.to_string() +
  727. 727 "," +
  728. 728● box.y.to_string() +
  729. 729 " | " +
  730. 730● box.width.to_string() +
  731. 731 "x" +
  732. 732● box.height.to_string() +
  733. 733 " |\n"
  734. 734 }
  735. 735 }
  736. 736
  737. 737 report = report + "\n### 评估指标\n\n"
  738. 738 report = report + "| 指标 | 值 |\n|------|------|\n"
  739. 739 report = report +
  740. 740 "| Precision | " +
  741. 741● (metrics.precision * 100.0).to_string() +
  742. 742 "% |\n"
  743. 743 report = report +
  744. 744 "| Recall | " +
  745. 745● (metrics.recall * 100.0).to_string() +
  746. 746 "% |\n"
  747. 747 report = report +
  748. 748 "| F1 Score | " +
  749. 749● (metrics.f1_score * 100.0).to_string() +
  750. 750 "% |\n"
  751. 751 report = report +
  752. 752 "| mAP@0.5 | " +
  753. 753● (metrics.mAP50 * 100.0).to_string() +
  754. 754 "% |\n"
  755. 755 report = report +
  756. 756 "| mAP@0.5:0.95 | " +
  757. 757● (metrics.mAP50_95 * 100.0).to_string() +
  758. 758 "% |\n"
  759. 759● report = report + "| TP | " + metrics.true_positives.to_string() + " |\n"
  760. 760● report = report + "| FP | " + metrics.false_positives.to_string() + " |\n"
  761. 761● report = report + "| FN | " + metrics.false_negatives.to_string() + " |\n"
  762. 762
  763. 763 report
  764. 764}