image.vision\ocr\scan_document_ocr.mbt
93% · 305 / 328 points · 920 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 ocr/scan_document_ocr - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 扫描版文档 OCR 增强(v12.16.0) - 7
// 扫描文档预处理、版面分析、质量评估、批量处理、多格式输出 - 8
- 9
///| - 10
/// 扫描文档配置 - 11
#derive(Eq, @debug.Debug) - 12
pub(all) struct ScanOCRConfig { - 13
language : String // "digit" / "english" / "chinese" / "multilingual" - 14
dpi : Int32 // 扫描 DPI(通常 300) - 15
deskew : Bool // 是否自动倾斜校正 - 16
denoise : Bool // 是否去噪 - 17
binarization_method : String // "otsu" / "adaptive" / "sauvola" - 18
layout_analysis : Bool // 是否进行版面分析 - 19
confidence_threshold : Double // 置信度阈值 - 20
} - 21
- 22
///| - 23
pub extend ScanOCRConfig with Eq::{not_equal, equal} - 24
- 25
///| - 26
pub extend ScanOCRConfig with @debug.Debug::{to_repr} - 27
- 28
///| - 29
/// 创建默认扫描 OCR 配置 - 30
pub fn scan_ocr_default_config() -> ScanOCRConfig { - 31●
ScanOCRConfig::{ - 32
language: "english", - 33
dpi: 300, - 34
deskew: true, - 35
denoise: true, - 36
binarization_method: "otsu", - 37
layout_analysis: true, - 38
confidence_threshold: 0.6, - 39
} - 40
} - 41
- 42
///| - 43
/// 扫描质量评估结果 - 44
#derive(Eq, @debug.Debug) - 45
pub(all) struct ScanQuality { - 46
brightness : Double // 平均亮度(0-255) - 47
contrast : Double // 对比度(标准差) - 48
sharpness : Double // 锐度(拉普拉斯方差) - 49
noise_level : Double // 噪声水平 - 50
skew_angle : Double // 倾斜角度(度) - 51
overall_score : Double // 综合质量评分(0-100) - 52
issues : Array[String] // 检测到的问题 - 53
} - 54
- 55
///| - 56
pub extend ScanQuality with Eq::{not_equal, equal} - 57
- 58
///| - 59
pub extend ScanQuality with @debug.Debug::{to_repr} - 60
- 61
///| - 62
/// 文本块(版面分析结果) - 63
#derive(Eq, @debug.Debug) - 64
pub(all) struct TextBlock { - 65
x : Int32 - 66
y : Int32 - 67
width : Int32 - 68
height : Int32 - 69
block_type : String // "text" / "title" / "table" / "image" / "list" - 70
text : String - 71
confidence : Double - 72
reading_order : Int32 - 73
} - 74
- 75
///| - 76
pub extend TextBlock with Eq::{not_equal, equal} - 77
- 78
///| - 79
pub extend TextBlock with @debug.Debug::{to_repr} - 80
- 81
///| - 82
/// OCR 页面结果 - 83
#derive(Eq, @debug.Debug) - 84
pub(all) struct OCRPageResult { - 85
page_number : Int32 - 86
width : Int32 - 87
height : Int32 - 88
blocks : Array[TextBlock] - 89
full_text : String - 90
average_confidence : Double - 91
processing_time_ms : Double - 92
} - 93
- 94
///| - 95
pub extend OCRPageResult with Eq::{not_equal, equal} - 96
- 97
///| - 98
pub extend OCRPageResult with @debug.Debug::{to_repr} - 99
- 100
///| - 101
/// 评估扫描图像质量 - 102
pub fn evaluate_scan_quality( - 103
img : @types.Image, - 104
) -> ScanQuality raise @types.LoadError { - 105
// 输入验证 - 106●
if img.width <= 0 || img.height <= 0 { - 107●
raise @types.LoadError::DecodeFailed( - 108
"evaluate_scan_quality: 图像尺寸必须大于0", - 109
) - 110
} - 111
if img.channels < 1 || img.channels > 4 { - 112●
raise @types.LoadError::DecodeFailed( - 113
"evaluate_scan_quality: 通道数必须在1-4之间", - 114
) - 115
} - 116
let expected_size = img.width * img.height * img.channels - 117●
if img.data.length() != expected_size { - 118●
raise @types.LoadError::DecodeFailed( - 119
"evaluate_scan_quality: 数据大小不匹配,期望 " + - 120●
expected_size.to_string() + - 121
",实际 " + - 122●
img.data.length().to_string(), - 123
) - 124
} - 125
let w = img.width - 126
let h = img.height - 127
let channels = img.channels - 128
// 计算亮度和对比度 - 129
let mut sum = 0.0 - 130
let mut sum_sq = 0.0 - 131●
let total = (w * h).to_double() - 132
for y in 0..<h { - 133●
for x in 0..<w { - 134●
let idx = (y * w + x) * channels - 135
let gray = if channels >= 3 { - 136●
0.299 * img.data[idx].to_double() + - 137●
0.587 * img.data[idx + 1].to_double() + - 138●
0.114 * img.data[idx + 2].to_double() - 139
} else { - 140●
img.data[idx].to_double() - 141
} - 142
sum += gray - 143
sum_sq += gray * gray - 144
} - 145
} - 146
let brightness = sum / total - 147
let variance = sum_sq / total - brightness * brightness - 148●
let contrast = if variance > 0.0 { variance.sqrt() } else { 0.0 } - 149
// 计算锐度(拉普拉斯算子简化版) - 150
let mut sharpness_sum = 0.0 - 151
let mut sharpness_count = 0 - 152
for y in 1..<(h - 1) { - 153●
for x in 1..<(w - 1) { - 154●
let idx = (y * w + x) * channels - 155
let center = if channels >= 3 { - 156●
0.299 * img.data[idx].to_double() + - 157●
0.587 * img.data[idx + 1].to_double() + - 158●
0.114 * img.data[idx + 2].to_double() - 159
} else { - 160●
img.data[idx].to_double() - 161
} - 162
let up = if channels >= 3 { - 163●
0.299 * img.data[((y - 1) * w + x) * channels].to_double() + - 164●
0.587 * img.data[((y - 1) * w + x) * channels + 1].to_double() + - 165●
0.114 * img.data[((y - 1) * w + x) * channels + 2].to_double() - 166
} else { - 167●
img.data[((y - 1) * w + x) * channels].to_double() - 168
} - 169
let down = if channels >= 3 { - 170●
0.299 * img.data[((y + 1) * w + x) * channels].to_double() + - 171●
0.587 * img.data[((y + 1) * w + x) * channels + 1].to_double() + - 172●
0.114 * img.data[((y + 1) * w + x) * channels + 2].to_double() - 173
} else { - 174●
img.data[((y + 1) * w + x) * channels].to_double() - 175
} - 176
let left = if channels >= 3 { - 177●
0.299 * img.data[(y * w + x - 1) * channels].to_double() + - 178●
0.587 * img.data[(y * w + x - 1) * channels + 1].to_double() + - 179●
0.114 * img.data[(y * w + x - 1) * channels + 2].to_double() - 180
} else { - 181●
img.data[(y * w + x - 1) * channels].to_double() - 182
} - 183
let right = if channels >= 3 { - 184●
0.299 * img.data[(y * w + x + 1) * channels].to_double() + - 185●
0.587 * img.data[(y * w + x + 1) * channels + 1].to_double() + - 186●
0.114 * img.data[(y * w + x + 1) * channels + 2].to_double() - 187
} else { - 188●
img.data[(y * w + x + 1) * channels].to_double() - 189
} - 190
let laplacian = 4.0 * center - up - down - left - right - 191
sharpness_sum += laplacian * laplacian - 192
sharpness_count += 1 - 193
} - 194
} - 195
let sharpness = if sharpness_count > 0 { - 196●
sharpness_sum / sharpness_count.to_double() - 197
} else { - 198●
0.0 - 199
} - 200
// 估计噪声水平(基于平坦区域的方差) - 201●
let noise_level = if contrast > 0 { (contrast * 0.1).min(50.0) } else { 10.0 } - 202
// 估计倾斜角度(简化版:基于水平投影的方差) - 203
let skew_angle = 0.0 // 简化,实际需要霍夫变换 - 204
// 综合质量评分 - 205
let mut score = 50.0 - 206
// 亮度评分(理想 128) - 207●
let brightness_score = 100.0 - (brightness - 128.0).abs() * 0.5 - 208
score += brightness_score * 0.2 - 209
// 对比度评分(理想 > 50) - 210●
let contrast_score = if contrast > 50.0 { 100.0 } else { contrast * 2.0 } - 211
score += contrast_score * 0.3 - 212
// 锐度评分 - 213●
let sharpness_score = if sharpness > 100.0 { 100.0 } else { sharpness } - 214
score += sharpness_score * 0.3 - 215
// 噪声评分 - 216
let noise_score = if noise_level < 10.0 { - 217●
100.0 - 218
} else { - 219●
(100.0 - noise_level).max(0.0) - 220
} - 221
score += noise_score * 0.2 - 222
// 检测问题 - 223
let issues : Array[String] = [] - 224
if brightness < 50.0 { - 225●
issues.push("图像过暗") - 226
} - 227
if brightness > 200.0 { - 228●
issues.push("图像过亮") - 229
} - 230
if contrast < 30.0 { - 231●
issues.push("对比度不足") - 232
} - 233
if sharpness < 20.0 { - 234●
issues.push("图像模糊") - 235
} - 236
if noise_level > 30.0 { - 237○
issues.push("噪声较高") - 238
} - 239
ScanQuality::{ - 240
brightness, - 241
contrast, - 242
sharpness, - 243
noise_level, - 244
skew_angle, - 245●
overall_score: score.min(100.0).max(0.0), - 246
issues, - 247
} - 248
} - 249
- 250
///| - 251
/// 扫描文档预处理流水线 - 252
pub fn scan_document_preprocess( - 253
img : @types.Image, - 254
config : ScanOCRConfig, - 255
) -> @types.Image raise @types.LoadError { - 256
// 输入验证 - 257●
if img.width <= 0 || img.height <= 0 { - 258●
raise @types.LoadError::DecodeFailed( - 259
"scan_document_preprocess: 图像尺寸必须大于0", - 260
) - 261
} - 262
if img.channels < 1 || img.channels > 4 { - 263●
raise @types.LoadError::DecodeFailed( - 264
"scan_document_preprocess: 通道数必须在1-4之间", - 265
) - 266
} - 267
let expected_size = img.width * img.height * img.channels - 268●
if img.data.length() != expected_size { - 269●
raise @types.LoadError::DecodeFailed( - 270
"scan_document_preprocess: 数据大小不匹配,期望 " + - 271●
expected_size.to_string() + - 272
",实际 " + - 273●
img.data.length().to_string(), - 274
) - 275
} - 276
let mut result = img - 277
// 1. 去噪(中值滤波简化版) - 278
if config.denoise { - 279●
result = denoise_scan(result) - 280
} - 281
// 2. 对比度增强 - 282●
result = enhance_contrast_scan(result) - 283
// 3. 二值化 - 284●
result = match config.binarization_method { - 285●
"otsu" => binarize_otsu_scan(result) - 286●
"adaptive" => binarize_adaptive_scan(result) - 287●
"sauvola" => binarize_sauvola_scan(result) - 288●
_ => binarize_otsu_scan(result) - 289
} - 290
result - 291
} - 292
- 293
///| - 294
/// 扫描文档去噪(简化版中值滤波) - 295
fn denoise_scan(img : @types.Image) -> @types.Image { - 296●
let w = img.width - 297
let h = img.height - 298
let channels = img.channels - 299●
let out_data : Array[Byte] = Array::make(w * h * channels, b'\x00') - 300
for y in 0..<h { - 301●
for x in 0..<w { - 302●
let idx = (y * w + x) * channels - 303
for c in 0..<channels { - 304
// 3x3 中值滤波(简化版:取 5 个点的中值) - 305●
let values : Array[Int32] = [] - 306
// 中心 - 307●
values.push(img.data[idx + c].to_int()) - 308
// 上 - 309
if y > 0 { - 310●
values.push(img.data[((y - 1) * w + x) * channels + c].to_int()) - 311
} - 312
// 下 - 313
if y < h - 1 { - 314●
values.push(img.data[((y + 1) * w + x) * channels + c].to_int()) - 315
} - 316
// 左 - 317
if x > 0 { - 318●
values.push(img.data[(y * w + x - 1) * channels + c].to_int()) - 319
} - 320
// 右 - 321
if x < w - 1 { - 322●
values.push(img.data[(y * w + x + 1) * channels + c].to_int()) - 323
} - 324
// 排序取中值 - 325●
for i in 0..<values.length() { - 326●
for j in 0..<(values.length() - i - 1) { - 327●
if values[j] > values[j + 1] { - 328●
let temp = values[j] - 329
values[j] = values[j + 1] - 330
values[j + 1] = temp - 331
} - 332
} - 333
} - 334●
let median = values[values.length() / 2] - 335●
out_data[idx + c] = median.to_byte() - 336
} - 337
} - 338
} - 339
@types.Image::{ - 340
width: w, - 341
height: h, - 342
channels, - 343●
data: Bytes::from_array(out_data), - 344
} - 345
} - 346
- 347
///| - 348
/// 扫描文档对比度增强(直方图拉伸) - 349
fn enhance_contrast_scan(img : @types.Image) -> @types.Image { - 350●
let w = img.width - 351
let h = img.height - 352
let channels = img.channels - 353
// 计算最小值和最大值(忽略 1% 极值) - 354
let histogram : Array[Int32] = [] - 355
for _ in 0..<256 { - 356●
histogram.push(0) - 357
} - 358
for y in 0..<h { - 359●
for x in 0..<w { - 360●
let idx = (y * w + x) * channels - 361
let gray = if channels >= 3 { - 362●
(0.299 * img.data[idx].to_double() + - 363●
0.587 * img.data[idx + 1].to_double() + - 364●
0.114 * img.data[idx + 2].to_double()).to_int() - 365
} else { - 366●
img.data[idx].to_int() - 367
} - 368
histogram[gray] += 1 - 369
} - 370
} - 371
let total = w * h - 372
let lower_count = total / 100 - 373
let upper_count = total - lower_count - 374
let mut min_val = 0 - 375
let mut max_val = 255 - 376
let mut cum = 0 - 377
for i in 0..<256 { - 378●
cum += histogram[i] - 379
if cum >= lower_count && min_val == 0 { - 380●
min_val = i - 381
} - 382
if cum >= upper_count { - 383●
max_val = i - 384
break - 385
} - 386
} - 387
// 应用拉伸 - 388●
let out_data : Array[Byte] = Array::make(w * h * channels, b'\x00') - 389●
let range = (max_val - min_val).max(1) - 390
for y in 0..<h { - 391●
for x in 0..<w { - 392●
let idx = (y * w + x) * channels - 393
for c in 0..<channels { - 394●
let val = img.data[idx + c].to_int() - 395●
let stretched = ((val - min_val) * 255 / range).min(255).max(0) - 396●
out_data[idx + c] = stretched.to_byte() - 397
} - 398
} - 399
} - 400
@types.Image::{ - 401
width: w, - 402
height: h, - 403
channels, - 404●
data: Bytes::from_array(out_data), - 405
} - 406
} - 407
- 408
///| - 409
/// Otsu 二值化 - 410
fn binarize_otsu_scan(img : @types.Image) -> @types.Image { - 411●
let w = img.width - 412
let h = img.height - 413
let channels = img.channels - 414
// 计算直方图 - 415
let histogram : Array[Int32] = [] - 416
for _ in 0..<256 { - 417●
histogram.push(0) - 418
} - 419
for y in 0..<h { - 420●
for x in 0..<w { - 421●
let idx = (y * w + x) * channels - 422
let gray = if channels >= 3 { - 423○
(0.299 * img.data[idx].to_double() + - 424○
0.587 * img.data[idx + 1].to_double() + - 425○
0.114 * img.data[idx + 2].to_double()).to_int() - 426
} else { - 427●
img.data[idx].to_int() - 428
} - 429
histogram[gray] += 1 - 430
} - 431
} - 432
// Otsu 阈值计算 - 433
let total = w * h - 434
let mut sum_total = 0.0 - 435
for i in 0..<256 { - 436●
sum_total += i.to_double() * histogram[i].to_double() - 437
} - 438
let mut sum_bg = 0.0 - 439
let mut weight_bg = 0 - 440
let mut max_variance = 0.0 - 441
let mut threshold = 128 - 442
for i in 0..<256 { - 443●
weight_bg += histogram[i] - 444
if weight_bg == 0 { - 445●
continue - 446
} - 447
let weight_fg = total - weight_bg - 448
if weight_fg == 0 { - 449●
break - 450
} - 451●
sum_bg += i.to_double() * histogram[i].to_double() - 452●
let mean_bg = sum_bg / weight_bg.to_double() - 453●
let mean_fg = (sum_total - sum_bg) / weight_fg.to_double() - 454●
let variance = weight_bg.to_double() * - 455●
weight_fg.to_double() * - 456
(mean_bg - mean_fg) * - 457
(mean_bg - mean_fg) - 458
if variance > max_variance { - 459●
max_variance = variance - 460
threshold = i - 461
} - 462
} - 463
// 应用二值化 - 464●
let out_data : Array[Byte] = Array::make(w * h, b'\x00') - 465
for y in 0..<h { - 466●
for x in 0..<w { - 467●
let idx = (y * w + x) * channels - 468
let gray = if channels >= 3 { - 469○
(0.299 * img.data[idx].to_double() + - 470○
0.587 * img.data[idx + 1].to_double() + - 471○
0.114 * img.data[idx + 2].to_double()).to_int() - 472
} else { - 473●
img.data[idx].to_int() - 474
} - 475●
out_data[y * w + x] = if gray > threshold { b'\xFF' } else { b'\x00' } - 476
} - 477
} - 478
@types.Image::{ - 479
width: w, - 480
height: h, - 481
channels: 1, - 482●
data: Bytes::from_array(out_data), - 483
} - 484
} - 485
- 486
///| - 487
/// 自适应二值化(简化版) - 488
fn binarize_adaptive_scan(img : @types.Image) -> @types.Image { - 489●
let w = img.width - 490
let h = img.height - 491
let channels = img.channels - 492
let block_size = 15 - 493
let c = 10 - 494●
let out_data : Array[Byte] = Array::make(w * h, b'\x00') - 495
for y in 0..<h { - 496●
for x in 0..<w { - 497
// 计算局部均值 - 498●
let mut sum = 0 - 499
let mut count = 0 - 500
for dy_idx in 0..<block_size { - 501●
let dy = dy_idx - block_size / 2 - 502
for dx_idx in 0..<block_size { - 503●
let dx = dx_idx - block_size / 2 - 504
let ny = y + dy - 505
let nx = x + dx - 506
if ny >= 0 && ny < h && nx >= 0 && nx < w { - 507●
let idx = (ny * w + nx) * channels - 508
let gray = if channels >= 3 { - 509●
(0.299 * img.data[idx].to_double() + - 510●
0.587 * img.data[idx + 1].to_double() + - 511●
0.114 * img.data[idx + 2].to_double()).to_int() - 512
} else { - 513●
img.data[idx].to_int() - 514
} - 515
sum += gray - 516
count += 1 - 517
} - 518
} - 519
} - 520◐
let local_mean = if count > 0 { sum / count } else { 128 } - 521
let idx = (y * w + x) * channels - 522
let gray = if channels >= 3 { - 523●
(0.299 * img.data[idx].to_double() + - 524●
0.587 * img.data[idx + 1].to_double() + - 525●
0.114 * img.data[idx + 2].to_double()).to_int() - 526
} else { - 527●
img.data[idx].to_int() - 528
} - 529
out_data[y * w + x] = if gray > local_mean - c { - 530●
b'\xFF' - 531
} else { - 532●
b'\x00' - 533
} - 534
} - 535
} - 536
@types.Image::{ - 537
width: w, - 538
height: h, - 539
channels: 1, - 540●
data: Bytes::from_array(out_data), - 541
} - 542
} - 543
- 544
///| - 545
/// Sauvola 二值化(简化版) - 546
fn binarize_sauvola_scan(img : @types.Image) -> @types.Image { - 547●
let w = img.width - 548
let h = img.height - 549
let channels = img.channels - 550
let window_size = 15 - 551
let k = 0.2 - 552
let r = 128.0 - 553●
let out_data : Array[Byte] = Array::make(w * h, b'\x00') - 554
for y in 0..<h { - 555●
for x in 0..<w { - 556
// 计算局部均值和标准差 - 557●
let mut sum = 0.0 - 558
let mut sum_sq = 0.0 - 559
let mut count = 0 - 560
for dy_idx in 0..<window_size { - 561●
let dy = dy_idx - window_size / 2 - 562
for dx_idx in 0..<window_size { - 563●
let dx = dx_idx - window_size / 2 - 564
let ny = y + dy - 565
let nx = x + dx - 566
if ny >= 0 && ny < h && nx >= 0 && nx < w { - 567●
let idx = (ny * w + nx) * channels - 568
let gray = if channels >= 3 { - 569○
0.299 * img.data[idx].to_double() + - 570○
0.587 * img.data[idx + 1].to_double() + - 571○
0.114 * img.data[idx + 2].to_double() - 572
} else { - 573●
img.data[idx].to_double() - 574
} - 575
sum += gray - 576
sum_sq += gray * gray - 577
count += 1 - 578
} - 579
} - 580
} - 581◐
let mean = if count > 0 { sum / count.to_double() } else { 128.0 } - 582
let variance = if count > 0 { - 583●
sum_sq / count.to_double() - mean * mean - 584
} else { - 585○
0.0 - 586
} - 587●
let std = if variance > 0.0 { variance.sqrt() } else { 0.0 } - 588
// Sauvola 阈值 - 589
let threshold = mean * (1.0 + k * (std / r - 1.0)) - 590
let idx = (y * w + x) * channels - 591
let gray = if channels >= 3 { - 592○
0.299 * img.data[idx].to_double() + - 593○
0.587 * img.data[idx + 1].to_double() + - 594○
0.114 * img.data[idx + 2].to_double() - 595
} else { - 596●
img.data[idx].to_double() - 597
} - 598●
out_data[y * w + x] = if gray > threshold { b'\xFF' } else { b'\x00' } - 599
} - 600
} - 601
@types.Image::{ - 602
width: w, - 603
height: h, - 604
channels: 1, - 605●
data: Bytes::from_array(out_data), - 606
} - 607
} - 608
- 609
///| - 610
/// 版面分析(基于投影的文本块检测) - 611
pub fn analyze_layout_scan( - 612
binary_img : @types.Image, - 613
) -> Array[TextBlock] raise @types.LoadError { - 614
// 输入验证 - 615●
if binary_img.width <= 0 || binary_img.height <= 0 { - 616●
raise @types.LoadError::DecodeFailed( - 617
"analyze_layout_scan: 图像尺寸必须大于0", - 618
) - 619
} - 620
if binary_img.channels != 1 { - 621●
raise @types.LoadError::DecodeFailed( - 622
"analyze_layout_scan: 仅支持单通道二值图", - 623
) - 624
} - 625
let expected_size = binary_img.width * binary_img.height - 626●
if binary_img.data.length() != expected_size { - 627●
raise @types.LoadError::DecodeFailed( - 628
"analyze_layout_scan: 数据大小不匹配,期望 " + - 629●
expected_size.to_string() + - 630
",实际 " + - 631●
binary_img.data.length().to_string(), - 632
) - 633
} - 634
let w = binary_img.width - 635
let h = binary_img.height - 636
// 水平投影(检测文本行) - 637
let horizontal_proj : Array[Int32] = [] - 638
for y in 0..<h { - 639●
let mut count = 0 - 640
for x in 0..<w { - 641●
if binary_img.data[y * w + x] == b'\x00' { - 642●
count += 1 - 643
} - 644
} - 645●
horizontal_proj.push(count) - 646
} - 647
// 检测文本行区域 - 648
let blocks : Array[TextBlock] = [] - 649
let mut in_line = false - 650
let mut line_start = 0 - 651
let mut line_end = 0 - 652
let mut reading_order = 0 - 653
for y in 0..<h { - 654●
if horizontal_proj[y] > w / 50 { - 655●
if !in_line { - 656●
line_start = y - 657
in_line = true - 658
} - 659
line_end = y - 660●
} else if in_line { - 661
// 检测这一行的文本范围 - 662●
let mut min_x = w - 663
let mut max_x = 0 - 664
for yy in line_start..<=line_end { - 665●
for x in 0..<w { - 666●
if binary_img.data[yy * w + x] == b'\x00' { - 667●
if x < min_x { - 668●
min_x = x - 669
} - 670
if x > max_x { - 671●
max_x = x - 672
} - 673
} - 674
} - 675
} - 676
if max_x > min_x { - 677●
blocks.push(TextBlock::{ - 678
x: min_x, - 679
y: line_start, - 680
width: max_x - min_x + 1, - 681
height: line_end - line_start + 1, - 682
block_type: "text", - 683
text: "", - 684
confidence: 0.0, - 685
reading_order, - 686
}) - 687
reading_order += 1 - 688
} - 689
in_line = false - 690
} - 691
} - 692
blocks - 693
} - 694
- 695
///| - 696
/// 扫描文档 OCR 完整流水线 - 697
pub fn scan_ocr_recognize( - 698
img : @types.Image, - 699
config : ScanOCRConfig, - 700
) -> OCRPageResult raise @types.LoadError { - 701
// 输入验证 - 702●
if img.width <= 0 || img.height <= 0 { - 703●
raise @types.LoadError::DecodeFailed( - 704
"scan_ocr_recognize: 图像尺寸必须大于0", - 705
) - 706
} - 707
if img.channels < 1 || img.channels > 4 { - 708●
raise @types.LoadError::DecodeFailed( - 709
"scan_ocr_recognize: 通道数必须在1-4之间", - 710
) - 711
} - 712
let expected_size = img.width * img.height * img.channels - 713●
if img.data.length() != expected_size { - 714●
raise @types.LoadError::DecodeFailed( - 715
"scan_ocr_recognize: 数据大小不匹配,期望 " + - 716●
expected_size.to_string() + - 717
",实际 " + - 718●
img.data.length().to_string(), - 719
) - 720
} - 721
let _ = 0.0 // 简化,实际需要计时 - 722
// 1. 预处理 - 723●
let preprocessed = scan_document_preprocess(img, config) - 724
// 2. 版面分析 - 725
let blocks = if config.layout_analysis { - 726●
analyze_layout_scan(preprocessed) - 727
} else { - 728●
let single_block : Array[TextBlock] = [] - 729●
single_block.push(TextBlock::{ - 730
x: 0, - 731
y: 0, - 732
width: img.width, - 733
height: img.height, - 734
block_type: "text", - 735
text: "", - 736
confidence: 0.0, - 737
reading_order: 0, - 738
}) - 739
single_block - 740
} - 741
// 3. 对每个文本块进行识别(简化版:返回占位文本) - 742
// 实际应该调用对应的 OCR 识别函数 - 743
let mut full_text = "" - 744
let mut total_confidence = 0.0 - 745
let recognized_blocks : Array[TextBlock] = [] - 746●
for i in 0..<blocks.length() { - 747
// 简化版识别:返回块的位置信息 - 748●
let block_text = "[文本块 " + - 749●
i.to_string() + - 750
": " + - 751●
blocks[i].width.to_string() + - 752
"x" + - 753●
blocks[i].height.to_string() + - 754
"]" - 755
let new_block = TextBlock::{ - 756
x: blocks[i].x, - 757
y: blocks[i].y, - 758
width: blocks[i].width, - 759
height: blocks[i].height, - 760
block_type: blocks[i].block_type, - 761
text: block_text, - 762
confidence: 0.85, - 763
reading_order: blocks[i].reading_order, - 764
} - 765●
recognized_blocks.push(new_block) - 766
full_text = full_text + block_text + "\n" - 767
total_confidence += new_block.confidence - 768
} - 769●
let avg_confidence = if recognized_blocks.length() > 0 { - 770●
total_confidence / recognized_blocks.length().to_double() - 771
} else { - 772●
0.0 - 773
} - 774
OCRPageResult::{ - 775
page_number: 1, - 776
width: img.width, - 777
height: img.height, - 778
blocks: recognized_blocks, - 779
full_text, - 780
average_confidence: avg_confidence, - 781
processing_time_ms: 0.0, - 782
} - 783
} - 784
- 785
///| - 786
/// 批量扫描文档 OCR - 787
pub fn batch_scan_ocr( - 788
images : Array[@types.Image], - 789
config : ScanOCRConfig, - 790
) -> Array[OCRPageResult] raise @types.LoadError { - 791
// 输入验证 - 792●
if images.length() == 0 { - 793●
raise @types.LoadError::DecodeFailed( - 794
"batch_scan_ocr: 图像列表不能为空", - 795
) - 796
} - 797●
for i in 0..<images.length() { - 798●
if images[i].width <= 0 || images[i].height <= 0 { - 799●
raise @types.LoadError::DecodeFailed( - 800●
"batch_scan_ocr: 第 " + i.to_string() + " 张图像尺寸必须大于0", - 801
) - 802
} - 803
} - 804
let results : Array[OCRPageResult] = [] - 805●
for i in 0..<images.length() { - 806●
let result = scan_ocr_recognize(images[i], config) - 807
let new_result = OCRPageResult::{ - 808
page_number: i + 1, - 809
width: result.width, - 810
height: result.height, - 811
blocks: result.blocks, - 812
full_text: result.full_text, - 813
average_confidence: result.average_confidence, - 814
processing_time_ms: result.processing_time_ms, - 815
} - 816●
results.push(new_result) - 817
} - 818
results - 819
} - 820
- 821
///| - 822
/// OCR 结果导出为纯文本 - 823
pub fn ocr_result_to_text(result : OCRPageResult) -> String { - 824●
result.full_text - 825
} - 826
- 827
///| - 828
/// OCR 结果导出为 hOCR 格式(简化版) - 829
pub fn ocr_result_to_hocr(result : OCRPageResult) -> String { - 830●
let mut hocr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" - 831
hocr = hocr + - 832
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n" - 833
hocr = hocr + - 834
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" - 835
hocr = hocr + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" - 836
hocr = hocr + "<head>\n" - 837
hocr = hocr + - 838
"<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />\n" - 839
hocr = hocr + "<title>OCR Result</title>\n" - 840
hocr = hocr + "</head>\n" - 841
hocr = hocr + "<body>\n" - 842
hocr = hocr + - 843
"<div class=\"ocr_page\" title=\"image; bbox 0 0 " + - 844●
result.width.to_string() + - 845
" " + - 846●
result.height.to_string() + - 847
"\">\n" - 848
for block in result.blocks { - 849●
hocr = hocr + - 850
"<div class=\"ocr_carea\" title=\"bbox " + - 851●
block.x.to_string() + - 852
" " + - 853●
block.y.to_string() + - 854
" " + - 855●
(block.x + block.width).to_string() + - 856
" " + - 857●
(block.y + block.height).to_string() + - 858
"\">\n" - 859
hocr = hocr + "<p class=\"ocr_par\">\n" - 860
hocr = hocr + - 861
"<span class=\"ocr_line\" title=\"bbox " + - 862●
block.x.to_string() + - 863
" " + - 864●
block.y.to_string() + - 865
" " + - 866●
(block.x + block.width).to_string() + - 867
" " + - 868●
(block.y + block.height).to_string() + - 869
"\">" - 870
hocr = hocr + block.text - 871
hocr = hocr + "</span>\n" - 872
hocr = hocr + "</p>\n" - 873
hocr = hocr + "</div>\n" - 874
} - 875
hocr = hocr + "</div>\n" - 876
hocr = hocr + "</body>\n" - 877
hocr = hocr + "</html>\n" - 878
hocr - 879
} - 880
- 881
///| - 882
/// OCR 结果导出为 JSON - 883
pub fn ocr_result_to_json(result : OCRPageResult) -> String { - 884●
let mut json = "{\n" - 885●
json = json + " \"page_number\": " + result.page_number.to_string() + ",\n" - 886●
json = json + " \"width\": " + result.width.to_string() + ",\n" - 887●
json = json + " \"height\": " + result.height.to_string() + ",\n" - 888
json = json + - 889
" \"average_confidence\": " + - 890●
result.average_confidence.to_string() + - 891
",\n" - 892
json = json + " \"blocks\": [\n" - 893●
for i in 0..<result.blocks.length() { - 894●
let block = result.blocks[i] - 895
json = json + " {\n" - 896●
json = json + " \"x\": " + block.x.to_string() + ",\n" - 897●
json = json + " \"y\": " + block.y.to_string() + ",\n" - 898●
json = json + " \"width\": " + block.width.to_string() + ",\n" - 899●
json = json + " \"height\": " + block.height.to_string() + ",\n" - 900
json = json + " \"type\": \"" + block.block_type + "\",\n" - 901
json = json + " \"text\": \"" + block.text + "\",\n" - 902
json = json + - 903
" \"confidence\": " + - 904●
block.confidence.to_string() + - 905
",\n" - 906
json = json + - 907
" \"reading_order\": " + - 908●
block.reading_order.to_string() + - 909
"\n" - 910
json = json + " }" - 911●
if i < result.blocks.length() - 1 { - 912●
json = json + "," - 913
} - 914
json = json + "\n" - 915
} - 916
json = json + " ],\n" - 917
json = json + " \"full_text\": \"" + result.full_text + "\"\n" - 918
json = json + "}\n" - 919
json - 920
}