image.vision\ocr\char_segmentation.mbt
87.8% · 172 / 196 points · 632 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # 字符分割 ocr/char_segmentation - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 字符分割完善 - 7
// 滴水算法、连通域分割、粘连字符处理、分割后处理 - 8
- 9
///| - 10
/// 分割点结构体 - 11
#derive(Eq, @debug.Debug) - 12
pub(all) struct SplitPoint { - 13
x : Int32 - 14
y_top : Int32 - 15
y_bottom : Int32 - 16
confidence : Double - 17
} - 18
- 19
///| - 20
pub extend SplitPoint with Eq::{not_equal, equal} - 21
- 22
///| - 23
pub extend SplitPoint with @debug.Debug::{to_repr} - 24
- 25
///| - 26
/// 滴水算法分割结果 - 27
#derive(Eq, @debug.Debug) - 28
pub(all) struct DropFallResult { - 29
split_points : Array[SplitPoint] - 30
char_regions : Array[(Int32, Int32)] - 31
success : Bool - 32
} - 33
- 34
///| - 35
pub extend DropFallResult with Eq::{not_equal, equal} - 36
- 37
///| - 38
pub extend DropFallResult with @debug.Debug::{to_repr} - 39
- 40
///| - 41
/// 滴水算法(Drop Fall Algorithm) - 42
/// 用于分割粘连字符,模拟水滴从顶部落下的路径 - 43
pub fn drop_fall_segmentation( - 44
img : @types.Image, - 45
start_x~ : Int32 = -1, - 46
) -> DropFallResult raise @types.LoadError { - 47
// 输入验证 - 48●
if img.width <= 0 || img.height <= 0 { - 49●
raise @types.LoadError::DecodeFailed( - 50
"drop_fall_segmentation: 图像尺寸必须大于0", - 51
) - 52
} - 53
if img.channels != 1 { - 54●
raise @types.LoadError::DecodeFailed( - 55
"drop_fall_segmentation: 仅支持单通道二值图", - 56
) - 57
} - 58
let expected_size = img.width * img.height - 59●
if img.data.length() != expected_size { - 60●
raise @types.LoadError::DecodeFailed( - 61
"drop_fall_segmentation: 数据大小不匹配,期望 " + - 62●
expected_size.to_string() + - 63
",实际 " + - 64●
img.data.length().to_string(), - 65
) - 66
} - 67
- 68
let w = img.width - 69
let h = img.height - 70
let data = img.data - 71
// 如果未指定起始x,使用中间位置 - 72●
let sx = if start_x < 0 { w / 2 } else { start_x } - 73
// 滴水路径 - 74
let path : Array[(Int32, Int32)] = [] - 75
let mut x = sx - 76
let mut y = 0 - 77
let stuck = false - 78
let mut iterations = 0 - 79
let max_iterations = w * h - 80
while y < h - 1 && !stuck && iterations < max_iterations { - 81●
iterations += 1 - 82●
path.push((x, y)) - 83
// 检查下方三个方向:左下、正下、右下 - 84◐
let left = if x > 0 { data[(y + 1) * w + (x - 1)].to_int() } else { 255 } - 85●
let center = data[(y + 1) * w + x].to_int() - 86
let right = if x < w - 1 { - 87●
data[(y + 1) * w + (x + 1)].to_int() - 88
} else { - 89○
255 - 90
} - 91
// 水滴优先向黑色像素(前景)移动 - 92
if center < 128 { - 93
// 正下是黑色,继续向下 - 94●
y += 1 - 95●
} else if left < 128 && right < 128 { - 96
// 左右都是黑色,随机选择(这里选择左) - 97○
x -= 1 - 98
y += 1 - 99●
} else if left < 128 { - 100
// 左下是黑色 - 101○
x -= 1 - 102
y += 1 - 103●
} else if right < 128 { - 104
// 右下是黑色 - 105●
x += 1 - 106
y += 1 - 107
} else { - 108
// 下方都是白色,水滴在白色区域 - 109
// 检查是否到达底部或卡住 - 110●
if y >= h - 1 { - 111○
break - 112
} - 113
// 在白色区域,继续向下(模拟水滴穿透白色背景) - 114
y += 1 - 115
} - 116
// 边界检查 - 117
if x < 0 { - 118○
x = 0 - 119
} - 120
if x >= w { - 121○
x = w - 1 - 122
} - 123
} - 124●
path.push((x, y)) - 125
// 从路径中提取分割点 - 126
let split_points : Array[SplitPoint] = [] - 127●
if path.length() > 0 { - 128●
let (final_x, _) = path[path.length() - 1] - 129●
split_points.push(SplitPoint::{ - 130
x: final_x, - 131
y_top: 0, - 132
y_bottom: h - 1, - 133
confidence: 0.8, - 134
}) - 135
} - 136
// 计算字符区域 - 137
let char_regions : Array[(Int32, Int32)] = [] - 138●
if split_points.length() > 0 { - 139●
let mut prev_x = 0 - 140
for sp in split_points { - 141●
char_regions.push((prev_x, sp.x)) - 142
prev_x = sp.x - 143
} - 144●
char_regions.push((prev_x, w - 1)) - 145
} else { - 146○
char_regions.push((0, w - 1)) - 147
} - 148
DropFallResult::{ - 149
split_points, - 150
char_regions, - 151●
success: split_points.length() > 0, - 152
} - 153
} - 154
- 155
///| - 156
/// 检测粘连字符(基于垂直投影的局部最小值分析) - 157
/// 返回粘连位置列表 - 158
pub fn detect_touching_chars( - 159
img : @types.Image, - 160
min_char_width~ : Int32 = 8, - 161
max_char_width~ : Int32 = 50, - 162
) -> Array[Int32] raise @types.LoadError { - 163
// 输入验证 - 164●
if img.width <= 0 || img.height <= 0 { - 165●
raise @types.LoadError::DecodeFailed( - 166
"detect_touching_chars: 图像尺寸必须大于0", - 167
) - 168
} - 169
if img.channels != 1 { - 170●
raise @types.LoadError::DecodeFailed( - 171
"detect_touching_chars: 仅支持单通道二值图", - 172
) - 173
} - 174
let expected_size = img.width * img.height - 175●
if img.data.length() != expected_size { - 176●
raise @types.LoadError::DecodeFailed( - 177
"detect_touching_chars: 数据大小不匹配,期望 " + - 178●
expected_size.to_string() + - 179
",实际 " + - 180●
img.data.length().to_string(), - 181
) - 182
} - 183
if min_char_width <= 0 { - 184○
raise @types.LoadError::DecodeFailed( - 185
"detect_touching_chars: min_char_width必须大于0", - 186
) - 187
} - 188
if max_char_width < min_char_width { - 189○
raise @types.LoadError::DecodeFailed( - 190
"detect_touching_chars: max_char_width不能小于min_char_width", - 191
) - 192
} - 193
- 194
let w = img.width - 195
let h = img.height - 196
let data = img.data - 197
// 垂直投影 - 198●
let projection : Array[Int32] = Array::make(w, 0) - 199
for y in 0..<h { - 200●
for x in 0..<w { - 201●
if data[y * w + x].to_int() > 128 { - 202●
projection[x] += 1 - 203
} - 204
} - 205
} - 206
// 找局部最小值(可能的分割点) - 207
let minima : Array[Int32] = [] - 208
for x in 2..<(w - 2) { - 209●
if projection[x] < projection[x - 1] && - 210
projection[x] <= projection[x + 1] && - 211
projection[x] < projection[x - 2] && - 212
projection[x] <= projection[x + 2] { - 213●
minima.push(x) - 214
} - 215
} - 216
// 过滤:只保留在合理字符宽度范围内的分割点 - 217
let touching_points : Array[Int32] = [] - 218
let mut last_split = 0 - 219
for x in minima { - 220●
let width = x - last_split - 221
if width >= min_char_width && width <= max_char_width * 2 { - 222
// 检查这个位置是否真的是粘连点(投影值较低但不为0) - 223●
if projection[x] > 0 && projection[x] < h / 4 { - 224○
touching_points.push(x) - 225
last_split = x - 226
} - 227
} - 228
} - 229
touching_points - 230
} - 231
- 232
///| - 233
/// 基于连通域的字符分割 - 234
/// 返回字符区域列表 - 235
pub fn segment_by_connected_components( - 236
img : @types.Image, - 237
min_area~ : Int32 = 5, - 238
max_area~ : Int32 = 10000, - 239
) -> Array[(Int32, Int32, Int32, Int32)] raise @types.LoadError { - 240
// 输入验证 - 241●
if img.width <= 0 || img.height <= 0 { - 242●
raise @types.LoadError::DecodeFailed( - 243
"segment_by_connected_components: 图像尺寸必须大于0", - 244
) - 245
} - 246
if img.channels != 1 { - 247●
raise @types.LoadError::DecodeFailed( - 248
"segment_by_connected_components: 仅支持单通道二值图", - 249
) - 250
} - 251
let expected_size = img.width * img.height - 252●
if img.data.length() != expected_size { - 253●
raise @types.LoadError::DecodeFailed( - 254
"segment_by_connected_components: 数据大小不匹配,期望 " + - 255●
expected_size.to_string() + - 256
",实际 " + - 257●
img.data.length().to_string(), - 258
) - 259
} - 260
if min_area < 0 { - 261●
raise @types.LoadError::DecodeFailed( - 262
"segment_by_connected_components: min_area不能为负数", - 263
) - 264
} - 265
if max_area < min_area { - 266●
raise @types.LoadError::DecodeFailed( - 267
"segment_by_connected_components: max_area不能小于min_area", - 268
) - 269
} - 270
- 271
let w = img.width - 272
let h = img.height - 273
let data = img.data - 274
// 连通域标记 + 并查集(S30 修复) - 275
// - 276
// 旧版只做「取左邻或上邻的标签」,**不做等价标签合并**:当一个像素同时有左邻与上邻、 - 277
// 且两者标签不同时,它只认左边,右边那一片从此独立——同一个连通的字形会被切成好几段。 - 278
// 实测 5×7 字形里带斜笔画的 `2`/`Z`/`N` 被切成 6 段,块状字母 `E`/`F`/`L` 却没事, - 279
// 这就是"英文识别只有块状字母能过"的真正原因。 - 280●
let parent : Array[Int32] = Array::make(w * h + 1, 0) - 281
let find = fn(start : Int32) -> Int32 { - 282●
let mut r = start - 283
while parent[r] != 0 && parent[r] != r { - 284●
r = parent[r] - 285
} - 286
r - 287
} - 288
let union = fn(a1 : Int32, b1 : Int32) -> Unit { - 289●
let ra = find(a1) - 290●
let rb = find(b1) - 291
if ra != rb { - 292●
parent[rb] = ra - 293
} - 294
} - 295●
let labels : Array[Int32] = Array::make(w * h, 0) - 296
let mut next_label = 1 - 297
// 第一遍:扫前景(>128 = 墨),左/上双亲时 union - 298
for y in 0..<h { - 299●
for x in 0..<w { - 300●
if data[y * w + x].to_int() > 128 { - 301●
let mut l = 0 - 302
if x > 0 { - 303●
l = labels[y * w + x - 1] - 304
} - 305
let mut u = 0 - 306
if y > 0 { - 307●
u = labels[(y - 1) * w + x] - 308
} - 309
let label = if l > 0 && u > 0 { - 310●
union(l, u) - 311
l - 312●
} else if l > 0 { - 313●
l - 314●
} else if u > 0 { - 315●
u - 316
} else { - 317●
let fresh = next_label - 318
next_label += 1 - 319
parent[fresh] = fresh - 320
fresh - 321
} - 322
labels[y * w + x] = label - 323
} - 324
} - 325
} - 326
// 第二遍:按并查集根统计每个连通域的包围盒与像素面积 - 327
// 计算每个标签的边界框 - 328●
let min_x : Array[Int32] = Array::make(next_label, w) - 329●
let max_x : Array[Int32] = Array::make(next_label, 0) - 330●
let min_y : Array[Int32] = Array::make(next_label, h) - 331●
let max_y : Array[Int32] = Array::make(next_label, 0) - 332●
let area : Array[Int32] = Array::make(next_label, 0) - 333
for y in 0..<h { - 334●
for x in 0..<w { - 335●
let label = find(labels[y * w + x]) - 336
if label > 0 { - 337●
area[label] += 1 - 338
if x < min_x[label] { - 339●
min_x[label] = x - 340
} - 341
if x > max_x[label] { - 342●
max_x[label] = x - 343
} - 344
if y < min_y[label] { - 345●
min_y[label] = y - 346
} - 347
if y > max_y[label] { - 348●
max_y[label] = y - 349
} - 350
} - 351
} - 352
} - 353
// 过滤并返回 - 354
let regions : Array[(Int32, Int32, Int32, Int32)] = [] - 355
for label in 1..<next_label { - 356●
if area[label] >= min_area && area[label] <= max_area { - 357●
let rw = max_x[label] - min_x[label] + 1 - 358
let rh = max_y[label] - min_y[label] + 1 - 359
if rw > 0 && rh > 0 { - 360●
regions.push((min_x[label], min_y[label], rw, rh)) - 361
} - 362
} - 363
} - 364
regions - 365
} - 366
- 367
///| - 368
/// 分割后处理:合并过小的分割区域 - 369
pub fn merge_small_segments( - 370
segments : Array[(Int32, Int32, Int32, Int32)], - 371
min_width : Int32, - 372
min_height : Int32, - 373
) -> Array[(Int32, Int32, Int32, Int32)] raise @types.LoadError { - 374
// 输入验证 - 375●
if segments.length() == 0 { - 376●
raise @types.LoadError::DecodeFailed( - 377
"merge_small_segments: 分割区域列表不能为空", - 378
) - 379
} - 380
if min_width <= 0 { - 381●
raise @types.LoadError::DecodeFailed( - 382
"merge_small_segments: min_width必须大于0", - 383
) - 384
} - 385
if min_height <= 0 { - 386●
raise @types.LoadError::DecodeFailed( - 387
"merge_small_segments: min_height必须大于0", - 388
) - 389
} - 390
- 391
let merged : Array[(Int32, Int32, Int32, Int32)] = [] - 392
let mut current = segments[0] - 393●
for i in 1..<segments.length() { - 394●
let next = segments[i] - 395
let (cx, cy, cw, ch) = current - 396
let (nx, ny, nw, nh) = next - 397
// 检查当前区域是否过小 - 398
if cw < min_width || ch < min_height { - 399
// 合并到下一个区域 - 400●
let new_x = min(cx, nx) - 401●
let new_y = min(cy, ny) - 402●
let new_max_x = max(cx + cw, nx + nw) - 403●
let new_max_y = max(cy + ch, ny + nh) - 404
current = (new_x, new_y, new_max_x - new_x, new_max_y - new_y) - 405
} else { - 406●
merged.push(current) - 407
current = next - 408
} - 409
} - 410
// 处理最后一个区域 - 411
let (cx, cy, cw, ch) = current - 412
if cw >= min_width && ch >= min_height { - 413●
merged.push(current) - 414●
} else if merged.length() > 0 { - 415
// 合并到前一个区域 - 416●
let (px, py, pw, ph) = merged[merged.length() - 1] - 417●
let new_x = min(px, cx) - 418●
let new_y = min(py, cy) - 419●
let new_max_x = max(px + pw, cx + cw) - 420●
let new_max_y = max(py + ph, cy + ch) - 421●
merged[merged.length() - 1] = ( - 422
new_x, - 423
new_y, - 424
new_max_x - new_x, - 425
new_max_y - new_y, - 426
) - 427
} - 428
merged - 429
} - 430
- 431
///| - 432
/// 分割后处理:过滤噪声区域 - 433
pub fn filter_noise_segments( - 434
segments : Array[(Int32, Int32, Int32, Int32)], - 435
img_width : Int32, - 436
img_height : Int32, - 437
min_area_ratio~ : Double = 0.001, - 438
max_area_ratio~ : Double = 0.5, - 439
) -> Array[(Int32, Int32, Int32, Int32)] raise @types.LoadError { - 440
// 输入验证 - 441●
if segments.length() == 0 { - 442●
raise @types.LoadError::DecodeFailed( - 443
"filter_noise_segments: 分割区域列表不能为空", - 444
) - 445
} - 446
if img_width <= 0 || img_height <= 0 { - 447●
raise @types.LoadError::DecodeFailed( - 448
"filter_noise_segments: 图像尺寸必须大于0", - 449
) - 450
} - 451
if min_area_ratio < 0.0 || min_area_ratio > 1.0 { - 452●
raise @types.LoadError::DecodeFailed( - 453
"filter_noise_segments: min_area_ratio必须在0-1之间", - 454
) - 455
} - 456
if max_area_ratio < 0.0 || max_area_ratio > 1.0 { - 457●
raise @types.LoadError::DecodeFailed( - 458
"filter_noise_segments: max_area_ratio必须在0-1之间", - 459
) - 460
} - 461
if max_area_ratio < min_area_ratio { - 462●
raise @types.LoadError::DecodeFailed( - 463
"filter_noise_segments: max_area_ratio不能小于min_area_ratio", - 464
) - 465
} - 466
- 467
let img_area = img_width * img_height - 468●
let min_area = (img_area.to_double() * min_area_ratio).to_int() - 469●
let max_area = (img_area.to_double() * max_area_ratio).to_int() - 470
let filtered : Array[(Int32, Int32, Int32, Int32)] = [] - 471
for _tup0 in segments { - 472●
let (x, y, w, h) = _tup0 - 473
let area = w * h - 474
if area >= min_area && area <= max_area { - 475●
filtered.push((x, y, w, h)) - 476
} - 477
} - 478
filtered - 479
} - 480
- 481
///| - 482
/// 完整字符分割流水线 - 483
/// 1. 连通域初步分割 - 484
/// 2. 粘连字符检测 - 485
/// 3. 滴水算法分割粘连字符 - 486
/// 4. 后处理(合并过小、过滤噪声) - 487
pub fn complete_char_segmentation( - 488
img : @types.Image, - 489
min_char_width~ : Int32 = 5, - 490
max_char_width~ : Int32 = 60, - 491
) -> Array[(Int32, Int32, Int32, Int32)] raise @types.LoadError { - 492
// 输入验证 - 493●
if img.width <= 0 || img.height <= 0 { - 494●
raise @types.LoadError::DecodeFailed( - 495
"complete_char_segmentation: 图像尺寸必须大于0", - 496
) - 497
} - 498
if img.channels != 1 { - 499●
raise @types.LoadError::DecodeFailed( - 500
"complete_char_segmentation: 仅支持单通道二值图", - 501
) - 502
} - 503
let expected_size = img.width * img.height - 504●
if img.data.length() != expected_size { - 505●
raise @types.LoadError::DecodeFailed( - 506
"complete_char_segmentation: 数据大小不匹配,期望 " + - 507●
expected_size.to_string() + - 508
",实际 " + - 509●
img.data.length().to_string(), - 510
) - 511
} - 512
if min_char_width <= 0 { - 513●
raise @types.LoadError::DecodeFailed( - 514
"complete_char_segmentation: min_char_width必须大于0", - 515
) - 516
} - 517
if max_char_width < min_char_width { - 518●
raise @types.LoadError::DecodeFailed( - 519
"complete_char_segmentation: max_char_width不能小于min_char_width", - 520
) - 521
} - 522
- 523
let w = img.width - 524
let h = img.height - 525
// 1. 连通域初步分割 - 526●
let segments = segment_by_connected_components( - 527
img, - 528
min_area=5, - 529
max_area=100000, - 530
) - 531
// 2. 检测粘连字符(宽度过大的区域) - 532
let final_segments : Array[(Int32, Int32, Int32, Int32)] = [] - 533
for _tup1 in segments { - 534●
let (x, y, sw, sh) = _tup1 - 535
if sw > max_char_width && sh > min_char_width { - 536
// 可能是粘连字符,尝试滴水算法分割 - 537
// 裁剪这个区域 - 538●
let sub_img = crop_sub_image(img, x, y, sw, sh) - 539●
match sub_img { - 540●
Some(si) => { - 541●
let drop_result = drop_fall_segmentation(si) - 542●
if drop_result.success && drop_result.char_regions.length() > 1 { - 543
// 分割成功,添加子区域 - 544●
for _tup2 in drop_result.char_regions { - 545●
let (rx1, rx2) = _tup2 - 546
let rw = rx2 - rx1 + 1 - 547
if rw >= min_char_width { - 548●
final_segments.push((x + rx1, y, rw, sh)) - 549
} - 550
} - 551
} else { - 552
// 分割失败,保留原区域 - 553○
final_segments.push((x, y, sw, sh)) - 554
} - 555
} - 556○
None => final_segments.push((x, y, sw, sh)) - 557
} - 558
} else { - 559●
final_segments.push((x, y, sw, sh)) - 560
} - 561
} - 562
// 空图/纯背景:没有候选就不该进后处理链(旧版会让 merge_small_segments 抛错) - 563●
if final_segments.length() == 0 { - 564●
return [] - 565
} - 566
// 3. 后处理:合并过小的区域 - 567●
let merged = merge_small_segments( - 568
final_segments, min_char_width, min_char_width, - 569
) - 570
// 4. 过滤噪声 - 571●
let filtered = filter_noise_segments( - 572
merged, - 573
w, - 574
h, - 575
min_area_ratio=0.0005, - 576
max_area_ratio=0.8, - 577
) - 578
filtered - 579
} - 580
- 581
///| - 582
/// 裁剪子图像 - 583
fn crop_sub_image( - 584
img : @types.Image, - 585
x : Int32, - 586
y : Int32, - 587
width : Int32, - 588
height : Int32, - 589
) -> @types.Image? { - 590●
let w = img.width - 591
let h = img.height - 592
let ch = img.channels - 593
if x < 0 || y < 0 || x + width > w || y + height > h { - 594○
return None - 595
} - 596●
let out : Array[Byte] = Array::make(width * height * ch, b'\x00') - 597
let data = img.data - 598
for yy in 0..<height { - 599●
for xx in 0..<width { - 600●
for c in 0..<ch { - 601●
out[(yy * width + xx) * ch + c] = data[((y + yy) * w + (x + xx)) * ch + - 602
c] - 603
} - 604
} - 605
} - 606
Some(@types.Image::{ - 607
width, - 608
height, - 609
channels: ch, - 610●
data: Bytes::from_array(out), - 611
}) - 612
} - 613
- 614
///| - 615
/// 辅助函数:最小值 - 616
fn _min_seg(a : Int32, b : Int32) -> Int32 { - 617○
if a < b { - 618○
a - 619
} else { - 620○
b - 621
} - 622
} - 623
- 624
///| - 625
/// 辅助函数:最大值 - 626
fn _max_seg(a : Int32, b : Int32) -> Int32 { - 627○
if a > b { - 628○
a - 629
} else { - 630○
b - 631
} - 632
}