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