image.vision\ocr\layout_analysis.mbt
93.1% · 121 / 130 points · 466 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/layout_analysis - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 版面分析 - 7
// 文本区域检测、页面分割、多栏检测 - 8
- 9
///| - 10
/// 文本区域结构体 - 11
#derive(Eq, @debug.Debug) - 12
pub(all) struct TextRegion { - 13
x : Int32 - 14
y : Int32 - 15
width : Int32 - 16
height : Int32 - 17
region_type : TextRegionType - 18
} - 19
- 20
///| - 21
pub extend TextRegion with Eq::{not_equal, equal} - 22
- 23
///| - 24
pub extend TextRegion with @debug.Debug::{to_repr} - 25
- 26
///| - 27
/// 文本区域类型 - 28
/// `#non_exhaustive` 表示未来可能添加新构造器 - 29
#derive(Eq, @debug.Debug) - 30
#non_exhaustive - 31
pub(all) enum TextRegionType { - 32
Text - 33
Image - 34
Table - 35
Unknown - 36
} - 37
- 38
///| - 39
pub extend TextRegionType with @debug.Debug::{to_repr} - 40
- 41
///| - 42
pub extend TextRegionType with Eq::{not_equal, equal} - 43
- 44
///| - 45
/// 文本行结构体 - 46
#derive(Eq, @debug.Debug) - 47
pub(all) struct TextLine { - 48
x : Int32 - 49
y : Int32 - 50
width : Int32 - 51
height : Int32 - 52
} - 53
- 54
///| - 55
pub extend TextLine with Eq::{not_equal, equal} - 56
- 57
///| - 58
pub extend TextLine with @debug.Debug::{to_repr} - 59
- 60
///| - 61
/// 检测文本区域(基于投影分析) - 62
/// 返回文本区域列表 - 63
pub fn detect_text_regions( - 64
img : @types.Image, - 65
) -> Array[TextRegion] raise @types.LoadError { - 66
// 输入验证 - 67●
if img.width <= 0 || img.height <= 0 { - 68●
raise @types.LoadError::DecodeFailed( - 69
"detect_text_regions: 图像尺寸必须大于0", - 70
) - 71
} - 72
if img.channels != 1 { - 73●
raise @types.LoadError::DecodeFailed( - 74
"detect_text_regions: 仅支持单通道灰度图", - 75
) - 76
} - 77
let expected_size = img.width * img.height - 78●
if img.data.length() != expected_size { - 79●
raise @types.LoadError::DecodeFailed( - 80
"detect_text_regions: 数据大小不匹配,期望 " + - 81●
expected_size.to_string() + - 82
",实际 " + - 83●
img.data.length().to_string(), - 84
) - 85
} - 86
let w = img.width - 87
let h = img.height - 88
let data = img.data - 89
// 二值化(简单阈值) - 90●
let binary : Array[Bool] = Array::make(w * h, false) - 91
for i in 0..<(w * h) { - 92●
binary[i] = data[i].to_int() < 128 - 93
} - 94
// 水平投影(检测文本行) - 95●
let horizontal_proj : Array[Int32] = Array::make(h, 0) - 96
for y in 0..<h { - 97●
for x in 0..<w { - 98●
if binary[y * w + x] { - 99●
horizontal_proj[y] += 1 - 100
} - 101
} - 102
} - 103
// 检测文本行区域 - 104
let regions : Array[TextRegion] = [] - 105
let mut in_text = false - 106
let mut start_y = 0 - 107
let threshold = w / 20 // 文本行阈值 - 108
for y in 0..<h { - 109●
if horizontal_proj[y] > threshold && !in_text { - 110●
in_text = true - 111
start_y = y - 112●
} else if horizontal_proj[y] <= threshold && in_text { - 113●
in_text = false - 114
// 计算这一行的水平范围 - 115
let mut min_x = w - 116
let mut max_x = 0 - 117
for yy in start_y..<y { - 118●
for x in 0..<w { - 119●
if binary[yy * w + x] { - 120●
if x < min_x { - 121●
min_x = x - 122
} - 123
if x > max_x { - 124●
max_x = x - 125
} - 126
} - 127
} - 128
} - 129
if max_x > min_x { - 130●
regions.push(TextRegion::{ - 131
x: min_x, - 132
y: start_y, - 133
width: max_x - min_x + 1, - 134
height: y - start_y, - 135
region_type: TextRegionType::Text, - 136
}) - 137
} - 138
} - 139
} - 140
regions - 141
} - 142
- 143
///| - 144
/// 页面分割(文本/图像/表格区域) - 145
/// 返回区域列表 - 146
pub fn segment_page( - 147
img : @types.Image, - 148
) -> Array[TextRegion] raise @types.LoadError { - 149
// 输入验证 - 150●
if img.width <= 0 || img.height <= 0 { - 151●
raise @types.LoadError::DecodeFailed( - 152
"segment_page: 图像尺寸必须大于0", - 153
) - 154
} - 155
if img.channels != 1 { - 156○
raise @types.LoadError::DecodeFailed( - 157
"segment_page: 仅支持单通道灰度图", - 158
) - 159
} - 160
let expected_size = img.width * img.height - 161●
if img.data.length() != expected_size { - 162●
raise @types.LoadError::DecodeFailed( - 163
"segment_page: 数据大小不匹配,期望 " + - 164●
expected_size.to_string() + - 165
",实际 " + - 166●
img.data.length().to_string(), - 167
) - 168
} - 169
let w = img.width - 170
let h = img.height - 171
let data = img.data - 172
// 二值化 - 173●
let binary : Array[Bool] = Array::make(w * h, false) - 174
for i in 0..<(w * h) { - 175●
binary[i] = data[i].to_int() < 128 - 176
} - 177
// 连通域分析(简化版) - 178●
let visited : Array[Bool] = Array::make(w * h, false) - 179
let regions : Array[TextRegion] = [] - 180
for y in 0..<h { - 181●
for x in 0..<w { - 182●
if binary[y * w + x] && !visited[y * w + x] { - 183
// BFS 找连通域 - 184●
let mut min_x = x - 185
let mut max_x = x - 186
let mut min_y = y - 187
let mut max_y = y - 188
let mut count = 0 - 189
let queue : Array[(Int32, Int32)] = [(x, y)] - 190
visited[y * w + x] = true - 191
let mut queue_idx = 0 - 192●
while queue_idx < queue.length() { - 193●
let (cx, cy) = queue[queue_idx] - 194
queue_idx += 1 - 195
count += 1 - 196
if cx < min_x { - 197○
min_x = cx - 198
} - 199
if cx > max_x { - 200●
max_x = cx - 201
} - 202
if cy < min_y { - 203○
min_y = cy - 204
} - 205
if cy > max_y { - 206●
max_y = cy - 207
} - 208
// 8 邻域 - 209
for dy in -1..<2 { - 210●
for dx in -1..<2 { - 211●
let nx = cx + dx - 212
let ny = cy + dy - 213
if nx >= 0 && - 214
nx < w && - 215
ny >= 0 && - 216
ny < h && - 217
binary[ny * w + nx] && - 218
!visited[ny * w + nx] { - 219●
visited[ny * w + nx] = true - 220●
queue.push((nx, ny)) - 221
} - 222
} - 223
} - 224
} - 225
// 根据区域大小和宽高比判断类型 - 226
let region_w = max_x - min_x + 1 - 227
let region_h = max_y - min_y + 1 - 228
let region_type = if count < 50 { - 229○
TextRegionType::Unknown // 噪声 - 230●
} else if region_w > 50 && region_h > 50 { - 231○
TextRegionType::Image // 大区域可能是图像 - 232
} else { - 233●
TextRegionType::Text // 小区域可能是文字 - 234
} - 235●
regions.push(TextRegion::{ - 236
x: min_x, - 237
y: min_y, - 238
width: region_w, - 239
height: region_h, - 240
region_type, - 241
}) - 242
} - 243
} - 244
} - 245
regions - 246
} - 247
- 248
///| - 249
/// 检测多栏布局 - 250
/// 返回栏数和每栏的 x 范围 - 251
pub fn detect_columns( - 252
img : @types.Image, - 253
) -> (Int32, Array[(Int32, Int32)]) raise @types.LoadError { - 254
// 输入验证 - 255●
if img.width <= 0 || img.height <= 0 { - 256●
raise @types.LoadError::DecodeFailed( - 257
"detect_columns: 图像尺寸必须大于0", - 258
) - 259
} - 260
if img.channels != 1 { - 261○
raise @types.LoadError::DecodeFailed( - 262
"detect_columns: 仅支持单通道灰度图", - 263
) - 264
} - 265
let expected_size = img.width * img.height - 266●
if img.data.length() != expected_size { - 267●
raise @types.LoadError::DecodeFailed( - 268
"detect_columns: 数据大小不匹配,期望 " + - 269●
expected_size.to_string() + - 270
",实际 " + - 271●
img.data.length().to_string(), - 272
) - 273
} - 274
let w = img.width - 275
let h = img.height - 276
let data = img.data - 277
// 垂直投影 - 278●
let vertical_proj : Array[Int32] = Array::make(w, 0) - 279
for y in 0..<h { - 280●
for x in 0..<w { - 281●
if data[y * w + x].to_int() < 128 { - 282●
vertical_proj[x] += 1 - 283
} - 284
} - 285
} - 286
// 找空白列(栏间距) - 287
let threshold = h / 50 // 空白列阈值 - 288
let gaps : Array[(Int32, Int32)] = [] - 289
let mut in_gap = false - 290
let mut gap_start = 0 - 291
for x in 0..<w { - 292●
if vertical_proj[x] < threshold && !in_gap { - 293●
in_gap = true - 294
gap_start = x - 295●
} else if vertical_proj[x] >= threshold && in_gap { - 296●
in_gap = false - 297
let gap_width = x - gap_start - 298
if gap_width > w / 20 { // 足够宽的间隙才算栏间距 - 299●
gaps.push((gap_start, x)) - 300
} - 301
} - 302
} - 303
// 根据间隙计算栏数和范围 - 304●
let num_columns = gaps.length() + 1 - 305
let columns : Array[(Int32, Int32)] = [] - 306
let mut prev_end = 0 - 307●
for i in 0..<gaps.length() { - 308●
let (start, end) = gaps[i] - 309●
columns.push((prev_end, start)) - 310
prev_end = end - 311
} - 312●
columns.push((prev_end, w)) - 313
(num_columns, columns) - 314
} - 315
- 316
///| - 317
/// 提取文本行图像 - 318
/// 返回文本行图像列表 - 319
pub fn extract_text_lines( - 320
img : @types.Image, - 321
) -> Array[@types.Image] raise @types.LoadError { - 322
// 输入验证 - 323●
if img.width <= 0 || img.height <= 0 { - 324●
raise @types.LoadError::DecodeFailed( - 325
"extract_text_lines: 图像尺寸必须大于0", - 326
) - 327
} - 328
if img.channels != 1 { - 329●
raise @types.LoadError::DecodeFailed( - 330
"extract_text_lines: 仅支持单通道灰度图", - 331
) - 332
} - 333
let expected_size = img.width * img.height - 334●
if img.data.length() != expected_size { - 335●
raise @types.LoadError::DecodeFailed( - 336
"extract_text_lines: 数据大小不匹配,期望 " + - 337●
expected_size.to_string() + - 338
",实际 " + - 339●
img.data.length().to_string(), - 340
) - 341
} - 342●
let regions = detect_text_regions(img) - 343
let lines : Array[@types.Image] = [] - 344
for region in regions { - 345●
if region.region_type == TextRegionType::Text { - 346●
let line = crop_region( - 347
img, - 348
region.x, - 349
region.y, - 350
region.width, - 351
region.height, - 352
) - 353●
match line { - 354●
Some(l) => lines.push(l) - 355○
None => ignore(()) - 356
} - 357
} - 358
} - 359
lines - 360
} - 361
- 362
///| - 363
/// 裁剪图像区域 - 364
fn crop_region( - 365
img : @types.Image, - 366
x : Int32, - 367
y : Int32, - 368
width : Int32, - 369
height : Int32, - 370
) -> @types.Image? { - 371●
let w = img.width - 372
let h = img.height - 373
let ch = img.channels - 374
if x < 0 || y < 0 || x + width > w || y + height > h { - 375○
return None - 376
} - 377●
let out : Array[Byte] = Array::make(width * height * ch, b'\x00') - 378
let data = img.data - 379
for yy in 0..<height { - 380●
for xx in 0..<width { - 381●
for c in 0..<ch { - 382●
out[(yy * width + xx) * ch + c] = data[((y + yy) * w + (x + xx)) * ch + - 383
c] - 384
} - 385
} - 386
} - 387
Some(@types.Image::{ - 388
width, - 389
height, - 390
channels: ch, - 391●
data: Bytes::from_array(out), - 392
}) - 393
} - 394
- 395
///| - 396
/// OCR 完整预处理流水线 - 397
/// 灰度化 -> 去噪 -> 倾斜校正 -> 二值化 -> 输出 - 398
pub fn ocr_preprocess( - 399
img : @types.Image, - 400
binarization_method~ : String = "sauvola", - 401
) -> @types.Image raise @types.LoadError { - 402
// 输入验证 - 403●
if img.width <= 0 || img.height <= 0 { - 404●
raise @types.LoadError::DecodeFailed( - 405
"ocr_preprocess: 图像尺寸必须大于0", - 406
) - 407
} - 408
if img.channels < 1 || img.channels > 4 { - 409●
raise @types.LoadError::DecodeFailed( - 410
"ocr_preprocess: 通道数必须在1-4之间", - 411
) - 412
} - 413
let expected_size = img.width * img.height * img.channels - 414●
if img.data.length() != expected_size { - 415●
raise @types.LoadError::DecodeFailed( - 416
"ocr_preprocess: 数据大小不匹配,期望 " + - 417●
expected_size.to_string() + - 418
",实际 " + - 419●
img.data.length().to_string(), - 420
) - 421
} - 422
let mut result = img - 423
// 1. 转灰度 - 424
if result.channels != 1 { - 425●
result = to_grayscale_ocr(result) - 426
} - 427
// 2. 文档增强(去噪+对比度+锐化) - 428●
result = document_enhance(result) - 429
// 3. 倾斜校正 - 430●
result = deskew(result) - 431
// 4. 二值化 - 432●
result = match binarization_method { - 433●
"sauvola" => sauvola_threshold(result) - 434●
"niblack" => niblack_threshold(result) - 435●
"otsu" => otsu_threshold(result) - 436●
"adaptive" => adaptive_threshold_ocr(result) - 437●
_ => sauvola_threshold(result) - 438
} - 439
result - 440
} - 441
- 442
///| - 443
/// 转灰度(OCR 专用) - 444
fn to_grayscale_ocr(img : @types.Image) -> @types.Image { - 445●
if img.channels == 1 { - 446○
return img - 447
} - 448
let n = img.width * img.height - 449
let ch = img.channels - 450●
let out : Array[Byte] = Array::make(n, b'\x00') - 451
let data = img.data - 452
for i in 0..<n { - 453●
let base = i * ch - 454●
let r = data[base].to_int() - 455●
let g = data[base + 1].to_int() - 456●
let b = data[base + 2].to_int() - 457
let gray = (r * 299 + g * 587 + b * 114) / 1000 - 458●
out[i] = gray.to_byte() - 459
} - 460
@types.Image::{ - 461
width: img.width, - 462
height: img.height, - 463
channels: 1, - 464●
data: Bytes::from_array(out), - 465
} - 466
}