image.vision\ocr\chinese_ocr.mbt
93.5% · 130 / 139 points · 416 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/chinese_ocr - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 中文 OCR 基础 - 7
// 常用汉字识别(基于点阵模板) - 8
- 9
///| - 10
/// 中文 OCR 配置 - 11
#derive(Eq, @debug.Debug) - 12
pub(all) struct ChineseOcrConfig { - 13
min_char_width : Int32 - 14
max_char_width : Int32 - 15
target_size : Int32 - 16
distance_metric : String - 17
char_set : String // "common" / "full" - 18
} - 19
- 20
///| - 21
pub extend ChineseOcrConfig with Eq::{not_equal, equal} - 22
- 23
///| - 24
pub extend ChineseOcrConfig with @debug.Debug::{to_repr} - 25
- 26
///| - 27
/// 创建默认中文 OCR 配置 - 28
pub fn chinese_ocr_default_config() -> ChineseOcrConfig { - 29●
ChineseOcrConfig::{ - 30
min_char_width: 10, - 31
max_char_width: 100, - 32
target_size: 48, - 33
distance_metric: "euclidean", - 34
char_set: "common", - 35
} - 36
} - 37
- 38
///| - 39
/// 生成常用汉字模板(100个常用汉字) - 40
pub fn generate_chinese_templates( - 41
char_set~ : String = "common", - 42
) -> Array[(String, Array[Double])] { - 43●
let templates : Array[(String, Array[Double])] = [] - 44
// 常用汉字列表(100个最常用汉字) - 45
let common_chars : Array[String] = [ - 46
"的", "一", "是", "在", "不", "了", "有", "和", "人", "这", "中", - 47
"大", "为", "上", "个", "国", "我", "以", "要", "他", "时", "来", - 48
"用", "们", "生", "到", "作", "地", "于", "出", "就", "分", "对", - 49
"成", "会", "可", "主", "发", "年", "动", "同", "工", "也", "能", - 50
"下", "过", "子", "说", "产", "种", "面", "而", "方", "后", "多", - 51
"定", "行", "学", "法", "所", "民", "得", "经", "十", "三", "之", - 52
"进", "着", "等", "部", "度", "家", "电", "力", "里", "如", "水", - 53
"化", "高", "自", "二", "理", "起", "小", "物", "现", "实", "加", - 54
"量", "都", "两", "体", "重", "机", "当", "使", "点", "从", "业", - 55
"本", - 56
] - 57
let chars = if char_set == "full" { - 58
// 完整字符集(这里简化,仍然用常用汉字) - 59●
common_chars - 60
} else { - 61●
common_chars - 62
} - 63
for char in chars { - 64●
let template = generate_chinese_char_template(char) - 65●
templates.push((char, template)) - 66
} - 67
templates - 68
} - 69
- 70
///| - 71
/// 生成单个汉字模板(基于16x16点阵简化模式) - 72
fn generate_chinese_char_template(char : String) -> Array[Double] { - 73●
let size = 16 - 74●
let features : Array[Double] = Array::make(size * size, 0.0) - 75
// 简化的汉字模式(基于常见汉字结构) - 76
// 这里使用字符的Unicode码点作为种子,生成伪随机但稳定的模式 - 77◐
let seed = if char.length() > 0 { char[0].to_int() } else { 0 } - 78
// 基于种子生成模式(简化版,实际应该使用真实点阵字体) - 79
for y in 0..<size { - 80●
for x in 0..<size { - 81
// 使用简单的哈希函数生成模式 - 82●
let hash = (seed * 31 + x * 17 + y * 13) % 100 - 83
// 中心区域更可能有像素 - 84●
let center_dist = ((x - 8) * (x - 8) + (y - 8) * (y - 8)).to_double() - 85
let center_factor = 1.0 - center_dist / 128.0 - 86●
let threshold = 30 + (center_factor * 40.0).to_int() - 87
if hash < threshold { - 88●
features[y * size + x] = 1.0 - 89
} - 90
} - 91
} - 92
features - 93
} - 94
- 95
///| - 96
/// 中文 OCR 识别(完整流水线) - 97
pub fn recognize_chinese( - 98
img : @types.Image, - 99
config? : ChineseOcrConfig, - 100
) -> OcrResult raise @types.LoadError { - 101
// 输入验证 - 102●
if img.width <= 0 || img.height <= 0 { - 103●
raise @types.LoadError::DecodeFailed( - 104
"recognize_chinese: 图像尺寸必须大于0", - 105
) - 106
} - 107
if img.channels != 1 { - 108●
raise @types.LoadError::DecodeFailed( - 109
"recognize_chinese: 仅支持单通道灰度图", - 110
) - 111
} - 112
let expected_size = img.width * img.height - 113●
if img.data.length() != expected_size { - 114●
raise @types.LoadError::DecodeFailed( - 115
"recognize_chinese: 数据大小不匹配,期望 " + - 116●
expected_size.to_string() + - 117
",实际 " + - 118●
img.data.length().to_string(), - 119
) - 120
} - 121
- 122●
let cfg = match config { - 123●
Some(c) => c - 124●
None => chinese_ocr_default_config() - 125
} - 126
// 配置验证 - 127
if cfg.min_char_width <= 0 { - 128●
raise @types.LoadError::DecodeFailed( - 129
"recognize_chinese: min_char_width必须大于0", - 130
) - 131
} - 132
if cfg.max_char_width < cfg.min_char_width { - 133●
raise @types.LoadError::DecodeFailed( - 134
"recognize_chinese: max_char_width不能小于min_char_width", - 135
) - 136
} - 137
if cfg.target_size <= 0 { - 138●
raise @types.LoadError::DecodeFailed( - 139
"recognize_chinese: target_size必须大于0", - 140
) - 141
} - 142
// 1. 预处理 - 143●
let preprocessed = ocr_preprocess(img) - 144
// 2. 字符分割(中文字符通常是方块形,使用连通域分割) - 145●
let char_regions = segment_chinese_chars(preprocessed, cfg) - 146
// 3. 生成模板 - 147●
let templates = generate_chinese_templates(char_set=cfg.char_set) - 148
// 4. 对每个字符进行识别 - 149
let char_results : Array[OcrCharResult] = [] - 150
let mut text = "" - 151
let mut total_confidence = 0.0 - 152
for _tup0 in char_regions { - 153●
let (x, y, w, h) = _tup0 - 154
// 提取字符图像 - 155●
let char_img = extract_chinese_char_region( - 156
preprocessed, - 157
x, - 158
y, - 159
w, - 160
h, - 161
cfg.target_size, - 162
) - 163
// 提取特征 - 164●
let features = extract_chinese_char_features(char_img, 16) - 165
// 模板匹配 - 166●
let result = match_chinese_template( - 167
features, - 168
templates, - 169
cfg.distance_metric, - 170
) - 171
text += result.0 - 172
total_confidence += result.1 - 173●
char_results.push(OcrCharResult::{ - 174
char: result.0, - 175
confidence: result.1, - 176
x, - 177
y, - 178
width: w, - 179
height: h, - 180
}) - 181
} - 182●
let avg_confidence = if char_results.length() > 0 { - 183●
total_confidence / char_results.length().to_double() - 184
} else { - 185●
0.0 - 186
} - 187
OcrResult::{ text, confidence: avg_confidence, characters: char_results, } - 188
} - 189
- 190
///| - 191
/// 中文字符分割(基于连通域和方块特征) - 192
fn segment_chinese_chars( - 193
img : @types.Image, - 194
cfg : ChineseOcrConfig, - 195
) -> Array[(Int32, Int32, Int32, Int32)] { - 196●
let w = img.width - 197
let h = img.height - 198
let data = img.data - 199
// 简单连通域标记 - 200●
let labels : Array[Int32] = Array::make(w * h, 0) - 201
let mut next_label = 1 - 202
for y in 0..<h { - 203●
for x in 0..<w { - 204●
if data[y * w + x].to_int() > 128 { - 205●
let mut label = 0 - 206
if x > 0 && labels[y * w + x - 1] > 0 { - 207●
label = labels[y * w + x - 1] - 208
} - 209
if y > 0 && labels[(y - 1) * w + x] > 0 { - 210●
if label == 0 { - 211●
label = labels[(y - 1) * w + x] - 212
} - 213
} - 214
if label == 0 { - 215●
label = next_label - 216
next_label += 1 - 217
} - 218
labels[y * w + x] = label - 219
} - 220
} - 221
} - 222
// 计算每个连通域的边界框 - 223●
let min_x : Array[Int32] = Array::make(next_label, w) - 224●
let max_x : Array[Int32] = Array::make(next_label, 0) - 225●
let min_y : Array[Int32] = Array::make(next_label, h) - 226●
let max_y : Array[Int32] = Array::make(next_label, 0) - 227●
let area : Array[Int32] = Array::make(next_label, 0) - 228
for y in 0..<h { - 229●
for x in 0..<w { - 230●
let label = labels[y * w + x] - 231
if label > 0 { - 232●
area[label] += 1 - 233
if x < min_x[label] { - 234●
min_x[label] = x - 235
} - 236
if x > max_x[label] { - 237●
max_x[label] = x - 238
} - 239
if y < min_y[label] { - 240●
min_y[label] = y - 241
} - 242
if y > max_y[label] { - 243●
max_y[label] = y - 244
} - 245
} - 246
} - 247
} - 248
// 过滤并返回(中文字符通常接近正方形) - 249
let regions : Array[(Int32, Int32, Int32, Int32)] = [] - 250
for label in 1..<next_label { - 251●
let rw = max_x[label] - min_x[label] + 1 - 252
let rh = max_y[label] - min_y[label] + 1 - 253
// 中文字符过滤:接近正方形,尺寸在合理范围内 - 254◐
let ratio = if rh > 0 { rw.to_double() / rh.to_double() } else { 0.0 } - 255
if rw >= cfg.min_char_width && - 256
rw <= cfg.max_char_width && - 257
rh >= cfg.min_char_width && - 258
rh <= cfg.max_char_width && - 259
ratio > 0.5 && - 260
ratio < 2.0 && - 261
area[label] > 20 { - 262●
regions.push((min_x[label], min_y[label], rw, rh)) - 263
} - 264
} - 265
regions - 266
} - 267
- 268
///| - 269
/// 提取中文字符区域 - 270
fn extract_chinese_char_region( - 271
img : @types.Image, - 272
x : Int32, - 273
y : Int32, - 274
width : Int32, - 275
height : Int32, - 276
target_size : Int32, - 277
) -> @types.Image { - 278●
let w = img.width - 279
let h = img.height - 280●
let crop_w = if x + width > w { w - x } else { width } - 281●
let crop_h = if y + height > h { h - y } else { height } - 282
if crop_w <= 0 || crop_h <= 0 { - 283●
let empty : Array[Byte] = Array::make(target_size * target_size, b'\x00') - 284
return @types.Image::{ - 285
width: target_size, - 286
height: target_size, - 287
channels: 1, - 288●
data: Bytes::from_array(empty), - 289
} - 290
} - 291
// 缩放到目标尺寸(中文字符保持正方形) - 292●
let out : Array[Byte] = Array::make(target_size * target_size, b'\x00') - 293
let data = img.data - 294
for py in 0..<target_size { - 295●
for px in 0..<target_size { - 296●
let src_x = x + px * crop_w / target_size - 297
let src_y = y + py * crop_h / target_size - 298
if src_x < w && src_y < h { - 299●
out[py * target_size + px] = data[src_y * w + src_x] - 300
} - 301
} - 302
} - 303
@types.Image::{ - 304
width: target_size, - 305
height: target_size, - 306
channels: 1, - 307●
data: Bytes::from_array(out), - 308
} - 309
} - 310
- 311
///| - 312
/// 提取中文字符特征(16x16网格特征) - 313
fn extract_chinese_char_features( - 314
char_img : @types.Image, - 315
grid_size : Int32, - 316
) -> Array[Double] { - 317●
let w = char_img.width - 318
let h = char_img.height - 319
let data = char_img.data - 320
let cell_w = w / grid_size - 321
let cell_h = h / grid_size - 322
let features : Array[Double] = [] - 323
for r in 0..<grid_size { - 324●
for c in 0..<grid_size { - 325●
let mut count = 0 - 326
let mut total = 0 - 327
for py in 0..<cell_h { - 328●
for px in 0..<cell_w { - 329●
let sx = c * cell_w + px - 330
let sy = r * cell_h + py - 331
if sx < w && sy < h { - 332●
total += 1 - 333●
if data[sy * w + sx].to_int() > 128 { - 334●
count += 1 - 335
} - 336
} - 337
} - 338
} - 339
let density = if total > 0 { - 340●
count.to_double() / total.to_double() - 341
} else { - 342●
0.0 - 343
} - 344●
features.push(density) - 345
} - 346
} - 347
features - 348
} - 349
- 350
///| - 351
/// 中文模板匹配 - 352
fn match_chinese_template( - 353
features : Array[Double], - 354
templates : Array[(String, Array[Double])], - 355
distance_metric : String, - 356
) -> (String, Double) { - 357●
let mut best_label = "?" - 358
let mut best_dist = 1000000.0 - 359
for _tup1 in templates { - 360●
let (label, template) = _tup1 - 361●
let dist = match distance_metric { - 362●
"manhattan" => manhattan_distance_chi(features, template) - 363●
"cosine" => cosine_distance_chi(features, template) - 364●
_ => euclidean_distance_chi(features, template) - 365
} - 366
if dist < best_dist { - 367●
best_dist = dist - 368
best_label = label - 369
} - 370
} - 371●
let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 } - 372
(best_label, confidence) - 373
} - 374
- 375
///| - 376
/// 局部欧氏距离 - 377
fn euclidean_distance_chi(a : Array[Double], b : Array[Double]) -> Double { - 378◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 379
let mut sum_sq = 0.0 - 380
for i in 0..<n { - 381●
let diff = a[i] - b[i] - 382
sum_sq += diff * diff - 383
} - 384●
sum_sq.sqrt() - 385
} - 386
- 387
///| - 388
/// 局部曼哈顿距离 - 389
fn manhattan_distance_chi(a : Array[Double], b : Array[Double]) -> Double { - 390◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 391
let mut sum = 0.0 - 392
for i in 0..<n { - 393●
sum += (a[i] - b[i]).abs() - 394
} - 395
sum - 396
} - 397
- 398
///| - 399
/// 局部余弦距离 - 400
fn cosine_distance_chi(a : Array[Double], b : Array[Double]) -> Double { - 401◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 402
let mut dot = 0.0 - 403
let mut norm_a = 0.0 - 404
let mut norm_b = 0.0 - 405
for i in 0..<n { - 406●
dot += a[i] * b[i] - 407
norm_a += a[i] * a[i] - 408
norm_b += b[i] * b[i] - 409
} - 410●
let denom = norm_a.sqrt() * norm_b.sqrt() - 411
if denom > 0.0 { - 412●
1.0 - dot / denom - 413
} else { - 414○
1.0 - 415
} - 416
}