image.process\segment\segmentation.mbt
99.3% · 150 / 151 points · 417 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # 图像分割 segmentation - 3
/// - 4
/// 图像处理算法模块 - 5
/// 图像处理算法模块 Image processing algorithm module - 6
// 图像分割(v12.2.0) - 7
// 分水岭算法 + 区域生长 + 阈值分割 - 8
- 9
///| - 10
/// 分割结果 - 11
pub(all) struct SegmentationResult { - 12
labels : Array[Int32] // 每个像素的标签 - 13
num_regions : Int32 // 区域数量 - 14
region_sizes : Array[Int32] // 每个区域的大小 - 15
} - 16
- 17
///| - 18
/// 分水岭算法配置 - 19
pub(all) struct WatershedConfig { - 20
threshold : Double // 梯度阈值 - 21
min_region_size : Int32 // 最小区域大小 - 22
connectivity : Int32 // 连通性(4或8) - 23
} - 24
- 25
///| - 26
/// 创建默认分水岭配置 - 27
pub fn watershed_default_config() -> WatershedConfig { - 28●
WatershedConfig::{ threshold: 10.0, min_region_size: 50, connectivity: 8, } - 29
} - 30
- 31
///| - 32
/// 计算图像梯度(Sobel) - 33
fn compute_gradient(img : @types.Image) -> Array[Double] { - 34●
let w = img.width - 35
let h = img.height - 36
let channels = img.channels - 37
let data = img.data - 38●
let gradient : Array[Double] = Array::make(w * h, 0.0) - 39
for y in 1..<(h - 1) { - 40●
for x in 1..<(w - 1) { - 41●
let _ = (y * w + x) * channels - 42
// 灰度 - 43●
let gray = (px, py) => { - 44
let i = (py * w + px) * channels - 45●
let r = data[i].to_double() - 46●
let g = if channels >= 2 { data[i + 1].to_double() } else { r } - 47●
let b = if channels >= 3 { data[i + 2].to_double() } else { r } - 48
0.299 * r + 0.587 * g + 0.114 * b - 49
} - 50●
let gx = -gray(x - 1, y - 1) - - 51●
2.0 * gray(x - 1, y) - - 52●
gray(x - 1, y + 1) + - 53●
gray(x + 1, y - 1) + - 54●
2.0 * gray(x + 1, y) + - 55●
gray(x + 1, y + 1) - 56●
let gy = -gray(x - 1, y - 1) - - 57●
2.0 * gray(x, y - 1) - - 58●
gray(x + 1, y - 1) + - 59●
gray(x - 1, y + 1) + - 60●
2.0 * gray(x, y + 1) + - 61●
gray(x + 1, y + 1) - 62●
gradient[y * w + x] = (gx * gx + gy * gy).sqrt() - 63
} - 64
} - 65
gradient - 66
} - 67
- 68
///| - 69
/// 分水岭算法(简化版) - 70
/// 基于梯度图像的区域生长分割 - 71
pub fn watershed_segment( - 72
img : @types.Image, - 73
config? : WatershedConfig, - 74
) -> SegmentationResult { - 75●
let cfg = match config { - 76●
Some(c) => c - 77●
None => watershed_default_config() - 78
} - 79
let w = img.width - 80
let h = img.height - 81
// 1. 计算梯度 - 82●
let gradient = compute_gradient(img) - 83
// 2. 寻找局部最小值作为种子点 - 84●
let labels : Array[Int32] = Array::make(w * h, 0) - 85
let mut next_label = 1 - 86
let seeds : Array[(Int32, Int32)] = [] - 87
for y in 1..<(h - 1) { - 88●
for x in 1..<(w - 1) { - 89●
let g = gradient[y * w + x] - 90
if g < cfg.threshold { - 91
// 检查是否是局部最小值 - 92●
let mut is_min = true - 93
let neighbors = [ - 94
(-1, 0), - 95
(1, 0), - 96
(0, -1), - 97
(0, 1), - 98
(-1, -1), - 99
(1, 1), - 100
(-1, 1), - 101
(1, -1), - 102
] - 103
for _tup0 in neighbors { - 104●
let (dx, dy) = _tup0 - 105
if gradient[(y + dy) * w + (x + dx)] < g { - 106●
is_min = false - 107
} - 108
} - 109
if is_min && labels[y * w + x] == 0 { - 110●
seeds.push((x, y)) - 111
labels[y * w + x] = next_label - 112
next_label += 1 - 113
} - 114
} - 115
} - 116
} - 117
// 3. 区域生长(从种子点开始,按梯度从小到大扩展) - 118
let mut changed = true - 119
while changed { - 120●
changed = false - 121
for y in 0..<h { - 122●
for x in 0..<w { - 123●
if labels[y * w + x] == 0 && gradient[y * w + x] < cfg.threshold * 2.0 { - 124
// 检查邻域是否有已标记像素 - 125●
let neighbors = if cfg.connectivity == 8 { - 126●
[ - 127
(-1, 0), - 128
(1, 0), - 129
(0, -1), - 130
(0, 1), - 131
(-1, -1), - 132
(1, 1), - 133
(-1, 1), - 134
(1, -1), - 135
] - 136
} else { - 137●
[(-1, 0), (1, 0), (0, -1), (0, 1)] - 138
} - 139
for _tup1 in neighbors { - 140●
let (dx, dy) = _tup1 - 141
let nx = x + dx - 142
let ny = y + dy - 143
if nx >= 0 && nx < w && ny >= 0 && ny < h && labels[ny * w + nx] > 0 { - 144●
labels[y * w + x] = labels[ny * w + nx] - 145
changed = true - 146
break - 147
} - 148
} - 149
} - 150
} - 151
} - 152
} - 153
// 4. 合并小区域 - 154●
let region_sizes : Array[Int32] = Array::make(next_label, 0) - 155
for i in 0..<(w * h) { - 156●
if labels[i] > 0 { - 157●
region_sizes[labels[i]] += 1 - 158
} - 159
} - 160
// 小区域合并到相邻大区域 - 161
for label in 1..<next_label { - 162●
if region_sizes[label] < cfg.min_region_size { - 163
// 找到第一个相邻的大区域 - 164●
for y in 0..<h { - 165●
for x in 0..<w { - 166●
if labels[y * w + x] == label { - 167●
let neighbors = [(-1, 0), (1, 0), (0, -1), (0, 1)] - 168
for _tup2 in neighbors { - 169●
let (dx, dy) = _tup2 - 170
let nx = x + dx - 171
let ny = y + dy - 172
if nx >= 0 && - 173
nx < w && - 174
ny >= 0 && - 175
ny < h && - 176
labels[ny * w + nx] > 0 && - 177
labels[ny * w + nx] != label && - 178
region_sizes[labels[ny * w + nx]] >= cfg.min_region_size { - 179
// 合并 - 180●
let old_label = label - 181
let new_label = labels[ny * w + nx] - 182
for i in 0..<(w * h) { - 183●
if labels[i] == old_label { - 184●
labels[i] = new_label - 185
} - 186
} - 187
region_sizes[new_label] += region_sizes[old_label] - 188
region_sizes[old_label] = 0 - 189
break - 190
} - 191
} - 192
} - 193
} - 194
} - 195
} - 196
} - 197
// 5. 重新编号标签 - 198●
let label_map : Array[Int32] = Array::make(next_label, 0) - 199
let mut new_num = 1 - 200
let new_sizes : Array[Int32] = [] - 201
for label in 1..<next_label { - 202●
if region_sizes[label] > 0 { - 203●
label_map[label] = new_num - 204●
new_sizes.push(region_sizes[label]) - 205
new_num += 1 - 206
} - 207
} - 208
for i in 0..<(w * h) { - 209●
if labels[i] > 0 { - 210●
labels[i] = label_map[labels[i]] - 211
} - 212
} - 213
SegmentationResult::{ - 214
labels, - 215
num_regions: new_num - 1, - 216
region_sizes: new_sizes, - 217
} - 218
} - 219
- 220
///| - 221
/// 区域生长分割 - 222
/// 从种子点开始,根据相似度生长区域 - 223
pub fn region_growing( - 224
img : @types.Image, - 225
seeds : Array[(Int32, Int32)], - 226
threshold~ : Double = 30.0, - 227
) -> SegmentationResult { - 228●
let thresh = threshold - 229
let w = img.width - 230
let h = img.height - 231
let channels = img.channels - 232
let data = img.data - 233●
let labels : Array[Int32] = Array::make(w * h, 0) - 234
let region_sizes : Array[Int32] = [] - 235
let mut label = 1 - 236
for _tup3 in seeds { - 237●
let (sx, sy) = _tup3 - 238
if sx < 0 || sx >= w || sy < 0 || sy >= h { - 239●
continue - 240
} - 241
if labels[sy * w + sx] > 0 { - 242●
continue - 243
} - 244
// 种子点颜色 - 245
let seed_idx = (sy * w + sx) * channels - 246●
let seed_r = data[seed_idx].to_double() - 247
let seed_g = if channels >= 2 { - 248●
data[seed_idx + 1].to_double() - 249
} else { - 250●
seed_r - 251
} - 252
let seed_b = if channels >= 3 { - 253●
data[seed_idx + 2].to_double() - 254
} else { - 255●
seed_r - 256
} - 257
// 区域生长(洪水填充) - 258
let stack : Array[(Int32, Int32)] = [] - 259●
stack.push((sx, sy)) - 260
labels[sy * w + sx] = label - 261
let mut size = 0 - 262●
while stack.length() > 0 { - 263●
match stack.pop() { - 264●
Some((x, y)) => { - 265
size += 1 - 266
let neighbors = [(-1, 0), (1, 0), (0, -1), (0, 1)] - 267
for _tup4 in neighbors { - 268●
let (dx, dy) = _tup4 - 269
let nx = x + dx - 270
let ny = y + dy - 271
if nx >= 0 && - 272
nx < w && - 273
ny >= 0 && - 274
ny < h && - 275
labels[ny * w + nx] == 0 { - 276●
let idx = (ny * w + nx) * channels - 277●
let r = data[idx].to_double() - 278●
let g = if channels >= 2 { data[idx + 1].to_double() } else { r } - 279●
let b = if channels >= 3 { data[idx + 2].to_double() } else { r } - 280
let dist = ((r - seed_r) * (r - seed_r) + - 281
(g - seed_g) * (g - seed_g) + - 282●
(b - seed_b) * (b - seed_b)).sqrt() - 283
if dist < thresh { - 284●
labels[ny * w + nx] = label - 285●
stack.push((nx, ny)) - 286
} - 287
} - 288
} - 289
} - 290○
None => ignore(()) - 291
} - 292
} - 293●
region_sizes.push(size) - 294
label += 1 - 295
} - 296
SegmentationResult::{ labels, num_regions: label - 1, region_sizes, } - 297
} - 298
- 299
///| - 300
/// 阈值分割(Otsu 自动阈值) - 301
pub fn threshold_otsu(img : @types.Image) -> @types.Image { - 302●
let w = img.width - 303
let h = img.height - 304
let channels = img.channels - 305
let data = img.data - 306
// 计算灰度直方图 - 307●
let histogram : Array[Int32] = Array::make(256, 0) - 308
for i in 0..<(w * h) { - 309●
let idx = i * channels - 310●
let r = data[idx].to_int() - 311●
let g = if channels >= 2 { data[idx + 1].to_int() } else { r } - 312●
let b = if channels >= 3 { data[idx + 2].to_int() } else { r } - 313●
let gray = (0.299 * r.to_double() + - 314●
0.587 * g.to_double() + - 315●
0.114 * b.to_double()).to_int() - 316
histogram[gray] += 1 - 317
} - 318
// Otsu 阈值计算 - 319
let total = w * h - 320
let mut sum = 0 - 321
for t in 0..<256 { - 322●
sum += t * histogram[t] - 323
} - 324
let mut sum_b = 0 - 325
let mut w_b = 0 - 326
let mut max_variance = 0.0 - 327
let mut threshold = 128 - 328
for t in 0..<256 { - 329●
w_b += histogram[t] - 330
if w_b == 0 { - 331●
continue - 332
} - 333
let w_f = total - w_b - 334
if w_f == 0 { - 335●
break - 336
} - 337
sum_b += t * histogram[t] - 338●
let m_b = sum_b.to_double() / w_b.to_double() - 339●
let m_f = (sum - sum_b).to_double() / w_f.to_double() - 340●
let variance = w_b.to_double() * w_f.to_double() * (m_b - m_f) * (m_b - m_f) - 341
if variance > max_variance { - 342●
max_variance = variance - 343
threshold = t - 344
} - 345
} - 346
// 应用阈值 - 347●
let out_data : Array[Byte] = Array::make(w * h * channels, b'\x00') - 348
for i in 0..<(w * h) { - 349●
let idx = i * channels - 350●
let r = data[idx].to_int() - 351●
let g = if channels >= 2 { data[idx + 1].to_int() } else { r } - 352●
let b = if channels >= 3 { data[idx + 2].to_int() } else { r } - 353●
let gray = (0.299 * r.to_double() + - 354●
0.587 * g.to_double() + - 355●
0.114 * b.to_double()).to_int() - 356●
let value = if gray > threshold { 255 } else { 0 } - 357
for c in 0..<channels { - 358●
out_data[idx + c] = value.to_byte() - 359
} - 360
} - 361
@types.Image::{ - 362
width: w, - 363
height: h, - 364
channels, - 365●
data: Bytes::from_array(out_data), - 366
} - 367
} - 368
- 369
///| - 370
/// 将分割结果可视化为彩色图像 - 371
pub fn segmentation_to_color( - 372
result : SegmentationResult, - 373
width : Int32, - 374
height : Int32, - 375
) -> @types.Image { - 376●
let colors = [ - 377
(255, 0, 0), - 378
(0, 255, 0), - 379
(0, 0, 255), - 380
(255, 255, 0), - 381
(255, 0, 255), - 382
(0, 255, 255), - 383
(128, 0, 0), - 384
(0, 128, 0), - 385
(0, 0, 128), - 386
(128, 128, 0), - 387
(128, 0, 128), - 388
(0, 128, 128), - 389
(192, 192, 192), - 390
(128, 128, 128), - 391
(255, 128, 0), - 392
(255, 0, 128), - 393
] - 394●
let out_data : Array[Byte] = Array::make(width * height * 3, b'\x00') - 395
for y in 0..<height { - 396●
for x in 0..<width { - 397●
let label = result.labels[y * width + x] - 398
let idx = (y * width + x) * 3 - 399●
if label > 0 && label <= colors.length() { - 400●
let (r, g, b) = colors[label - 1] - 401●
out_data[idx] = r.to_byte() - 402●
out_data[idx + 1] = g.to_byte() - 403●
out_data[idx + 2] = b.to_byte() - 404
} else { - 405●
out_data[idx] = b'\x00' - 406
out_data[idx + 1] = b'\x00' - 407
out_data[idx + 2] = b'\x00' - 408
} - 409
} - 410
} - 411
@types.Image::{ - 412
width, - 413
height, - 414
channels: 3, - 415●
data: Bytes::from_array(out_data), - 416
} - 417
}