image.vision\ocr\multilingual_ocr.mbt
92.3% · 144 / 156 points · 676 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/multilingual_ocr - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 多语言混合识别 - 7
// 中英混排、标点符号优化、语言检测、多语言识别流水线 - 8
- 9
///| - 10
/// 语言类型 - 11
/// `#non_exhaustive` 表示未来可能添加新构造器 - 12
#derive(Eq, @debug.Debug) - 13
#non_exhaustive - 14
pub(all) enum LanguageType { - 15
Chinese - 16
English - 17
Digit - 18
Punctuation - 19
Mixed - 20
Unknown - 21
} - 22
- 23
///| - 24
pub extend LanguageType with @debug.Debug::{to_repr} - 25
- 26
///| - 27
pub extend LanguageType with Eq::{not_equal, equal} - 28
- 29
///| - 30
/// 多语言识别配置 - 31
#derive(Eq, @debug.Debug) - 32
pub(all) struct MultilingualOcrConfig { - 33
enable_chinese : Bool - 34
enable_english : Bool - 35
enable_digits : Bool - 36
enable_punctuation : Bool - 37
target_size : Int32 - 38
distance_metric : String - 39
auto_language_detection : Bool - 40
} - 41
- 42
///| - 43
pub extend MultilingualOcrConfig with Eq::{not_equal, equal} - 44
- 45
///| - 46
pub extend MultilingualOcrConfig with @debug.Debug::{to_repr} - 47
- 48
///| - 49
/// 创建默认多语言识别配置 - 50
pub fn multilingual_ocr_default_config() -> MultilingualOcrConfig { - 51●
MultilingualOcrConfig::{ - 52
enable_chinese: true, - 53
enable_english: true, - 54
enable_digits: true, - 55
enable_punctuation: true, - 56
target_size: 48, - 57
distance_metric: "euclidean", - 58
auto_language_detection: true, - 59
} - 60
} - 61
- 62
///| - 63
/// 标点符号模板 - 64
#derive(Eq, @debug.Debug) - 65
pub(all) struct PunctuationTemplate { - 66
char : String - 67
features : Array[Double] - 68
width_ratio : Double // 相对宽度(窄/宽) - 69
} - 70
- 71
///| - 72
pub extend PunctuationTemplate with Eq::{not_equal, equal} - 73
- 74
///| - 75
pub extend PunctuationTemplate with @debug.Debug::{to_repr} - 76
- 77
///| - 78
/// 生成标点符号模板 - 79
pub fn generate_punctuation_templates() -> Array[PunctuationTemplate] { - 80●
let templates : Array[PunctuationTemplate] = [] - 81
// 常见标点符号 - 82
let punctuations : Array[(String, Double)] = [ - 83
(",", 0.3), // 逗号(窄) - 84
(".", 0.3), // 句号(窄) - 85
("!", 0.3), // 感叹号(窄) - 86
("?", 0.5), // 问号(中) - 87
(";", 0.3), // 分号(窄) - 88
(":", 0.3), // 冒号(窄) - 89
("\"", 0.4), // 引号(中) - 90
("'", 0.2), // 单引号(窄) - 91
("(", 0.4), // 左括号(中) - 92
(")", 0.4), // 右括号(中) - 93
("[", 0.4), // 左方括号 - 94
("]", 0.4), // 右方括号 - 95
("{", 0.5), // 左花括号 - 96
("}", 0.5), // 右花括号 - 97
("-", 0.6), // 连字符(宽) - 98
("_", 0.6), // 下划线(宽) - 99
("/", 0.4), // 斜杠 - 100
("\\", 0.4), // 反斜杠 - 101
("|", 0.2), // 竖线(窄) - 102
("@", 0.7), // at符号(宽) - 103
("#", 0.6), // 井号 - 104
("$", 0.5), // 美元符号 - 105
("%", 0.6), // 百分号 - 106
("^", 0.5), // 脱字符 - 107
("&", 0.6), // 和号 - 108
("*", 0.5), // 星号 - 109
("+", 0.5), // 加号 - 110
("=", 0.6), // 等号 - 111
("<", 0.5), // 小于号 - 112
(">", 0.5), // 大于号 - 113
("~", 0.6), // 波浪号 - 114
("`", 0.3), // 反引号 - 115
(",", 0.5), // 中文逗号 - 116
("。", 0.5), // 中文句号 - 117
("!", 0.5), // 中文感叹号 - 118
("?", 0.6), // 中文问号 - 119
(";", 0.5), // 中文分号 - 120
(":", 0.5), // 中文冒号 - 121
("“", 0.6), // 中文左引号 - 122
("”", 0.6), // 中文右引号 - 123
("(", 0.6), // 中文左括号 - 124
(")", 0.6), // 中文右括号 - 125
("、", 0.4), // 顿号 - 126
("《", 0.6), // 书名号左 - 127
("》", 0.6), // 书名号右 - 128
("—", 0.8), // 破折号 - 129
("…", 0.7), // 省略号 - 130
] - 131
for _tup0 in punctuations { - 132●
let (char, width_ratio) = _tup0 - 133●
let features = generate_punctuation_features(char, width_ratio) - 134●
templates.push(PunctuationTemplate::{ char, features, width_ratio, }) - 135
} - 136
templates - 137
} - 138
- 139
///| - 140
/// 生成标点符号特征 - 141
fn generate_punctuation_features( - 142
char : String, - 143
width_ratio : Double, - 144
) -> Array[Double] { - 145●
let size = 16 - 146●
let features : Array[Double] = Array::make(size * size, 0.0) - 147●
let seed = if char.length() > 0 { char[0].to_int() } else { 0 } - 148
// 基于字符生成简单的标点模式 - 149●
let center_x = (size.to_double() * (0.5 + (width_ratio - 0.5) * 0.3)).to_int() - 150
let center_y = size / 2 - 151
for y in 0..<size { - 152●
for x in 0..<size { - 153●
let h = (seed * 31 + x * 17 + y * 13) % 100 - 154
let dist = ((x - center_x) * (x - center_x) + - 155●
(y - center_y) * (y - center_y)).to_double() - 156
let center_factor = 1.0 - dist / 64.0 - 157●
if h < 40 + (center_factor * 30.0).to_int() { - 158●
features[y * size + x] = 1.0 - 159
} - 160
} - 161
} - 162
features - 163
} - 164
- 165
///| - 166
/// 检测字符语言类型(基于宽高比和尺寸) - 167
pub fn detect_char_language( - 168
char_img : @types.Image, - 169
) -> LanguageType raise @types.LoadError { - 170
// 输入验证 - 171●
if char_img.width <= 0 || char_img.height <= 0 { - 172●
raise @types.LoadError::DecodeFailed( - 173
"detect_char_language: 图像尺寸必须大于0", - 174
) - 175
} - 176
if char_img.channels < 1 || char_img.channels > 4 { - 177●
raise @types.LoadError::DecodeFailed( - 178
"detect_char_language: 通道数必须在1-4之间", - 179
) - 180
} - 181
let expected_size = char_img.width * char_img.height * char_img.channels - 182●
if char_img.data.length() != expected_size { - 183●
raise @types.LoadError::DecodeFailed( - 184
"detect_char_language: 数据大小不匹配,期望 " + - 185●
expected_size.to_string() + - 186
",实际 " + - 187●
char_img.data.length().to_string(), - 188
) - 189
} - 190
let w = char_img.width - 191
let h = char_img.height - 192◐
let ratio = if h > 0 { w.to_double() / h.to_double() } else { 1.0 } - 193
// 中文字符通常接近正方形(ratio 0.8-1.2) - 194
if ratio > 0.75 && ratio < 1.35 && w > 20 && h > 20 { - 195●
return LanguageType::Chinese - 196
} - 197
// 英文字符通常较窄(ratio 0.4-0.8) - 198
if ratio > 0.3 && ratio < 0.75 { - 199●
return LanguageType::English - 200
} - 201
// 数字 - 202
if ratio > 0.4 && ratio < 0.7 { - 203○
return LanguageType::Digit - 204
} - 205
// 标点符号通常很窄或很宽 - 206
if ratio < 0.4 || ratio > 1.35 { - 207●
return LanguageType::Punctuation - 208
} - 209
LanguageType::Unknown - 210
} - 211
- 212
///| - 213
/// 检测文档主要语言 - 214
pub fn detect_document_language( - 215
img : @types.Image, - 216
) -> LanguageType raise @types.LoadError { - 217
// 输入验证 - 218●
if img.width <= 0 || img.height <= 0 { - 219●
raise @types.LoadError::DecodeFailed( - 220
"detect_document_language: 图像尺寸必须大于0", - 221
) - 222
} - 223
if img.channels < 1 || img.channels > 4 { - 224●
raise @types.LoadError::DecodeFailed( - 225
"detect_document_language: 通道数必须在1-4之间", - 226
) - 227
} - 228
let expected_size = img.width * img.height * img.channels - 229●
if img.data.length() != expected_size { - 230●
raise @types.LoadError::DecodeFailed( - 231
"detect_document_language: 数据大小不匹配,期望 " + - 232●
expected_size.to_string() + - 233
",实际 " + - 234●
img.data.length().to_string(), - 235
) - 236
} - 237
// 预处理 - 238●
let preprocessed = ocr_preprocess(img) - 239
// 检测文本行 - 240●
let lines = detect_text_lines_projection(preprocessed) - 241●
if lines.length() == 0 { - 242○
return LanguageType::Unknown - 243
} - 244
// 统计字符宽高比 - 245
let mut chinese_count = 0 - 246
let mut english_count = 0 - 247
let mut digit_count = 0 - 248
// 简单统计:基于文本行的平均字符宽度 - 249
for line in lines { - 250●
let avg_char_width = if line.width > 0 { - 251●
line.width.to_double() / (line.width.to_double() / 15.0).max(1.0) - 252
} else { - 253○
15.0 - 254
} - 255●
let ratio = avg_char_width / line.height.to_double() - 256
if ratio > 0.75 && ratio < 1.35 { - 257●
chinese_count += 1 - 258●
} else if ratio > 0.3 && ratio < 0.75 { - 259●
english_count += 1 - 260
} else { - 261●
digit_count += 1 - 262
} - 263
} - 264
// 判断主要语言 - 265
if chinese_count > english_count && chinese_count > digit_count { - 266●
return LanguageType::Chinese - 267
} - 268
if english_count > chinese_count && english_count > digit_count { - 269●
return LanguageType::English - 270
} - 271
if chinese_count > 0 && english_count > 0 { - 272○
return LanguageType::Mixed - 273
} - 274
LanguageType::Unknown - 275
} - 276
- 277
///| - 278
/// 多语言混合识别(完整流水线) - 279
/// @deprecated 已废弃,请使用 recognize_multilingual_enhanced 代替 - 280
#deprecated("Use recognize_multilingual_enhanced instead", skip_current_package=true) - 281
pub fn recognize_multilingual( - 282
img : @types.Image, - 283
config? : MultilingualOcrConfig, - 284
) -> OcrResult raise @types.LoadError { - 285
// 输入验证 - 286
if img.width <= 0 || img.height <= 0 { - 287
raise @types.LoadError::DecodeFailed( - 288
"recognize_multilingual: 图像尺寸必须大于0", - 289
) - 290
} - 291
if img.channels < 1 || img.channels > 4 { - 292
raise @types.LoadError::DecodeFailed( - 293
"recognize_multilingual: 通道数必须在1-4之间", - 294
) - 295
} - 296
let expected_size = img.width * img.height * img.channels - 297
if img.data.length() != expected_size { - 298
raise @types.LoadError::DecodeFailed( - 299
"recognize_multilingual: 数据大小不匹配,期望 " + - 300
expected_size.to_string() + - 301
",实际 " + - 302
img.data.length().to_string(), - 303
) - 304
} - 305
let cfg = match config { - 306
Some(c) => c - 307
None => multilingual_ocr_default_config() - 308
} - 309
// 1. 预处理 - 310
let preprocessed = ocr_preprocess(img) - 311
// 2. 检测文档主要语言 - 312
let _ = if cfg.auto_language_detection { - 313
detect_document_language(preprocessed) - 314
} else { - 315
LanguageType::Mixed - 316
} - 317
// 3. 字符分割 - 318
let char_regions = segment_multilingual_chars(preprocessed, cfg) - 319
// 4. 生成各语言模板 - 320
let chinese_templates = if cfg.enable_chinese { - 321
generate_3500_chinese_templates(char_set="common100") - 322
} else { - 323
[] - 324
} - 325
let english_templates = if cfg.enable_english { - 326
generate_english_templates(case_sensitive=false) - 327
} else { - 328
[] - 329
} - 330
let digit_templates = if cfg.enable_digits { - 331
generate_digit_templates() - 332
} else { - 333
[] - 334
} - 335
let punctuation_templates = if cfg.enable_punctuation { - 336
generate_punctuation_templates() - 337
} else { - 338
[] - 339
} - 340
// 5. 对每个字符进行识别 - 341
let char_results : Array[OcrCharResult] = [] - 342
let mut text = "" - 343
let mut total_confidence = 0.0 - 344
for _tup1 in char_regions { - 345
let (x, y, w, h) = _tup1 - 346
// 提取字符图像 - 347
let char_img = extract_multilingual_char_region( - 348
preprocessed, - 349
x, - 350
y, - 351
w, - 352
h, - 353
cfg.target_size, - 354
) - 355
// 检测字符语言类型 - 356
let char_language = detect_char_language(char_img) - 357
// 根据语言类型选择模板 - 358
let result = match char_language { - 359
LanguageType::Chinese => - 360
if chinese_templates.length() > 0 { - 361
match_multilingual_template( - 362
extract_multilingual_features(char_img, 16), - 363
chinese_templates, - 364
cfg.distance_metric, - 365
) - 366
} else { - 367
("?", 0.0) - 368
} - 369
LanguageType::English => - 370
if english_templates.length() > 0 { - 371
match_multilingual_template( - 372
extract_multilingual_features(char_img, 16), - 373
english_templates, - 374
cfg.distance_metric, - 375
) - 376
} else { - 377
("?", 0.0) - 378
} - 379
LanguageType::Digit => - 380
if digit_templates.length() > 0 { - 381
match_multilingual_template( - 382
extract_multilingual_features(char_img, 16), - 383
digit_templates, - 384
cfg.distance_metric, - 385
) - 386
} else { - 387
("?", 0.0) - 388
} - 389
LanguageType::Punctuation => - 390
if punctuation_templates.length() > 0 { - 391
match_punctuation_template( - 392
extract_multilingual_features(char_img, 16), - 393
punctuation_templates, - 394
) - 395
} else { - 396
("?", 0.0) - 397
} - 398
_ => { - 399
// 未知语言,尝试所有模板 - 400
let all_templates : Array[(String, Array[Double])] = [] - 401
for t in chinese_templates { - 402
all_templates.push(t) - 403
} - 404
for t in english_templates { - 405
all_templates.push(t) - 406
} - 407
for t in digit_templates { - 408
all_templates.push(t) - 409
} - 410
if all_templates.length() > 0 { - 411
match_multilingual_template( - 412
extract_multilingual_features(char_img, 16), - 413
all_templates, - 414
cfg.distance_metric, - 415
) - 416
} else { - 417
("?", 0.0) - 418
} - 419
} - 420
} - 421
text += result.0 - 422
total_confidence += result.1 - 423
char_results.push(OcrCharResult::{ - 424
char: result.0, - 425
confidence: result.1, - 426
x, - 427
y, - 428
width: w, - 429
height: h, - 430
}) - 431
} - 432
let avg_confidence = if char_results.length() > 0 { - 433
total_confidence / char_results.length().to_double() - 434
} else { - 435
0.0 - 436
} - 437
OcrResult::{ text, confidence: avg_confidence, characters: char_results, } - 438
} - 439
- 440
///| - 441
/// 多语言字符分割 - 442
fn segment_multilingual_chars( - 443
img : @types.Image, - 444
_cfg : MultilingualOcrConfig, - 445
) -> Array[(Int32, Int32, Int32, Int32)] { - 446●
let w = img.width - 447
let h = img.height - 448
let data = img.data - 449
// 简单连通域标记 - 450●
let labels : Array[Int32] = Array::make(w * h, 0) - 451
let mut next_label = 1 - 452
for y in 0..<h { - 453●
for x in 0..<w { - 454●
if data[y * w + x].to_int() > 128 { - 455●
let mut label = 0 - 456
if x > 0 && labels[y * w + x - 1] > 0 { - 457●
label = labels[y * w + x - 1] - 458
} - 459
if y > 0 && labels[(y - 1) * w + x] > 0 { - 460●
if label == 0 { - 461●
label = labels[(y - 1) * w + x] - 462
} - 463
} - 464
if label == 0 { - 465●
label = next_label - 466
next_label += 1 - 467
} - 468
labels[y * w + x] = label - 469
} - 470
} - 471
} - 472
// 计算边界框 - 473●
let min_x : Array[Int32] = Array::make(next_label, w) - 474●
let max_x : Array[Int32] = Array::make(next_label, 0) - 475●
let min_y : Array[Int32] = Array::make(next_label, h) - 476●
let max_y : Array[Int32] = Array::make(next_label, 0) - 477●
let area : Array[Int32] = Array::make(next_label, 0) - 478
for y in 0..<h { - 479●
for x in 0..<w { - 480●
let label = labels[y * w + x] - 481
if label > 0 { - 482●
area[label] += 1 - 483
if x < min_x[label] { - 484●
min_x[label] = x - 485
} - 486
if x > max_x[label] { - 487●
max_x[label] = x - 488
} - 489
if y < min_y[label] { - 490●
min_y[label] = y - 491
} - 492
if y > max_y[label] { - 493●
max_y[label] = y - 494
} - 495
} - 496
} - 497
} - 498
// 过滤(多语言更宽松) - 499
let regions : Array[(Int32, Int32, Int32, Int32)] = [] - 500
for label in 1..<next_label { - 501●
let rw = max_x[label] - min_x[label] + 1 - 502
let rh = max_y[label] - min_y[label] + 1 - 503
if rw >= 5 && rw <= 100 && rh >= 8 && rh <= 100 && area[label] > 10 { - 504●
regions.push((min_x[label], min_y[label], rw, rh)) - 505
} - 506
} - 507
regions - 508
} - 509
- 510
///| - 511
/// 提取多语言字符区域 - 512
fn extract_multilingual_char_region( - 513
img : @types.Image, - 514
x : Int32, - 515
y : Int32, - 516
width : Int32, - 517
height : Int32, - 518
target_size : Int32, - 519
) -> @types.Image { - 520●
let w = img.width - 521
let h = img.height - 522●
let crop_w = if x + width > w { w - x } else { width } - 523●
let crop_h = if y + height > h { h - y } else { height } - 524
if crop_w <= 0 || crop_h <= 0 { - 525●
let empty : Array[Byte] = Array::make(target_size * target_size, b'\x00') - 526
return @types.Image::{ - 527
width: target_size, - 528
height: target_size, - 529
channels: 1, - 530●
data: Bytes::from_array(empty), - 531
} - 532
} - 533●
let out : Array[Byte] = Array::make(target_size * target_size, b'\x00') - 534
let data = img.data - 535
for py in 0..<target_size { - 536●
for px in 0..<target_size { - 537●
let src_x = x + px * crop_w / target_size - 538
let src_y = y + py * crop_h / target_size - 539
if src_x < w && src_y < h { - 540●
out[py * target_size + px] = data[src_y * w + src_x] - 541
} - 542
} - 543
} - 544
@types.Image::{ - 545
width: target_size, - 546
height: target_size, - 547
channels: 1, - 548●
data: Bytes::from_array(out), - 549
} - 550
} - 551
- 552
///| - 553
/// 提取多语言字符特征 - 554
fn extract_multilingual_features( - 555
char_img : @types.Image, - 556
grid_size : Int32, - 557
) -> Array[Double] { - 558●
let w = char_img.width - 559
let h = char_img.height - 560
let data = char_img.data - 561
let cell_w = w / grid_size - 562
let cell_h = h / grid_size - 563
let features : Array[Double] = [] - 564
for r in 0..<grid_size { - 565●
for c in 0..<grid_size { - 566●
let mut count = 0 - 567
let mut total = 0 - 568
for py in 0..<cell_h { - 569●
for px in 0..<cell_w { - 570●
let sx = c * cell_w + px - 571
let sy = r * cell_h + py - 572
if sx < w && sy < h { - 573●
total += 1 - 574●
if data[sy * w + sx].to_int() > 128 { - 575●
count += 1 - 576
} - 577
} - 578
} - 579
} - 580
let density = if total > 0 { - 581●
count.to_double() / total.to_double() - 582
} else { - 583○
0.0 - 584
} - 585●
features.push(density) - 586
} - 587
} - 588
features - 589
} - 590
- 591
///| - 592
/// 多语言模板匹配 - 593
fn match_multilingual_template( - 594
features : Array[Double], - 595
templates : Array[(String, Array[Double])], - 596
distance_metric : String, - 597
) -> (String, Double) { - 598●
let mut best_label = "?" - 599
let mut best_dist = 1000000.0 - 600
for _tup2 in templates { - 601●
let (label, template) = _tup2 - 602●
let dist = match distance_metric { - 603●
"manhattan" => manhattan_ml(features, template) - 604●
"cosine" => cosine_ml(features, template) - 605●
_ => euclidean_ml(features, template) - 606
} - 607
if dist < best_dist { - 608●
best_dist = dist - 609
best_label = label - 610
} - 611
} - 612●
let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 } - 613
(best_label, confidence) - 614
} - 615
- 616
///| - 617
/// 标点符号模板匹配 - 618
fn match_punctuation_template( - 619
features : Array[Double], - 620
templates : Array[PunctuationTemplate], - 621
) -> (String, Double) { - 622●
let mut best_label = "?" - 623
let mut best_dist = 1000000.0 - 624
for template in templates { - 625●
let dist = euclidean_ml(features, template.features) - 626
if dist < best_dist { - 627●
best_dist = dist - 628
best_label = template.char - 629
} - 630
} - 631●
let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 } - 632
(best_label, confidence) - 633
} - 634
- 635
///| - 636
/// 局部欧氏距离 - 637
fn euclidean_ml(a : Array[Double], b : Array[Double]) -> Double { - 638◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 639
let mut sum_sq = 0.0 - 640
for i in 0..<n { - 641●
let diff = a[i] - b[i] - 642
sum_sq += diff * diff - 643
} - 644●
sum_sq.sqrt() - 645
} - 646
- 647
///| - 648
/// 局部曼哈顿距离 - 649
fn manhattan_ml(a : Array[Double], b : Array[Double]) -> Double { - 650◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 651
let mut sum = 0.0 - 652
for i in 0..<n { - 653●
sum += (a[i] - b[i]).abs() - 654
} - 655
sum - 656
} - 657
- 658
///| - 659
/// 局部余弦距离 - 660
fn cosine_ml(a : Array[Double], b : Array[Double]) -> Double { - 661◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 662
let mut dot = 0.0 - 663
let mut norm_a = 0.0 - 664
let mut norm_b = 0.0 - 665
for i in 0..<n { - 666●
dot += a[i] * b[i] - 667
norm_a += a[i] * a[i] - 668
norm_b += b[i] * b[i] - 669
} - 670●
let denom = norm_a.sqrt() * norm_b.sqrt() - 671
if denom > 0.0 { - 672●
1.0 - dot / denom - 673
} else { - 674●
1.0 - 675
} - 676
}