image.process\segment\segment.mbt
93.2% · 124 / 133 points · 461 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # 分割 segment - 3
/// - 4
/// 图像处理算法模块 - 5
/// 图像处理算法模块 Image processing algorithm module - 6
// 图像分割(纯 MoonBit):kmeans_segment / region_growing_segment / flood_fill / segment_to_color - 7
- 8
///| - 9
/// 分割标签图 - 10
pub(all) struct SegmentLabelImage { - 11
width : Int32 - 12
height : Int32 - 13
labels : Array[Int32] // 每个像素的标签(0=背景,1..N=区域) - 14
num_regions : Int32 - 15
} - 16
- 17
///| - 18
/// 分割区域信息 - 19
pub struct SegmentRegion { - 20
label : Int32 // 标签号 - 21
area : Int32 // 像素数 - 22
mean_r : Int32 // 平均颜色 R - 23
mean_g : Int32 // 平均颜色 G - 24
mean_b : Int32 // 平均颜色 B - 25
bbox_x : Int32 - 26
bbox_y : Int32 - 27
bbox_w : Int32 - 28
bbox_h : Int32 - 29
} - 30
- 31
///| - 32
/// K-means 颜色分割。将图像像素按颜色聚为 k 类,返回标签图和区域信息。 - 33
/// 适用于 RGB/RGBA 图像(channels=3/4)。 - 34
pub fn kmeans_segment( - 35
img : @types.Image, - 36
k : Int32, - 37
max_iters~ : Int32 = 20, - 38
) -> (SegmentLabelImage, Array[SegmentRegion]) raise @types.LoadError { - 39●
if k < 1 || k > 256 { - 40●
raise @types.LoadError::DecodeFailed("k 必须在 1..256 之间") - 41
} - 42
if img.channels != 3 && img.channels != 4 { - 43●
raise @types.LoadError::DecodeFailed( - 44
"kmeans_segment 需要 RGB/RGBA 图像", - 45
) - 46
} - 47
let ch = img.channels - 48
let w = img.width - 49
let h = img.height - 50
let n = w * h - 51
if n == 0 { - 52●
return ( - 53
SegmentLabelImage::{ width: w, height: h, labels: [], num_regions: 0, }, - 54
[], - 55
) - 56
} - 57
// 初始化聚类中心 - 58●
let centroids_r : Array[Int32] = Array::make(k, 0) - 59●
let centroids_g : Array[Int32] = Array::make(k, 0) - 60●
let centroids_b : Array[Int32] = Array::make(k, 0) - 61●
let data_int : Array[Int32] = Array::make(n * ch, 0) - 62
for i in 0..<(n * ch) { - 63●
data_int[i] = img.data[i].to_int() - 64
} - 65●
let step = if n > k { n / k } else { 1 } - 66
for i in 0..<k { - 67●
let idx = (i * step).clamp(min=0, max=n - 1) - 68
centroids_r[i] = data_int[idx * ch] - 69
centroids_g[i] = data_int[idx * ch + 1] - 70
centroids_b[i] = data_int[idx * ch + 2] - 71
} - 72●
let labels : Array[Int32] = Array::make(n, 0) - 73◐
let iters = if max_iters < 1 { 20 } else { max_iters } - 74
for _ in 0..<iters { - 75●
let mut changed = false - 76
for i in 0..<n { - 77●
let r = data_int[i * ch] - 78
let g = data_int[i * ch + 1] - 79
let b = data_int[i * ch + 2] - 80
let mut best = 0 - 81●
let mut best_dist = color_dist_sq( - 82
r, - 83
g, - 84
b, - 85
centroids_r[0], - 86
centroids_g[0], - 87
centroids_b[0], - 88
) - 89
for j in 1..<k { - 90●
let d = color_dist_sq( - 91
r, - 92
g, - 93
b, - 94
centroids_r[j], - 95
centroids_g[j], - 96
centroids_b[j], - 97
) - 98
if d < best_dist { - 99●
best_dist = d - 100
best = j - 101
} - 102
} - 103
if labels[i] != best { - 104●
changed = true - 105
labels[i] = best - 106
} - 107
} - 108
if !changed { - 109●
break - 110
} - 111●
let sum_r : Array[Int32] = Array::make(k, 0) - 112●
let sum_g : Array[Int32] = Array::make(k, 0) - 113●
let sum_b : Array[Int32] = Array::make(k, 0) - 114●
let cnt : Array[Int32] = Array::make(k, 0) - 115
for i in 0..<n { - 116●
let label = labels[i] - 117
sum_r[label] += data_int[i * ch] - 118
sum_g[label] += data_int[i * ch + 1] - 119
sum_b[label] += data_int[i * ch + 2] - 120
cnt[label] += 1 - 121
} - 122
for j in 0..<k { - 123●
if cnt[j] > 0 { - 124●
centroids_r[j] = sum_r[j] / cnt[j] - 125
centroids_g[j] = sum_g[j] / cnt[j] - 126
centroids_b[j] = sum_b[j] / cnt[j] - 127
} - 128
} - 129
} - 130●
let regions = compute_regions(data_int, labels, w, h, ch, k) - 131
(SegmentLabelImage::{ width: w, height: h, labels, num_regions: k, }, regions) - 132
} - 133
- 134
///| - 135
/// 区域生长分割。从指定种子点出发,按颜色相似性(阈值 threshold)生长区域。 - 136
/// seeds 为种子点坐标数组 [(x, y), ...]。 - 137
/// 适用于 RGB/RGBA 图像(channels=3/4)。 - 138
pub fn region_growing_segment( - 139
img : @types.Image, - 140
seeds : Array[(Int32, Int32)], - 141
threshold~ : Int32 = 30, - 142
) -> (SegmentLabelImage, Array[SegmentRegion]) raise @types.LoadError { - 143●
if img.channels != 3 && img.channels != 4 { - 144●
raise @types.LoadError::DecodeFailed( - 145
"region_growing_segment 需要 RGB/RGBA 图像", - 146
) - 147
} - 148
let ch = img.channels - 149
let w = img.width - 150
let h = img.height - 151
let n = w * h - 152●
let labels : Array[Int32] = Array::make(n, 0) - 153
let regions : Array[SegmentRegion] = [] - 154●
let data_int : Array[Int32] = Array::make(n * ch, 0) - 155
for i in 0..<(n * ch) { - 156●
data_int[i] = img.data[i].to_int() - 157
} - 158
let mut current_label = 0 - 159
for seed in seeds { - 160●
let (sx, sy) = seed - 161
if sx < 0 || sx >= w || sy < 0 || sy >= h { - 162●
continue - 163
} - 164
let seed_idx = sy * w + sx - 165
if labels[seed_idx] != 0 { - 166○
continue // 已分配 - 167
} - 168
current_label += 1 - 169
let seed_r = data_int[seed_idx * ch] - 170
let seed_g = data_int[seed_idx * ch + 1] - 171
let seed_b = data_int[seed_idx * ch + 2] - 172
// BFS 区域生长 - 173
let stack : Array[Int32] = [seed_idx] - 174
labels[seed_idx] = current_label - 175
let mut area = 0 - 176
let mut sum_r = 0 - 177
let mut sum_g = 0 - 178
let mut sum_b = 0 - 179
let mut min_x = sx - 180
let mut max_x = sx - 181
let mut min_y = sy - 182
let mut max_y = sy - 183●
while stack.length() > 0 { - 184●
let idx = stack.remove(stack.length() - 1) - 185
let px = idx % w - 186
let py = idx / w - 187
area += 1 - 188
sum_r += data_int[idx * ch] - 189
sum_g += data_int[idx * ch + 1] - 190
sum_b += data_int[idx * ch + 2] - 191
if px < min_x { - 192○
min_x = px - 193
} - 194
if px > max_x { - 195●
max_x = px - 196
} - 197
if py < min_y { - 198○
min_y = py - 199
} - 200
if py > max_y { - 201●
max_y = py - 202
} - 203
// 4 邻域 - 204
let neighbors = [(px + 1, py), (px - 1, py), (px, py + 1), (px, py - 1)] - 205
for nb in neighbors { - 206●
let (nx, ny) = nb - 207
if nx >= 0 && nx < w && ny >= 0 && ny < h { - 208●
let nidx = ny * w + nx - 209
if labels[nidx] == 0 { - 210●
let nr = data_int[nidx * ch] - 211
let ng = data_int[nidx * ch + 1] - 212
let nb2 = data_int[nidx * ch + 2] - 213●
let dist = color_dist_sq(seed_r, seed_g, seed_b, nr, ng, nb2) - 214
if dist <= threshold * threshold { - 215●
labels[nidx] = current_label - 216●
stack.push(nidx) - 217
} - 218
} - 219
} - 220
} - 221
} - 222●
regions.push(SegmentRegion::{ - 223
label: current_label, - 224
area, - 225
mean_r: if area > 0 { - 226●
sum_r / area - 227
} else { - 228○
0 - 229
}, - 230
mean_g: if area > 0 { - 231●
sum_g / area - 232
} else { - 233○
0 - 234
}, - 235
mean_b: if area > 0 { - 236●
sum_b / area - 237
} else { - 238○
0 - 239
}, - 240
bbox_x: min_x, - 241
bbox_y: min_y, - 242
bbox_w: max_x - min_x + 1, - 243
bbox_h: max_y - min_y + 1, - 244
}) - 245
} - 246
( - 247
SegmentLabelImage::{ - 248
width: w, - 249
height: h, - 250
labels, - 251
num_regions: current_label, - 252
}, - 253
regions, - 254
) - 255
} - 256
- 257
///| - 258
/// 泛洪填充。从种子点 (seed_x, seed_y) 出发,填充与种子点颜色差异 <= threshold 的连通区域, - 259
/// 用 fill_color 替换。返回填充后的图像。 - 260
/// 适用于 RGB/RGBA 图像(channels=3/4)。 - 261
pub fn flood_fill( - 262
img : @types.Image, - 263
seed_x : Int32, - 264
seed_y : Int32, - 265
fill_color : Array[Byte], - 266
threshold~ : Int32 = 0, - 267
) -> @types.Image raise @types.LoadError { - 268●
if img.channels != 3 && img.channels != 4 { - 269●
raise @types.LoadError::DecodeFailed("flood_fill 需要 RGB/RGBA 图像") - 270
} - 271
let ch = img.channels - 272
let w = img.width - 273
let h = img.height - 274
let n = w * h - 275
if seed_x < 0 || seed_x >= w || seed_y < 0 || seed_y >= h { - 276●
raise @types.LoadError::DecodeFailed("种子点越界") - 277
} - 278●
let out : Array[Byte] = Array::make(n * ch, b'\x00') - 279
for i in 0..<(n * ch) { - 280●
out[i] = img.data[i] - 281
} - 282●
let data_int : Array[Int32] = Array::make(n * ch, 0) - 283
for i in 0..<(n * ch) { - 284●
data_int[i] = img.data[i].to_int() - 285
} - 286
let seed_idx = seed_y * w + seed_x - 287
let seed_r = data_int[seed_idx * ch] - 288
let seed_g = data_int[seed_idx * ch + 1] - 289
let seed_b = data_int[seed_idx * ch + 2] - 290●
let visited : Array[Bool] = Array::make(n, false) - 291
let stack : Array[Int32] = [seed_idx] - 292
visited[seed_idx] = true - 293◐
let fill_ch = if ch >= 3 { 3 } else { 1 } - 294●
while stack.length() > 0 { - 295●
let idx = stack.remove(stack.length() - 1) - 296
let px = idx % w - 297
let py = idx / w - 298
// 填充 - 299
for c in 0..<fill_ch { - 300●
if c < fill_color.length() { - 301●
out[idx * ch + c] = fill_color[c] - 302
} - 303
} - 304
// 4 邻域 - 305
let neighbors = [(px + 1, py), (px - 1, py), (px, py + 1), (px, py - 1)] - 306
for nb in neighbors { - 307●
let (nx, ny) = nb - 308
if nx >= 0 && nx < w && ny >= 0 && ny < h { - 309●
let nidx = ny * w + nx - 310
if !visited[nidx] { - 311●
let nr = data_int[nidx * ch] - 312
let ng = data_int[nidx * ch + 1] - 313
let nb2 = data_int[nidx * ch + 2] - 314●
let dist = color_dist_sq(seed_r, seed_g, seed_b, nr, ng, nb2) - 315
if dist <= threshold * threshold { - 316●
visited[nidx] = true - 317●
stack.push(nidx) - 318
} - 319
} - 320
} - 321
} - 322
} - 323
@types.Image::{ - 324
width: w, - 325
height: h, - 326
channels: ch, - 327●
data: Bytes::from_array(out), - 328
} - 329
} - 330
- 331
///| - 332
/// 将分割标签图可视化为彩色图像。每个标签分配一个不同颜色。 - 333
pub fn segment_to_color( - 334
seg : SegmentLabelImage, - 335
) -> @types.Image raise @types.LoadError { - 336●
let w = seg.width - 337
let h = seg.height - 338
let n = w * h - 339●
let out : Array[Byte] = Array::make(n * 3, b'\x00') - 340
let num = seg.num_regions - 341
for i in 0..<n { - 342●
let label = seg.labels[i] - 343
if label >= 0 && label < num { - 344●
let hue = Float::from_int( - 345◐
label * 360 / (if num > 0 { num } else { 1 }) % 360, - 346
) - 347●
let (r, g, b) = @color.hsv_to_rgb(hue, 1.0F, 1.0F) - 348●
out[i * 3] = r.to_byte() - 349●
out[i * 3 + 1] = g.to_byte() - 350●
out[i * 3 + 2] = b.to_byte() - 351
} - 352
} - 353
@types.Image::{ - 354
width: w, - 355
height: h, - 356
channels: 3, - 357●
data: Bytes::from_array(out), - 358
} - 359
} - 360
- 361
///| - 362
fn color_dist_sq( - 363
r1 : Int32, - 364
g1 : Int32, - 365
b1 : Int32, - 366
r2 : Int32, - 367
g2 : Int32, - 368
b2 : Int32, - 369
) -> Int32 { - 370●
let dr = r1 - r2 - 371
let dg = g1 - g2 - 372
let db = b1 - b2 - 373
dr * dr + dg * dg + db * db - 374
} - 375
- 376
///| - 377
fn compute_regions( - 378
data_int : Array[Int32], - 379
labels : Array[Int32], - 380
w : Int32, - 381
h : Int32, - 382
ch : Int32, - 383
k : Int32, - 384
) -> Array[SegmentRegion] { - 385●
let sum_r : Array[Int32] = Array::make(k, 0) - 386●
let sum_g : Array[Int32] = Array::make(k, 0) - 387●
let sum_b : Array[Int32] = Array::make(k, 0) - 388●
let cnt : Array[Int32] = Array::make(k, 0) - 389●
let min_x : Array[Int32] = Array::make(k, w) - 390●
let min_y : Array[Int32] = Array::make(k, h) - 391●
let max_x : Array[Int32] = Array::make(k, 0) - 392●
let max_y : Array[Int32] = Array::make(k, 0) - 393
for y in 0..<h { - 394●
for x in 0..<w { - 395●
let idx = y * w + x - 396
let label = labels[idx] - 397
if label >= 0 && label < k { - 398●
sum_r[label] += data_int[idx * ch] - 399
sum_g[label] += data_int[idx * ch + 1] - 400
sum_b[label] += data_int[idx * ch + 2] - 401
cnt[label] += 1 - 402
if x < min_x[label] { - 403●
min_x[label] = x - 404
} - 405
if x > max_x[label] { - 406●
max_x[label] = x - 407
} - 408
if y < min_y[label] { - 409●
min_y[label] = y - 410
} - 411
if y > max_y[label] { - 412●
max_y[label] = y - 413
} - 414
} - 415
} - 416
} - 417
let regions : Array[SegmentRegion] = [] - 418
for j in 0..<k { - 419●
let area = cnt[j] - 420●
regions.push(SegmentRegion::{ - 421
label: j, - 422
area, - 423
mean_r: if area > 0 { - 424●
sum_r[j] / area - 425
} else { - 426●
0 - 427
}, - 428
mean_g: if area > 0 { - 429●
sum_g[j] / area - 430
} else { - 431●
0 - 432
}, - 433
mean_b: if area > 0 { - 434●
sum_b[j] / area - 435
} else { - 436●
0 - 437
}, - 438
bbox_x: if area > 0 { - 439●
min_x[j] - 440
} else { - 441●
0 - 442
}, - 443
bbox_y: if area > 0 { - 444●
min_y[j] - 445
} else { - 446●
0 - 447
}, - 448
bbox_w: if area > 0 { - 449●
max_x[j] - min_x[j] + 1 - 450
} else { - 451●
0 - 452
}, - 453
bbox_h: if area > 0 { - 454●
max_y[j] - min_y[j] + 1 - 455
} else { - 456●
0 - 457
}, - 458
}) - 459
} - 460
regions - 461
}