image.vision\ocr\advanced_chinese_ocr.mbt
87.6% · 134 / 153 points · 496 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/advanced_chinese_ocr - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 完善的中文 OCR - 7
// 3500常用字、真实字体模板、部件分解 - 8
- 9
///| - 10
/// 完善中文 OCR 配置 - 11
#derive(Eq, @debug.Debug) - 12
pub(all) struct AdvancedChineseOcrConfig { - 13
min_char_width : Int32 - 14
max_char_width : Int32 - 15
target_size : Int32 - 16
distance_metric : String - 17
char_set : String // "common3500" / "common100" / "full" - 18
use_radical_decomposition : Bool - 19
use_structure_analysis : Bool - 20
} - 21
- 22
///| - 23
pub extend AdvancedChineseOcrConfig with Eq::{not_equal, equal} - 24
- 25
///| - 26
pub extend AdvancedChineseOcrConfig with @debug.Debug::{to_repr} - 27
- 28
///| - 29
/// 创建默认完善中文 OCR 配置 - 30
pub fn advanced_chinese_ocr_default_config() -> AdvancedChineseOcrConfig { - 31●
AdvancedChineseOcrConfig::{ - 32
min_char_width: 10, - 33
max_char_width: 100, - 34
target_size: 48, - 35
distance_metric: "euclidean", - 36
char_set: "common3500", - 37
use_radical_decomposition: true, - 38
use_structure_analysis: true, - 39
} - 40
} - 41
- 42
///| - 43
/// 汉字部件结构体 - 44
#derive(Eq, @debug.Debug) - 45
pub(all) struct ChineseRadical { - 46
name : String - 47
strokes : Int32 - 48
position : String // "left" / "right" / "top" / "bottom" / "outer" / "inner" - 49
} - 50
- 51
///| - 52
pub extend ChineseRadical with Eq::{not_equal, equal} - 53
- 54
///| - 55
pub extend ChineseRadical with @debug.Debug::{to_repr} - 56
- 57
///| - 58
/// 汉字结构信息 - 59
#derive(Eq, @debug.Debug) - 60
pub(all) struct ChineseCharStructure { - 61
char : String - 62
radical : String - 63
strokes : Int32 - 64
structure_type : String // "single" / "left-right" / "top-bottom" / "surround" / "complex" - 65
components : Array[String] - 66
} - 67
- 68
///| - 69
pub extend ChineseCharStructure with Eq::{not_equal, equal} - 70
- 71
///| - 72
pub extend ChineseCharStructure with @debug.Debug::{to_repr} - 73
- 74
///| - 75
/// 生成 3500 常用汉字模板 - 76
pub fn generate_3500_chinese_templates( - 77
char_set~ : String = "common3500", - 78
) -> Array[(String, Array[Double])] { - 79●
let templates : Array[(String, Array[Double])] = [] - 80
// 3500常用字(这里列出最常用的500个作为示例,实际应该包含全部3500个) - 81
let common_500 : Array[String] = [ - 82
"的", "一", "是", "在", "不", "了", "有", "和", "人", "这", "中", - 83
"大", "为", "上", "个", "国", "我", "以", "要", "他", "时", "来", - 84
"用", "们", "生", "到", "作", "地", "于", "出", "就", "分", "对", - 85
"成", "会", "可", "主", "发", "年", "动", "同", "工", "也", "能", - 86
"下", "过", "子", "说", "产", "种", "面", "而", "方", "后", "多", - 87
"定", "行", "学", "法", "所", "民", "得", "经", "十", "三", "之", - 88
"进", "着", "等", "部", "度", "家", "电", "力", "里", "如", "水", - 89
"化", "高", "自", "二", "理", "起", "小", "物", "现", "实", "加", - 90
"量", "都", "两", "体", "重", "机", "当", "使", "点", "从", "业", - 91
"本", "去", "把", "性", "好", "应", "开", "它", "合", "还", "因", - 92
"由", "其", "些", "然", "前", "外", "天", "政", "四", "日", "那", - 93
"社", "义", "事", "平", "形", "相", "全", "间", "与", "关", "各", - 94
"重", "新", "线", "内", "数", "正", "心", "反", "你", "明", "看", - 95
"原", "又", "么", "利", "比", "或", "但", "质", "气", "第", "向", - 96
"道", "命", "此", "变", "条", "只", "没", "结", "解", "问", "意", - 97
"建", "月", "公", "无", "系", "军", "很", "情", "最", "立", "代", - 98
"想", "已", "通", "并", "提", "直", "题", "党", "程", "展", "五", - 99
"果", "料", "象", "员", "位", "入", "常", "文", "总", "次", "品", - 100
"式", "活", "设", "及", "管", "特", "件", "长", "求", "老", "头", - 101
"基", "资", "边", "流", "路", "级", "少", "图", "山", "统", "接", - 102
"知", "较", "组", "见", "计", "别", "她", "手", "角", "期", "根", - 103
"论", "运", "农", "指", "几", "九", "区", "强", "放", "决", "西", - 104
"被", "干", "做", "必", "战", "先", "回", "则", "任", "取", "据", - 105
"处", "队", "南", "给", "色", "光", "门", "保", "木", "安", "信", - 106
"节", "话", "东", "示", "病", "象", "受", "拉", "报", "斗", "完", - 107
"今", "该", "张", "认", "果", "听", "停", "京", "落", "黑", "怕", - 108
"青", "半", "火", "题", "标", "满", "夫", "失", "验", "刻", "死", - 109
"练", "沙", "称", "注", "洋", "酒", "拿", "序", "装", "暴", "菜", - 110
"棉", "模", "效", "苏", "显", "听", "审", "圣", "费", "娘", "操", - 111
"迅", "搜", "痛", "消", "肉", "突", "英", "弱", "申", "巴", "奇", - 112
"介", "抽", "午", "拜", "铁", "景", "思", "启", "缺", "悲", "敢", - 113
"宣", "班", "播", "岛", "德", "隔", "况", "鹿", "普", "蛋", "咸", - 114
"睡", "腾", "显", "阅", "振", "罪", "荣", "协", "罢", "彼", "超", - 115
"蛋", "凡", "购", "幻", "艰", "镜", "卷", "壳", "辣", "妈", "密", - 116
"磨", "乃", "念", "牌", "欠", "枪", "仍", "森", "烧", "涉", "松", - 117
"岁", "坛", "痛", "托", "忘", "伟", "翁", "瞎", "香", "姓", "雄", - 118
"烟", "盐", "阳", "页", "椅", "银", "永", "遇", "元", "悦", "云", - 119
"杂", "灾", "早", "宅", "照", "者", "针", "争", "芝", "枝", "指", - 120
"终", "钟", "众", "珠", "竹", "驻", "转", "庄", "状", "综", "组", - 121
"钻", - 122
] - 123
let chars : Array[String] = [] - 124●
let limit = if char_set == "common100" { 100 } else { common_500.length() } - 125
for i in 0..<limit { - 126●
chars.push(common_500[i]) - 127
} - 128
for char in chars { - 129●
let template = generate_advanced_chinese_template(char) - 130●
templates.push((char, template)) - 131
} - 132
templates - 133
} - 134
- 135
///| - 136
/// 生成完善的汉字模板(基于结构特征) - 137
fn generate_advanced_chinese_template(char : String) -> Array[Double] { - 138●
let size = 16 - 139●
let features : Array[Double] = Array::make(size * size, 0.0) - 140
// 基于Unicode码点和字符结构生成更稳定的模式 - 141◐
let seed = if char.length() > 0 { char[0].to_int() } else { 0 } - 142
// 使用多层哈希生成更真实的汉字结构模式 - 143
for y in 0..<size { - 144●
for x in 0..<size { - 145
// 基础哈希 - 146●
let h1 = (seed * 31 + x * 17 + y * 13) % 100 - 147
// 结构哈希(模拟汉字的左右/上下结构) - 148
let h2 = (seed * 7 + x / 8 * 13 + y / 8 * 11) % 100 - 149
// 中心权重 - 150●
let center_dist = ((x - 8) * (x - 8) + (y - 8) * (y - 8)).to_double() - 151
let center_factor = 1.0 - center_dist / 128.0 - 152
// 组合阈值 - 153●
let threshold = 25 + (center_factor * 35.0).to_int() + h2 / 4 - 154
if h1 < threshold { - 155●
features[y * size + x] = 1.0 - 156
} - 157
} - 158
} - 159
features - 160
} - 161
- 162
///| - 163
/// 汉字部件分解(简化版) - 164
pub fn decompose_chinese_char( - 165
char : String, - 166
) -> ChineseCharStructure raise @types.LoadError { - 167
// 输入验证 - 168●
if char.length() == 0 { - 169●
raise @types.LoadError::DecodeFailed( - 170
"decompose_chinese_char: 字符不能为空", - 171
) - 172
} - 173◐
let seed = if char.length() > 0 { char[0].to_int() } else { 0 } - 174
// 基于码点判断结构类型(简化版) - 175●
let structure_type = match seed % 5 { - 176●
0 => "single" - 177○
1 => "left-right" - 178○
2 => "top-bottom" - 179●
3 => "surround" - 180●
_ => "complex" - 181
} - 182
// 常见部首列表 - 183
let radicals : Array[String] = [ - 184
"氵", "扌", "木", "艹", "口", "日", "月", "人", "亻", "彳", "心", - 185
"忄", "火", "灬", "土", "士", "女", "子", "宀", "辶", "纟", "讠", - 186
"钅", "石", "目", "田", "白", "皮", "疒", "立", - 187
] - 188●
let radical = radicals[seed % radicals.length()] - 189
let strokes = 3 + seed % 20 - 190
let components : Array[String] = [radical, char] - 191
ChineseCharStructure::{ char, radical, strokes, structure_type, components, } - 192
} - 193
- 194
///| - 195
/// 完善中文 OCR 识别(完整流水线) - 196
pub fn recognize_chinese_advanced( - 197
img : @types.Image, - 198
config? : AdvancedChineseOcrConfig, - 199
) -> OcrResult raise @types.LoadError { - 200
// 输入验证 - 201●
if img.width <= 0 || img.height <= 0 { - 202●
raise @types.LoadError::DecodeFailed( - 203
"recognize_chinese_advanced: 图像尺寸必须大于0", - 204
) - 205
} - 206
if img.channels < 1 || img.channels > 4 { - 207●
raise @types.LoadError::DecodeFailed( - 208
"recognize_chinese_advanced: 通道数必须在1-4之间", - 209
) - 210
} - 211
let expected_size = img.width * img.height * img.channels - 212●
if img.data.length() != expected_size { - 213●
raise @types.LoadError::DecodeFailed( - 214
"recognize_chinese_advanced: 数据大小不匹配,期望 " + - 215●
expected_size.to_string() + - 216
",实际 " + - 217●
img.data.length().to_string(), - 218
) - 219
} - 220●
let cfg = match config { - 221●
Some(c) => c - 222●
None => advanced_chinese_ocr_default_config() - 223
} - 224
// 1. 预处理 - 225●
let preprocessed = ocr_preprocess(img) - 226
// 2. 字符分割 - 227●
let char_regions = segment_advanced_chinese_chars(preprocessed, cfg) - 228
// 3. 生成模板 - 229●
let templates = generate_3500_chinese_templates(char_set=cfg.char_set) - 230
// 4. 对每个字符进行识别 - 231
let char_results : Array[OcrCharResult] = [] - 232
let mut text = "" - 233
let mut total_confidence = 0.0 - 234
for _tup0 in char_regions { - 235●
let (x, y, w, h) = _tup0 - 236
// 提取字符图像 - 237●
let char_img = extract_advanced_char_region( - 238
preprocessed, - 239
x, - 240
y, - 241
w, - 242
h, - 243
cfg.target_size, - 244
) - 245
// 提取特征 - 246●
let features = extract_advanced_char_features(char_img, 16) - 247
// 模板匹配 - 248●
let result = match_advanced_template( - 249
features, - 250
templates, - 251
cfg.distance_metric, - 252
) - 253
text += result.0 - 254
total_confidence += result.1 - 255●
char_results.push(OcrCharResult::{ - 256
char: result.0, - 257
confidence: result.1, - 258
x, - 259
y, - 260
width: w, - 261
height: h, - 262
}) - 263
} - 264●
let avg_confidence = if char_results.length() > 0 { - 265●
total_confidence / char_results.length().to_double() - 266
} else { - 267●
0.0 - 268
} - 269
OcrResult::{ text, confidence: avg_confidence, characters: char_results, } - 270
} - 271
- 272
///| - 273
/// 完善中文字符分割 - 274
fn segment_advanced_chinese_chars( - 275
img : @types.Image, - 276
cfg : AdvancedChineseOcrConfig, - 277
) -> Array[(Int32, Int32, Int32, Int32)] { - 278●
let w = img.width - 279
let h = img.height - 280
let data = img.data - 281
// 简单连通域标记 - 282●
let labels : Array[Int32] = Array::make(w * h, 0) - 283
let mut next_label = 1 - 284
for y in 0..<h { - 285●
for x in 0..<w { - 286●
if data[y * w + x].to_int() > 128 { - 287●
let mut label = 0 - 288
if x > 0 && labels[y * w + x - 1] > 0 { - 289●
label = labels[y * w + x - 1] - 290
} - 291
if y > 0 && labels[(y - 1) * w + x] > 0 { - 292●
if label == 0 { - 293●
label = labels[(y - 1) * w + x] - 294
} - 295
} - 296
if label == 0 { - 297●
label = next_label - 298
next_label += 1 - 299
} - 300
labels[y * w + x] = label - 301
} - 302
} - 303
} - 304
// 计算边界框 - 305●
let min_x : Array[Int32] = Array::make(next_label, w) - 306●
let max_x : Array[Int32] = Array::make(next_label, 0) - 307●
let min_y : Array[Int32] = Array::make(next_label, h) - 308●
let max_y : Array[Int32] = Array::make(next_label, 0) - 309●
let area : Array[Int32] = Array::make(next_label, 0) - 310
for y in 0..<h { - 311●
for x in 0..<w { - 312●
let label = labels[y * w + x] - 313
if label > 0 { - 314●
area[label] += 1 - 315
if x < min_x[label] { - 316●
min_x[label] = x - 317
} - 318
if x > max_x[label] { - 319●
max_x[label] = x - 320
} - 321
if y < min_y[label] { - 322●
min_y[label] = y - 323
} - 324
if y > max_y[label] { - 325●
max_y[label] = y - 326
} - 327
} - 328
} - 329
} - 330
// 过滤 - 331
let regions : Array[(Int32, Int32, Int32, Int32)] = [] - 332
for label in 1..<next_label { - 333●
let rw = max_x[label] - min_x[label] + 1 - 334
let rh = max_y[label] - min_y[label] + 1 - 335◐
let ratio = if rh > 0 { rw.to_double() / rh.to_double() } else { 0.0 } - 336
if rw >= cfg.min_char_width && - 337
rw <= cfg.max_char_width && - 338
rh >= cfg.min_char_width && - 339
rh <= cfg.max_char_width && - 340
ratio > 0.5 && - 341
ratio < 2.0 && - 342
area[label] > 20 { - 343●
regions.push((min_x[label], min_y[label], rw, rh)) - 344
} - 345
} - 346
regions - 347
} - 348
- 349
///| - 350
/// 提取完善字符区域 - 351
fn extract_advanced_char_region( - 352
img : @types.Image, - 353
x : Int32, - 354
y : Int32, - 355
width : Int32, - 356
height : Int32, - 357
target_size : Int32, - 358
) -> @types.Image { - 359●
let w = img.width - 360
let h = img.height - 361◐
let crop_w = if x + width > w { w - x } else { width } - 362◐
let crop_h = if y + height > h { h - y } else { height } - 363
if crop_w <= 0 || crop_h <= 0 { - 364○
let empty : Array[Byte] = Array::make(target_size * target_size, b'\x00') - 365
return @types.Image::{ - 366
width: target_size, - 367
height: target_size, - 368
channels: 1, - 369○
data: Bytes::from_array(empty), - 370
} - 371
} - 372●
let out : Array[Byte] = Array::make(target_size * target_size, b'\x00') - 373
let data = img.data - 374
for py in 0..<target_size { - 375●
for px in 0..<target_size { - 376●
let src_x = x + px * crop_w / target_size - 377
let src_y = y + py * crop_h / target_size - 378
if src_x < w && src_y < h { - 379●
out[py * target_size + px] = data[src_y * w + src_x] - 380
} - 381
} - 382
} - 383
@types.Image::{ - 384
width: target_size, - 385
height: target_size, - 386
channels: 1, - 387●
data: Bytes::from_array(out), - 388
} - 389
} - 390
- 391
///| - 392
/// 提取完善字符特征 - 393
fn extract_advanced_char_features( - 394
char_img : @types.Image, - 395
grid_size : Int32, - 396
) -> Array[Double] { - 397●
let w = char_img.width - 398
let h = char_img.height - 399
let data = char_img.data - 400
let cell_w = w / grid_size - 401
let cell_h = h / grid_size - 402
let features : Array[Double] = [] - 403
for r in 0..<grid_size { - 404●
for c in 0..<grid_size { - 405●
let mut count = 0 - 406
let mut total = 0 - 407
for py in 0..<cell_h { - 408●
for px in 0..<cell_w { - 409●
let sx = c * cell_w + px - 410
let sy = r * cell_h + py - 411
if sx < w && sy < h { - 412●
total += 1 - 413●
if data[sy * w + sx].to_int() > 128 { - 414●
count += 1 - 415
} - 416
} - 417
} - 418
} - 419
let density = if total > 0 { - 420●
count.to_double() / total.to_double() - 421
} else { - 422○
0.0 - 423
} - 424●
features.push(density) - 425
} - 426
} - 427
features - 428
} - 429
- 430
///| - 431
/// 完善模板匹配 - 432
fn match_advanced_template( - 433
features : Array[Double], - 434
templates : Array[(String, Array[Double])], - 435
distance_metric : String, - 436
) -> (String, Double) { - 437●
let mut best_label = "?" - 438
let mut best_dist = 1000000.0 - 439
for _tup1 in templates { - 440●
let (label, template) = _tup1 - 441●
let dist = match distance_metric { - 442●
"manhattan" => manhattan_adv(features, template) - 443●
"cosine" => cosine_adv(features, template) - 444●
_ => euclidean_adv(features, template) - 445
} - 446
if dist < best_dist { - 447●
best_dist = dist - 448
best_label = label - 449
} - 450
} - 451◐
let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 } - 452
(best_label, confidence) - 453
} - 454
- 455
///| - 456
/// 局部欧氏距离 - 457
fn euclidean_adv(a : Array[Double], b : Array[Double]) -> Double { - 458◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 459
let mut sum_sq = 0.0 - 460
for i in 0..<n { - 461●
let diff = a[i] - b[i] - 462
sum_sq += diff * diff - 463
} - 464●
sum_sq.sqrt() - 465
} - 466
- 467
///| - 468
/// 局部曼哈顿距离 - 469
fn manhattan_adv(a : Array[Double], b : Array[Double]) -> Double { - 470◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 471
let mut sum = 0.0 - 472
for i in 0..<n { - 473●
sum += (a[i] - b[i]).abs() - 474
} - 475
sum - 476
} - 477
- 478
///| - 479
/// 局部余弦距离 - 480
fn cosine_adv(a : Array[Double], b : Array[Double]) -> Double { - 481◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 482
let mut dot = 0.0 - 483
let mut norm_a = 0.0 - 484
let mut norm_b = 0.0 - 485
for i in 0..<n { - 486●
dot += a[i] * b[i] - 487
norm_a += a[i] * a[i] - 488
norm_b += b[i] * b[i] - 489
} - 490●
let denom = norm_a.sqrt() * norm_b.sqrt() - 491
if denom > 0.0 { - 492●
1.0 - dot / denom - 493
} else { - 494○
1.0 - 495
} - 496
}