image.process\segment\advanced_segmentation.mbt

96.8% · 243 / 251 points · 944 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/// # 高级分割 advanced segmentation
  3. 3///
  4. 4/// 图像处理算法模块
  5. 5/// 图像处理算法模块 Image processing algorithm module
  6. 6// 图像分割增强(v17.0.0)
  7. 7// 语义分割、实例分割、超像素分割、分水岭算法、K-Means 聚类分割、GrabCut
  8. 8
  9. 9///|
  10. 10/// 分割标签
  11. 11pub(all) struct SegmentationLabel {
  12. 12 id : Int32
  13. 13 name : String
  14. 14 color : (Int32, Int32, Int32)
  15. 15 pixel_count : Int32
  16. 16}
  17. 17
  18. 18///|
  19. 19/// 语义分割结果
  20. 20pub(all) struct SemanticSegmentationResult {
  21. 21 width : Int32
  22. 22 height : Int32
  23. 23 labels : Array[Int32] // 每个像素的标签 ID
  24. 24 label_info : Array[SegmentationLabel]
  25. 25 num_classes : Int32
  26. 26 inference_time_ms : Double
  27. 27}
  28. 28
  29. 29///|
  30. 30/// 实例分割结果
  31. 31pub(all) struct InstanceSegmentationResult {
  32. 32 width : Int32
  33. 33 height : Int32
  34. 34 masks : Array[Array[Bool]] // 每个实例的掩码
  35. 35 boxes : Array[(Int32, Int32, Int32, Int32)] // 每个实例的边界框 (x, y, w, h)
  36. 36 class_ids : Array[Int32]
  37. 37 class_names : Array[String]
  38. 38 confidences : Array[Double]
  39. 39 num_instances : Int32
  40. 40}
  41. 41
  42. 42///|
  43. 43/// 超像素
  44. 44pub(all) struct Superpixel {
  45. 45 id : Int32
  46. 46 center_x : Double
  47. 47 center_y : Double
  48. 48 size : Int32
  49. 49 mean_color : Double
  50. 50 label : Int32
  51. 51}
  52. 52
  53. 53///|
  54. 54/// 超像素分割结果
  55. 55pub(all) struct SuperpixelResultAdv {
  56. 56 width : Int32
  57. 57 height : Int32
  58. 58 labels : Array[Int32] // 每个像素的超像素 ID
  59. 59 superpixels : Array[Superpixel]
  60. 60 num_superpixels : Int32
  61. 61}
  62. 62
  63. 63///|
  64. 64/// 分水岭分割配置
  65. 65pub(all) struct WatershedConfigAdv {
  66. 66 min_region_size : Int32
  67. 67 max_regions : Int32
  68. 68 use_markers : Bool
  69. 69 connectivity : Int32 // 4 或 8
  70. 70}
  71. 71
  72. 72///|
  73. 73/// K-Means 分割配置
  74. 74pub(all) struct KMeansConfig {
  75. 75 num_clusters : Int32
  76. 76 max_iterations : Int32
  77. 77 tolerance : Double
  78. 78 use_color_space : Bool
  79. 79 random_seed : Int32
  80. 80}
  81. 81
  82. 82///|
  83. 83/// GrabCut 配置
  84. 84pub(all) struct GrabCutConfig {
  85. 85 num_iterations : Int32
  86. 86 gamma : Double
  87. 87 use_gmm : Bool
  88. 88}
  89. 89
  90. 90///|
  91. 91/// 分割评估指标
  92. 92pub(all) struct SegmentationMetrics {
  93. 93 pixel_accuracy : Double
  94. 94 mean_iou : Double
  95. 95 mean_accuracy : Double
  96. 96 frequency_weighted_iou : Double
  97. 97 dice_coefficient : Double
  98. 98 true_positives : Int32
  99. 99 false_positives : Int32
  100. 100 false_negatives : Int32
  101. 101}
  102. 102
  103. 103///|
  104. 104/// 创建默认分水岭配置
  105. 105pub fn create_default_watershed_config() -> WatershedConfigAdv {
  106. 106● WatershedConfigAdv::{
  107. 107 min_region_size: 50,
  108. 108 max_regions: 100,
  109. 109 use_markers: true,
  110. 110 connectivity: 8,
  111. 111 }
  112. 112}
  113. 113
  114. 114///|
  115. 115/// 创建默认 K-Means 配置
  116. 116pub fn create_default_kmeans_config() -> KMeansConfig {
  117. 117● KMeansConfig::{
  118. 118 num_clusters: 5,
  119. 119 max_iterations: 100,
  120. 120 tolerance: 0.001,
  121. 121 use_color_space: true,
  122. 122 random_seed: 42,
  123. 123 }
  124. 124}
  125. 125
  126. 126///|
  127. 127/// 创建默认 GrabCut 配置
  128. 128pub fn create_default_grabcut_config() -> GrabCutConfig {
  129. 129● GrabCutConfig::{ num_iterations: 5, gamma: 50.0, use_gmm: true, }
  130. 130}
  131. 131
  132. 132///|
  133. 133/// 简单阈值分割
  134. 134pub fn threshold_segmentation(
  135. 135 img : @types.Image,
  136. 136 threshold : Double,
  137. 137) -> SemanticSegmentationResult raise @types.LoadError {
  138. 138 // 输入验证
  139. 139● if img.width <= 0 || img.height <= 0 {
  140. 140● raise @types.LoadError::DecodeFailed(
  141. 141 "threshold_segmentation: 图像尺寸必须大于0",
  142. 142 )
  143. 143 }
  144. 144 if img.channels < 1 || img.channels > 4 {
  145. 145● raise @types.LoadError::DecodeFailed(
  146. 146 "threshold_segmentation: 通道数必须在1-4之间",
  147. 147 )
  148. 148 }
  149. 149 let expected_size = img.width * img.height * img.channels
  150. 150● if img.data.length() != expected_size {
  151. 151● raise @types.LoadError::DecodeFailed(
  152. 152 "threshold_segmentation: 数据大小不匹配",
  153. 153 )
  154. 154 }
  155. 155 let w = img.width
  156. 156 let h = img.height
  157. 157 let labels : Array[Int32] = []
  158. 158 let mut fg_count = 0
  159. 159 let mut bg_count = 0
  160. 160
  161. 161 for y in 0..<h {
  162. 162● for x in 0..<w {
  163. 163● let pixel = img.data[y * w + x].to_double()
  164. 164 if pixel > threshold {
  165. 165● labels.push(1)
  166. 166 fg_count += 1
  167. 167 } else {
  168. 168● labels.push(0)
  169. 169 bg_count += 1
  170. 170 }
  171. 171 }
  172. 172 }
  173. 173
  174. 174 let label_info : Array[SegmentationLabel] = [
  175. 175 SegmentationLabel::{
  176. 176 id: 0,
  177. 177 name: "background",
  178. 178 color: (0, 0, 0),
  179. 179 pixel_count: bg_count,
  180. 180 },
  181. 181 SegmentationLabel::{
  182. 182 id: 1,
  183. 183 name: "foreground",
  184. 184 color: (255, 255, 255),
  185. 185 pixel_count: fg_count,
  186. 186 },
  187. 187 ]
  188. 188
  189. 189 SemanticSegmentationResult::{
  190. 190 width: w,
  191. 191 height: h,
  192. 192 labels,
  193. 193 label_info,
  194. 194 num_classes: 2,
  195. 195 inference_time_ms: 0.0,
  196. 196 }
  197. 197}
  198. 198
  199. 199///|
  200. 200/// Otsu 自动阈值分割
  201. 201pub fn otsu_threshold_value(
  202. 202 img : @types.Image,
  203. 203) -> Double raise @types.LoadError {
  204. 204 // 输入验证
  205. 205● if img.width <= 0 || img.height <= 0 {
  206. 206● raise @types.LoadError::DecodeFailed(
  207. 207 "otsu_threshold_value: 图像尺寸必须大于0",
  208. 208 )
  209. 209 }
  210. 210 if img.channels < 1 || img.channels > 4 {
  211. 211● raise @types.LoadError::DecodeFailed(
  212. 212 "otsu_threshold_value: 通道数必须在1-4之间",
  213. 213 )
  214. 214 }
  215. 215 let expected_size = img.width * img.height * img.channels
  216. 216● if img.data.length() != expected_size {
  217. 217● raise @types.LoadError::DecodeFailed(
  218. 218 "otsu_threshold_value: 数据大小不匹配",
  219. 219 )
  220. 220 }
  221. 221 let w = img.width
  222. 222 let h = img.height
  223. 223 let histogram : Array[Int32] = []
  224. 224 for _ in 0..<256 {
  225. 225● histogram.push(0)
  226. 226 }
  227. 227
  228. 228 for y in 0..<h {
  229. 229● for x in 0..<w {
  230. 230● let pixel = img.data[y * w + x].to_int()
  231. 231 histogram[pixel] += 1
  232. 232 }
  233. 233 }
  234. 234
  235. 235 let total = w * h
  236. 236 let mut sum = 0.0
  237. 237 for i in 0..<256 {
  238. 238● sum += i.to_double() * histogram[i].to_double()
  239. 239 }
  240. 240
  241. 241 let mut sum_b = 0.0
  242. 242 let mut w_b = 0
  243. 243 let mut max_variance = 0.0
  244. 244 let mut threshold = 128.0
  245. 245
  246. 246 for i in 0..<256 {
  247. 247● w_b += histogram[i]
  248. 248 if w_b == 0 {
  249. 249○ continue
  250. 250 }
  251. 251 let w_f = total - w_b
  252. 252 if w_f == 0 {
  253. 253● break
  254. 254 }
  255. 255● sum_b += i.to_double() * histogram[i].to_double()
  256. 256● let m_b = sum_b / w_b.to_double()
  257. 257● let m_f = (sum - sum_b) / w_f.to_double()
  258. 258● let variance = w_b.to_double() * w_f.to_double() * (m_b - m_f) * (m_b - m_f)
  259. 259 if variance > max_variance {
  260. 260● max_variance = variance
  261. 261● threshold = i.to_double()
  262. 262 }
  263. 263 }
  264. 264
  265. 265 threshold
  266. 266}
  267. 267
  268. 268///|
  269. 269/// K-Means 聚类分割
  270. 270pub fn kmeans_segmentation(
  271. 271 img : @types.Image,
  272. 272 config : KMeansConfig,
  273. 273) -> SemanticSegmentationResult raise @types.LoadError {
  274. 274 // 输入验证
  275. 275● if img.width <= 0 || img.height <= 0 {
  276. 276● raise @types.LoadError::DecodeFailed(
  277. 277 "kmeans_segmentation: 图像尺寸必须大于0",
  278. 278 )
  279. 279 }
  280. 280 if img.channels < 1 || img.channels > 4 {
  281. 281● raise @types.LoadError::DecodeFailed(
  282. 282 "kmeans_segmentation: 通道数必须在1-4之间",
  283. 283 )
  284. 284 }
  285. 285 let expected_size = img.width * img.height * img.channels
  286. 286● if img.data.length() != expected_size {
  287. 287● raise @types.LoadError::DecodeFailed(
  288. 288 "kmeans_segmentation: 数据大小不匹配",
  289. 289 )
  290. 290 }
  291. 291 let w = img.width
  292. 292 let h = img.height
  293. 293 let k = config.num_clusters
  294. 294 let total = w * h
  295. 295
  296. 296 // 初始化聚类中心
  297. 297 let centers : Array[Double] = []
  298. 298 for i in 0..<k {
  299. 299● centers.push(i.to_double() * 255.0 / k.to_double() + 128.0 / k.to_double())
  300. 300 }
  301. 301
  302. 302 let labels : Array[Int32] = []
  303. 303 for _ in 0..<total {
  304. 304● labels.push(0)
  305. 305 }
  306. 306
  307. 307 // K-Means 迭代
  308. 308 for _ in 0..<config.max_iterations {
  309. 309 // 分配标签
  310. 310● for i in 0..<total {
  311. 311● let pixel = img.data[i].to_double()
  312. 312 let mut min_dist = 1000000.0
  313. 313 let mut best_cluster = 0
  314. 314 for c in 0..<k {
  315. 315● let dist = (pixel - centers[c]) * (pixel - centers[c])
  316. 316 if dist < min_dist {
  317. 317● min_dist = dist
  318. 318 best_cluster = c
  319. 319 }
  320. 320 }
  321. 321 labels[i] = best_cluster
  322. 322 }
  323. 323
  324. 324 // 更新聚类中心
  325. 325 let sums : Array[Double] = []
  326. 326 let counts : Array[Int32] = []
  327. 327 for _ in 0..<k {
  328. 328● sums.push(0.0)
  329. 329● counts.push(0)
  330. 330 }
  331. 331 for i in 0..<total {
  332. 332● let pixel = img.data[i].to_double()
  333. 333 let cluster = labels[i]
  334. 334 sums[cluster] += pixel
  335. 335 counts[cluster] += 1
  336. 336 }
  337. 337 for c in 0..<k {
  338. 338● if counts[c] > 0 {
  339. 339● centers[c] = sums[c] / counts[c].to_double()
  340. 340 }
  341. 341 }
  342. 342 }
  343. 343
  344. 344 // 统计每个类别的像素数
  345. 345 let pixel_counts : Array[Int32] = []
  346. 346 for _ in 0..<k {
  347. 347● pixel_counts.push(0)
  348. 348 }
  349. 349 for i in 0..<total {
  350. 350● pixel_counts[labels[i]] += 1
  351. 351 }
  352. 352
  353. 353 let label_info : Array[SegmentationLabel] = []
  354. 354 let colors = [
  355. 355 (255, 0, 0),
  356. 356 (0, 255, 0),
  357. 357 (0, 0, 255),
  358. 358 (255, 255, 0),
  359. 359 (255, 0, 255),
  360. 360 (0, 255, 255),
  361. 361 (128, 0, 0),
  362. 362 (0, 128, 0),
  363. 363 (0, 0, 128),
  364. 364 (128, 128, 128),
  365. 365 ]
  366. 366 for c in 0..<k {
  367. 367● label_info.push(SegmentationLabel::{
  368. 368 id: c,
  369. 369● name: "class_" + c.to_string(),
  370. 370● color: colors[c % colors.length()],
  371. 371 pixel_count: pixel_counts[c],
  372. 372 })
  373. 373 }
  374. 374
  375. 375 SemanticSegmentationResult::{
  376. 376 width: w,
  377. 377 height: h,
  378. 378 labels,
  379. 379 label_info,
  380. 380 num_classes: k,
  381. 381 inference_time_ms: 0.0,
  382. 382 }
  383. 383}
  384. 384
  385. 385///|
  386. 386/// 超像素分割(简化版 SLIC)
  387. 387pub fn superpixel_segmentation(
  388. 388 img : @types.Image,
  389. 389 num_superpixels : Int32,
  390. 390) -> SuperpixelResultAdv raise @types.LoadError {
  391. 391 // 输入验证
  392. 392● if img.width <= 0 || img.height <= 0 {
  393. 393● raise @types.LoadError::DecodeFailed(
  394. 394 "superpixel_segmentation: 图像尺寸必须大于0",
  395. 395 )
  396. 396 }
  397. 397 if img.channels < 1 || img.channels > 4 {
  398. 398● raise @types.LoadError::DecodeFailed(
  399. 399 "superpixel_segmentation: 通道数必须在1-4之间",
  400. 400 )
  401. 401 }
  402. 402 let expected_size = img.width * img.height * img.channels
  403. 403● if img.data.length() != expected_size {
  404. 404● raise @types.LoadError::DecodeFailed(
  405. 405 "superpixel_segmentation: 数据大小不匹配",
  406. 406 )
  407. 407 }
  408. 408 if num_superpixels <= 0 {
  409. 409● raise @types.LoadError::DecodeFailed(
  410. 410 "superpixel_segmentation: num_superpixels 必须 >= 1",
  411. 411 )
  412. 412 }
  413. 413 let w = img.width
  414. 414 let h = img.height
  415. 415 let total = w * h
  416. 416 // 超像素数超过像素数时按像素数截断;否则 sqrt(total/num) 会取整成 0 →
  417. 417 // 旧实现随后 `w / step` 直接除零 panic、`cx += 0` 死循环(S22 修复)
  418. 418● let n_super = if num_superpixels > total { total } else { num_superpixels }
  419. 419● let mut step = (total.to_double() / n_super.to_double()).sqrt().to_int()
  420. 420 if step < 1 {
  421. 421○ step = 1
  422. 422 }
  423. 423
  424. 424 let labels : Array[Int32] = []
  425. 425 for _ in 0..<total {
  426. 426● labels.push(-1)
  427. 427 }
  428. 428
  429. 429 // 初始化超像素中心
  430. 430 let centers_x : Array[Double] = []
  431. 431 let centers_y : Array[Double] = []
  432. 432 let centers_color : Array[Double] = []
  433. 433 let mut sp_id = 0
  434. 434 let mut cols = 1
  435. 435 let mut cy = step / 2
  436. 436 while cy < h {
  437. 437● let mut cx = step / 2
  438. 438 let mut row_cols = 0
  439. 439 while cx < w {
  440. 440● centers_x.push(cx.to_double())
  441. 441● centers_y.push(cy.to_double())
  442. 442● centers_color.push(img.data[cy * w + cx].to_double())
  443. 443 sp_id += 1
  444. 444 row_cols += 1
  445. 445 cx += step
  446. 446 }
  447. 447 if row_cols > cols {
  448. 448● cols = row_cols
  449. 449 }
  450. 450 cy += step
  451. 451 }
  452. 452
  453. 453 // 简化的 SLIC 迭代
  454. 454 for _ in 0..<5 {
  455. 455● for sp in 0..<sp_id {
  456. 456● let cx = centers_x[sp].to_int()
  457. 457● let cy = centers_y[sp].to_int()
  458. 458 for y in (cy - step)..<(cy + step) {
  459. 459● if y < 0 || y >= h {
  460. 460● continue
  461. 461 }
  462. 462 for x in (cx - step)..<(cx + step) {
  463. 463● if x < 0 || x >= w {
  464. 464● continue
  465. 465 }
  466. 466 let idx = y * w + x
  467. 467● let pixel = img.data[idx].to_double()
  468. 468● let color_dist = (pixel - centers_color[sp]).abs()
  469. 469 let spatial_dist = (
  470. 470● (x.to_double() - centers_x[sp]).abs() +
  471. 471● (y.to_double() - centers_y[sp]).abs()
  472. 472 ) /
  473. 473● step.to_double()
  474. 474 let dist = color_dist + spatial_dist * 10.0
  475. 475 if labels[idx] == -1 || dist < 50.0 {
  476. 476● labels[idx] = sp
  477. 477 }
  478. 478 }
  479. 479 }
  480. 480 }
  481. 481 }
  482. 482
  483. 483 // 兜底:简化 SLIC 的距离阈值会剪掉部分像素,未标注的按「网格归属」补上,
  484. 484 // 保证 labels 全部 >= 0(下游按 label 统计时不会出现 -1 空洞)
  485. 485 for y in 0..<h {
  486. 486● for x in 0..<w {
  487. 487● let idx = y * w + x
  488. 488 if labels[idx] < 0 {
  489. 489○ let gid = y / step * cols + x / step
  490. 490○ labels[idx] = if gid < sp_id { gid } else { sp_id - 1 }
  491. 491 }
  492. 492 }
  493. 493 }
  494. 494
  495. 495 // 计算超像素信息
  496. 496 let superpixels : Array[Superpixel] = []
  497. 497 for sp in 0..<sp_id {
  498. 498● let mut sum_x = 0.0
  499. 499 let mut sum_y = 0.0
  500. 500 let mut sum_color = 0.0
  501. 501 let mut count = 0
  502. 502 for y in 0..<h {
  503. 503● for x in 0..<w {
  504. 504● if labels[y * w + x] == sp {
  505. 505● sum_x += x.to_double()
  506. 506● sum_y += y.to_double()
  507. 507● sum_color += img.data[y * w + x].to_double()
  508. 508 count += 1
  509. 509 }
  510. 510 }
  511. 511 }
  512. 512 if count > 0 {
  513. 513● superpixels.push(Superpixel::{
  514. 514 id: sp,
  515. 515● center_x: sum_x / count.to_double(),
  516. 516● center_y: sum_y / count.to_double(),
  517. 517 size: count,
  518. 518● mean_color: sum_color / count.to_double(),
  519. 519 label: sp,
  520. 520 })
  521. 521 }
  522. 522 }
  523. 523
  524. 524 SuperpixelResultAdv::{
  525. 525 width: w,
  526. 526 height: h,
  527. 527 labels,
  528. 528 superpixels,
  529. 529● num_superpixels: superpixels.length(),
  530. 530 }
  531. 531}
  532. 532
  533. 533///|
  534. 534/// 分水岭分割(简化版)
  535. 535pub fn watershed_segmentation(
  536. 536 img : @types.Image,
  537. 537 config : WatershedConfigAdv,
  538. 538) -> SemanticSegmentationResult raise @types.LoadError {
  539. 539 // 输入验证
  540. 540● if img.width <= 0 || img.height <= 0 {
  541. 541● raise @types.LoadError::DecodeFailed(
  542. 542 "watershed_segmentation: 图像尺寸必须大于0",
  543. 543 )
  544. 544 }
  545. 545 if img.channels < 1 || img.channels > 4 {
  546. 546● raise @types.LoadError::DecodeFailed(
  547. 547 "watershed_segmentation: 通道数必须在1-4之间",
  548. 548 )
  549. 549 }
  550. 550 let expected_size = img.width * img.height * img.channels
  551. 551● if img.data.length() != expected_size {
  552. 552● raise @types.LoadError::DecodeFailed(
  553. 553 "watershed_segmentation: 数据大小不匹配",
  554. 554 )
  555. 555 }
  556. 556 let w = img.width
  557. 557 let h = img.height
  558. 558 let total = w * h
  559. 559
  560. 560 // 简化版:基于梯度的区域生长
  561. 561 let labels : Array[Int32] = []
  562. 562 for _ in 0..<total {
  563. 563● labels.push(-1)
  564. 564 }
  565. 565
  566. 566 // 找局部最小值作为种子点
  567. 567 let mut region_id = 0
  568. 568 for y in 1..<(h - 1) {
  569. 569● for x in 1..<(w - 1) {
  570. 570● let idx = y * w + x
  571. 571● let pixel = img.data[idx].to_double()
  572. 572 let mut is_min = true
  573. 573 for dy in -1..<2 {
  574. 574● for dx in -1..<2 {
  575. 575● if dx == 0 && dy == 0 {
  576. 576● continue
  577. 577 }
  578. 578● let neighbor = img.data[(y + dy) * w + (x + dx)].to_double()
  579. 579 if neighbor < pixel {
  580. 580● is_min = false
  581. 581 }
  582. 582 }
  583. 583 }
  584. 584 if is_min && labels[idx] == -1 {
  585. 585 // 区域生长
  586. 586● let queue_x : Array[Int32] = [x]
  587. 587 let queue_y : Array[Int32] = [y]
  588. 588 labels[idx] = region_id
  589. 589 let mut queue_idx = 0
  590. 590● while queue_idx < queue_x.length() {
  591. 591● let cx = queue_x[queue_idx]
  592. 592 let cy = queue_y[queue_idx]
  593. 593 queue_idx += 1
  594. 594 for dy in -1..<2 {
  595. 595● for dx in -1..<2 {
  596. 596● if dx == 0 && dy == 0 {
  597. 597● continue
  598. 598 }
  599. 599 let nx = cx + dx
  600. 600 let ny = cy + dy
  601. 601 if nx < 0 || nx >= w || ny < 0 || ny >= h {
  602. 602● continue
  603. 603 }
  604. 604 let nidx = ny * w + nx
  605. 605 if labels[nidx] == -1 {
  606. 606● let npixel = img.data[nidx].to_double()
  607. 607 if npixel < pixel + 30.0 {
  608. 608● labels[nidx] = region_id
  609. 609● queue_x.push(nx)
  610. 610● queue_y.push(ny)
  611. 611 }
  612. 612 }
  613. 613 }
  614. 614 }
  615. 615 }
  616. 616 region_id += 1
  617. 617 if region_id >= config.max_regions {
  618. 618○ break
  619. 619 }
  620. 620 }
  621. 621 }
  622. 622 if region_id >= config.max_regions {
  623. 623○ break
  624. 624 }
  625. 625 }
  626. 626
  627. 627 // 未标记的像素归为背景
  628. 628 for i in 0..<total {
  629. 629● if labels[i] == -1 {
  630. 630● labels[i] = region_id // 背景
  631. 631 }
  632. 632 }
  633. 633
  634. 634 // 统计
  635. 635 let pixel_counts : Array[Int32] = []
  636. 636 for _ in 0..<(region_id + 1) {
  637. 637● pixel_counts.push(0)
  638. 638 }
  639. 639 for i in 0..<total {
  640. 640● pixel_counts[labels[i]] += 1
  641. 641 }
  642. 642
  643. 643 let label_info : Array[SegmentationLabel] = []
  644. 644 for r in 0..<(region_id + 1) {
  645. 645● let name = if r == region_id {
  646. 646● "background"
  647. 647 } else {
  648. 648● "region_" + r.to_string()
  649. 649 }
  650. 650● label_info.push(SegmentationLabel::{
  651. 651 id: r,
  652. 652 name,
  653. 653 color: (r * 37 % 256, r * 73 % 256, r * 113 % 256),
  654. 654 pixel_count: pixel_counts[r],
  655. 655 })
  656. 656 }
  657. 657
  658. 658 SemanticSegmentationResult::{
  659. 659 width: w,
  660. 660 height: h,
  661. 661 labels,
  662. 662 label_info,
  663. 663 num_classes: region_id + 1,
  664. 664 inference_time_ms: 0.0,
  665. 665 }
  666. 666}
  667. 667
  668. 668///|
  669. 669/// GrabCut 前景提取(简化版)
  670. 670pub fn grabcut_segmentation(
  671. 671 img : @types.Image,
  672. 672 rect_x : Int32,
  673. 673 rect_y : Int32,
  674. 674 rect_w : Int32,
  675. 675 rect_h : Int32,
  676. 676 config : GrabCutConfig,
  677. 677) -> SemanticSegmentationResult raise @types.LoadError {
  678. 678 // 输入验证
  679. 679● if img.width <= 0 || img.height <= 0 {
  680. 680● raise @types.LoadError::DecodeFailed(
  681. 681 "grabcut_segmentation: 图像尺寸必须大于0",
  682. 682 )
  683. 683 }
  684. 684 if img.channels < 1 || img.channels > 4 {
  685. 685● raise @types.LoadError::DecodeFailed(
  686. 686 "grabcut_segmentation: 通道数必须在1-4之间",
  687. 687 )
  688. 688 }
  689. 689 let expected_size = img.width * img.height * img.channels
  690. 690● if img.data.length() != expected_size {
  691. 691● raise @types.LoadError::DecodeFailed(
  692. 692 "grabcut_segmentation: 数据大小不匹配",
  693. 693 )
  694. 694 }
  695. 695 let w = img.width
  696. 696 let h = img.height
  697. 697 let total = w * h
  698. 698 let labels : Array[Int32] = []
  699. 699
  700. 700 // 初始化:矩形内为可能前景,外为背景
  701. 701 for y in 0..<h {
  702. 702● for x in 0..<w {
  703. 703● if x >= rect_x &&
  704. 704 x < rect_x + rect_w &&
  705. 705 y >= rect_y &&
  706. 706 y < rect_y + rect_h {
  707. 707● labels.push(1) // 可能前景
  708. 708 } else {
  709. 709● labels.push(0) // 背景
  710. 710 }
  711. 711 }
  712. 712 }
  713. 713
  714. 714 // 简化迭代:基于颜色相似度的前景/背景分类
  715. 715 for _ in 0..<config.num_iterations {
  716. 716 // 计算前景和背景的平均颜色
  717. 717● let mut fg_sum = 0.0
  718. 718 let mut fg_count = 0
  719. 719 let mut bg_sum = 0.0
  720. 720 let mut bg_count = 0
  721. 721 for i in 0..<total {
  722. 722● let pixel = img.data[i].to_double()
  723. 723 if labels[i] == 1 {
  724. 724● fg_sum += pixel
  725. 725 fg_count += 1
  726. 726 } else {
  727. 727● bg_sum += pixel
  728. 728 bg_count += 1
  729. 729 }
  730. 730 }
  731. 731 let fg_mean = if fg_count > 0 {
  732. 732● fg_sum / fg_count.to_double()
  733. 733 } else {
  734. 734● 128.0
  735. 735 }
  736. 736 let bg_mean = if bg_count > 0 {
  737. 737● bg_sum / bg_count.to_double()
  738. 738 } else {
  739. 739● 128.0
  740. 740 }
  741. 741
  742. 742 // 重新分类
  743. 743 for i in 0..<total {
  744. 744● let pixel = img.data[i].to_double()
  745. 745● let fg_dist = (pixel - fg_mean).abs()
  746. 746● let bg_dist = (pixel - bg_mean).abs()
  747. 747 if fg_dist < bg_dist {
  748. 748● labels[i] = 1
  749. 749 } else {
  750. 750● labels[i] = 0
  751. 751 }
  752. 752 }
  753. 753 }
  754. 754
  755. 755 // 统计
  756. 756 let mut fg_count = 0
  757. 757 let mut bg_count = 0
  758. 758 for i in 0..<total {
  759. 759● if labels[i] == 1 {
  760. 760● fg_count += 1
  761. 761 } else {
  762. 762● bg_count += 1
  763. 763 }
  764. 764 }
  765. 765
  766. 766 let label_info : Array[SegmentationLabel] = [
  767. 767 SegmentationLabel::{
  768. 768 id: 0,
  769. 769 name: "background",
  770. 770 color: (0, 0, 0),
  771. 771 pixel_count: bg_count,
  772. 772 },
  773. 773 SegmentationLabel::{
  774. 774 id: 1,
  775. 775 name: "foreground",
  776. 776 color: (255, 255, 255),
  777. 777 pixel_count: fg_count,
  778. 778 },
  779. 779 ]
  780. 780
  781. 781 SemanticSegmentationResult::{
  782. 782 width: w,
  783. 783 height: h,
  784. 784 labels,
  785. 785 label_info,
  786. 786 num_classes: 2,
  787. 787 inference_time_ms: 0.0,
  788. 788 }
  789. 789}
  790. 790
  791. 791///|
  792. 792/// 计算分割评估指标
  793. 793pub fn calculate_segmentation_metrics(
  794. 794 prediction : Array[Int32],
  795. 795 ground_truth : Array[Int32],
  796. 796 num_classes : Int32,
  797. 797) -> SegmentationMetrics {
  798. 798● ignore(num_classes)
  799. 799● let total = prediction.length()
  800. 800 let mut tp = 0
  801. 801 let mut fp = 0
  802. 802 let mut false_neg = 0
  803. 803 let mut correct = 0
  804. 804
  805. 805 for i in 0..<total {
  806. 806● if prediction[i] == ground_truth[i] {
  807. 807● correct += 1
  808. 808 }
  809. 809 if prediction[i] == 1 && ground_truth[i] == 1 {
  810. 810● tp += 1
  811. 811● } else if prediction[i] == 1 && ground_truth[i] == 0 {
  812. 812● fp += 1
  813. 813● } else if prediction[i] == 0 && ground_truth[i] == 1 {
  814. 814● false_neg += 1
  815. 815 }
  816. 816 }
  817. 817
  818. 818 let pixel_accuracy = if total > 0 {
  819. 819● correct.to_double() / total.to_double()
  820. 820 } else {
  821. 821● 0.0
  822. 822 }
  823. 823 let iou = if tp + fp + false_neg > 0 {
  824. 824● tp.to_double() / (tp + fp + false_neg).to_double()
  825. 825 } else {
  826. 826● 0.0
  827. 827 }
  828. 828 let dice = if 2 * tp + fp + false_neg > 0 {
  829. 829● (2 * tp).to_double() / (2 * tp + fp + false_neg).to_double()
  830. 830 } else {
  831. 831● 0.0
  832. 832 }
  833. 833
  834. 834 SegmentationMetrics::{
  835. 835 pixel_accuracy,
  836. 836 mean_iou: iou,
  837. 837 mean_accuracy: pixel_accuracy,
  838. 838 frequency_weighted_iou: iou,
  839. 839 dice_coefficient: dice,
  840. 840 true_positives: tp,
  841. 841 false_positives: fp,
  842. 842 false_negatives: false_neg,
  843. 843 }
  844. 844}
  845. 845
  846. 846///|
  847. 847/// 生成分割可视化图像
  848. 848pub fn segmentation_to_image(
  849. 849 result : SemanticSegmentationResult,
  850. 850) -> @types.Image {
  851. 851● let w = result.width
  852. 852 let h = result.height
  853. 853 let out : Array[Byte] = []
  854. 854 for i in 0..<(w * h) {
  855. 855● let label = result.labels[i]
  856. 856 let mut color = 0
  857. 857 for info in result.label_info {
  858. 858● if info.id == label {
  859. 859● color = (info.color.0 + info.color.1 + info.color.2) / 3
  860. 860 }
  861. 861 }
  862. 862● out.push(if color > 127 { b'\xFF' } else { b'\x00' })
  863. 863 }
  864. 864 @types.Image::{
  865. 865 width: w,
  866. 866 height: h,
  867. 867 channels: 1,
  868. 868● data: Bytes::from_array(out),
  869. 869 }
  870. 870}
  871. 871
  872. 872///|
  873. 873/// 生成分割报告
  874. 874pub fn segmentation_report_to_string(
  875. 875 result : SemanticSegmentationResult,
  876. 876 metrics : SegmentationMetrics,
  877. 877) -> String {
  878. 878● let mut report = "## 图像分割报告\n\n"
  879. 879 report = report + "### 分割结果\n\n"
  880. 880 report = report + "| 指标 | 值 |\n|------|------|\n"
  881. 881 report = report +
  882. 882 "| 图像尺寸 | " +
  883. 883● result.width.to_string() +
  884. 884 "x" +
  885. 885● result.height.to_string() +
  886. 886 " |\n"
  887. 887● report = report + "| 类别数 | " + result.num_classes.to_string() + " |\n"
  888. 888 report = report +
  889. 889 "| 推理耗时 | " +
  890. 890● result.inference_time_ms.to_string() +
  891. 891 "ms |\n\n"
  892. 892
  893. 893 report = report + "### 类别统计\n\n"
  894. 894 report = report + "| ID | 名称 | 颜色(RGB) | 像素数 | 占比 |\n"
  895. 895 report = report + "|----|------|-----------|--------|------|\n"
  896. 896 let total = result.width * result.height
  897. 897 for info in result.label_info {
  898. 898● let ratio = if total > 0 {
  899. 899● info.pixel_count.to_double() / total.to_double() * 100.0
  900. 900 } else {
  901. 901○ 0.0
  902. 902 }
  903. 903 report = report +
  904. 904 "| " +
  905. 905● info.id.to_string() +
  906. 906 " | " +
  907. 907 info.name +
  908. 908 " | " +
  909. 909● info.color.0.to_string() +
  910. 910 "," +
  911. 911● info.color.1.to_string() +
  912. 912 "," +
  913. 913● info.color.2.to_string() +
  914. 914 " | " +
  915. 915● info.pixel_count.to_string() +
  916. 916 " | " +
  917. 917● ratio.to_string() +
  918. 918 "% |\n"
  919. 919 }
  920. 920
  921. 921 report = report + "\n### 评估指标\n\n"
  922. 922 report = report + "| 指标 | 值 |\n|------|------|\n"
  923. 923 report = report +
  924. 924 "| Pixel Accuracy | " +
  925. 925● (metrics.pixel_accuracy * 100.0).to_string() +
  926. 926 "% |\n"
  927. 927 report = report +
  928. 928 "| Mean IoU | " +
  929. 929● (metrics.mean_iou * 100.0).to_string() +
  930. 930 "% |\n"
  931. 931 report = report +
  932. 932 "| Mean Accuracy | " +
  933. 933● (metrics.mean_accuracy * 100.0).to_string() +
  934. 934 "% |\n"
  935. 935 report = report +
  936. 936 "| Dice Coefficient | " +
  937. 937● (metrics.dice_coefficient * 100.0).to_string() +
  938. 938 "% |\n"
  939. 939● report = report + "| TP | " + metrics.true_positives.to_string() + " |\n"
  940. 940● report = report + "| FP | " + metrics.false_positives.to_string() + " |\n"
  941. 941● report = report + "| FN | " + metrics.false_negatives.to_string() + " |\n"
  942. 942
  943. 943 report
  944. 944}