image.vision\ocr\handwriting_ocr.mbt
94.1% · 159 / 169 points · 553 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/handwriting_ocr - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 手写体识别 - 7
// 手写体专用模板、灵活的字符分割、手写体识别流水线 - 8
- 9
///| - 10
/// 手写体识别配置 - 11
#derive(Eq, @debug.Debug) - 12
pub(all) struct HandwritingOcrConfig { - 13
min_char_width : Int32 - 14
max_char_width : Int32 - 15
min_char_height : Int32 - 16
max_char_height : Int32 - 17
target_size : Int32 - 18
distance_metric : String - 19
flexibility : Double // 0.0-1.0,越高越灵活 - 20
use_slant_correction : Bool - 21
} - 22
- 23
///| - 24
pub extend HandwritingOcrConfig with Eq::{not_equal, equal} - 25
- 26
///| - 27
pub extend HandwritingOcrConfig with @debug.Debug::{to_repr} - 28
- 29
///| - 30
/// 创建默认手写体识别配置 - 31
pub fn handwriting_ocr_default_config() -> HandwritingOcrConfig { - 32●
HandwritingOcrConfig::{ - 33
min_char_width: 8, - 34
max_char_width: 80, - 35
min_char_height: 10, - 36
max_char_height: 100, - 37
target_size: 48, - 38
distance_metric: "euclidean", - 39
flexibility: 0.7, - 40
use_slant_correction: true, - 41
} - 42
} - 43
- 44
///| - 45
/// 生成手写体数字模板(更灵活的形状) - 46
pub fn generate_handwriting_templates( - 47
char_set~ : String = "digits", - 48
) -> Array[(String, Array[Double])] { - 49●
let templates : Array[(String, Array[Double])] = [] - 50
let chars = if char_set == "digits+letters" { - 51●
[ - 52
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", - 53
"F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", - 54
"U", "V", "W", "X", "Y", "Z", - 55
] - 56
} else { - 57●
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] - 58
} - 59
for char in chars { - 60
// 生成多个变体(手写体有多种写法) - 61●
for variant in 0..<3 { - 62●
let template = generate_handwriting_char_template(char, variant) - 63●
let label = char + "_v" + variant.to_string() - 64●
templates.push((label, template)) - 65
} - 66
} - 67
templates - 68
} - 69
- 70
///| - 71
/// 生成手写体字符模板(带变体) - 72
fn generate_handwriting_char_template( - 73
char : String, - 74
variant : Int32, - 75
) -> Array[Double] { - 76●
let size = 16 - 77●
let features : Array[Double] = Array::make(size * size, 0.0) - 78●
let seed = if char.length() > 0 { - 79●
char[0].to_int() + variant * 100 - 80
} else { - 81○
0 - 82
} - 83
// 手写体特征:更随机、更灵活的形状 - 84
for y in 0..<size { - 85●
for x in 0..<size { - 86
// 基础哈希 - 87●
let h1 = (seed * 31 + x * 17 + y * 13) % 100 - 88
// 变体哈希 - 89
let h2 = (seed * 7 + (x + variant * 3) * 11 + (y + variant * 2) * 19) % - 90
100 - 91
// 中心权重(手写体通常居中但有偏移) - 92
let center_x = 8 + (variant - 1) * 2 - 93
let center_y = 8 + variant % 2 * 2 - 94
let center_dist = ((x - center_x) * (x - center_x) + - 95●
(y - center_y) * (y - center_y)).to_double() - 96
let center_factor = 1.0 - center_dist / 128.0 - 97
// 手写体灵活性:更宽松的阈值 - 98●
let threshold = 35 + (center_factor * 30.0).to_int() + h2 / 5 - 99
if h1 < threshold { - 100●
features[y * size + x] = 1.0 - 101
} - 102
} - 103
} - 104
features - 105
} - 106
- 107
///| - 108
/// 倾斜校正(手写体专用) - 109
pub fn correct_slant( - 110
img : @types.Image, - 111
max_slant~ : Double = 15.0, - 112
) -> @types.Image raise @types.LoadError { - 113●
ignore(max_slant) - 114
// 输入验证 - 115
if img.width <= 0 || img.height <= 0 { - 116●
raise @types.LoadError::DecodeFailed( - 117
"correct_slant: 图像尺寸必须大于0", - 118
) - 119
} - 120
if img.channels != 1 { - 121●
raise @types.LoadError::DecodeFailed( - 122
"correct_slant: 仅支持单通道灰度图", - 123
) - 124
} - 125
let expected_size = img.width * img.height - 126●
if img.data.length() != expected_size { - 127●
raise @types.LoadError::DecodeFailed( - 128
"correct_slant: 数据大小不匹配,期望 " + - 129●
expected_size.to_string() + - 130
",实际 " + - 131●
img.data.length().to_string(), - 132
) - 133
} - 134
- 135
// 简化版:检测主要倾斜角度并校正 - 136●
let angle = estimate_slant_angle(img) - 137●
if angle.abs() > 1.0 { - 138●
rotate_document(img, -angle) - 139
} else { - 140●
img - 141
} - 142
} - 143
- 144
///| - 145
/// 估计倾斜角度(手写体专用) - 146
fn estimate_slant_angle(img : @types.Image) -> Double { - 147●
let w = img.width - 148
let h = img.height - 149
let data = img.data - 150
// 简化:基于垂直投影的倾斜估计 - 151
let mut best_angle = 0.0 - 152
let mut best_score = 0.0 - 153
let mut angle = -15.0 - 154
while angle <= 15.0 { - 155●
let angle_rad = angle * 3.141592653589793 / 180.0 - 156●
let cos_a = @math.cos(angle_rad) - 157●
let sin_a = @math.sin(angle_rad) - 158
// 计算旋转后的垂直投影方差 - 159●
let projection : Array[Int32] = Array::make(w, 0) - 160
for y in 0..<h { - 161●
for x in 0..<w { - 162●
if data[y * w + x].to_int() > 128 { - 163●
let new_x = ((x.to_double() - w.to_double() / 2.0) * cos_a - - 164●
(y.to_double() - h.to_double() / 2.0) * sin_a + - 165●
w.to_double() / 2.0).to_int() - 166
if new_x >= 0 && new_x < w { - 167●
projection[new_x] += 1 - 168
} - 169
} - 170
} - 171
} - 172
// 计算方差 - 173
let mut sum = 0 - 174
let mut sum_sq = 0 - 175
for i in 0..<w { - 176●
sum += projection[i] - 177
sum_sq += projection[i] * projection[i] - 178
} - 179●
let mean = sum.to_double() / w.to_double() - 180●
let variance = sum_sq.to_double() / w.to_double() - mean * mean - 181
if variance > best_score { - 182●
best_score = variance - 183
best_angle = angle - 184
} - 185
angle += 1.0 - 186
} - 187
best_angle - 188
} - 189
- 190
///| - 191
/// 手写体字符分割(更宽松的参数) - 192
fn segment_handwriting_chars( - 193
img : @types.Image, - 194
cfg : HandwritingOcrConfig, - 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
let min_ratio = 0.3 * (1.0 + cfg.flexibility) - 256
let max_ratio = 3.0 * (1.0 + cfg.flexibility) - 257
if rw >= cfg.min_char_width && - 258
rw <= cfg.max_char_width && - 259
rh >= cfg.min_char_height && - 260
rh <= cfg.max_char_height && - 261
ratio > min_ratio && - 262
ratio < max_ratio && - 263
area[label] > 15 { - 264●
regions.push((min_x[label], min_y[label], rw, rh)) - 265
} - 266
} - 267
regions - 268
} - 269
- 270
///| - 271
/// 手写体识别(完整流水线) - 272
/// @deprecated 已废弃,请使用 recognize_handwriting_enhanced 代替 - 273
#deprecated("Use recognize_handwriting_enhanced instead", skip_current_package=true) - 274
pub fn recognize_handwriting( - 275
img : @types.Image, - 276
config? : HandwritingOcrConfig, - 277
) -> OcrResult raise @types.LoadError { - 278
// 输入验证 - 279
if img.width <= 0 || img.height <= 0 { - 280
raise @types.LoadError::DecodeFailed( - 281
"recognize_handwriting: 图像尺寸必须大于0", - 282
) - 283
} - 284
if img.channels < 1 || img.channels > 4 { - 285
raise @types.LoadError::DecodeFailed( - 286
"recognize_handwriting: 通道数必须在1-4之间", - 287
) - 288
} - 289
let expected_size = img.width * img.height * img.channels - 290
if img.data.length() != expected_size { - 291
raise @types.LoadError::DecodeFailed( - 292
"recognize_handwriting: 数据大小不匹配,期望 " + - 293
expected_size.to_string() + - 294
",实际 " + - 295
img.data.length().to_string(), - 296
) - 297
} - 298
- 299
let cfg = match config { - 300
Some(c) => c - 301
None => handwriting_ocr_default_config() - 302
} - 303
// 配置验证 - 304
if cfg.min_char_width <= 0 { - 305
raise @types.LoadError::DecodeFailed( - 306
"recognize_handwriting: min_char_width必须大于0", - 307
) - 308
} - 309
if cfg.max_char_width < cfg.min_char_width { - 310
raise @types.LoadError::DecodeFailed( - 311
"recognize_handwriting: max_char_width不能小于min_char_width", - 312
) - 313
} - 314
if cfg.target_size <= 0 { - 315
raise @types.LoadError::DecodeFailed( - 316
"recognize_handwriting: target_size必须大于0", - 317
) - 318
} - 319
// 1. 预处理 - 320
let mut preprocessed = ocr_preprocess(img) - 321
// 2. 倾斜校正(手写体专用) - 322
if cfg.use_slant_correction { - 323
preprocessed = correct_slant(preprocessed) - 324
} - 325
// 3. 字符分割(手写体更宽松) - 326
let char_regions = segment_handwriting_chars(preprocessed, cfg) - 327
// 4. 生成手写体模板 - 328
let templates = generate_handwriting_templates(char_set="digits") - 329
// 5. 对每个字符进行识别 - 330
let char_results : Array[OcrCharResult] = [] - 331
let mut text = "" - 332
let mut total_confidence = 0.0 - 333
for _tup0 in char_regions { - 334
let (x, y, w, h) = _tup0 - 335
// 提取字符图像 - 336
let char_img = extract_handwriting_char_region( - 337
preprocessed, - 338
x, - 339
y, - 340
w, - 341
h, - 342
cfg.target_size, - 343
) - 344
// 提取特征 - 345
let features = extract_handwriting_char_features(char_img, 16) - 346
// 模板匹配(多变体投票) - 347
let result = match_handwriting_template( - 348
features, - 349
templates, - 350
cfg.distance_metric, - 351
) - 352
text += result.0 - 353
total_confidence += result.1 - 354
char_results.push(OcrCharResult::{ - 355
char: result.0, - 356
confidence: result.1, - 357
x, - 358
y, - 359
width: w, - 360
height: h, - 361
}) - 362
} - 363
let avg_confidence = if char_results.length() > 0 { - 364
total_confidence / char_results.length().to_double() - 365
} else { - 366
0.0 - 367
} - 368
OcrResult::{ text, confidence: avg_confidence, characters: char_results, } - 369
} - 370
- 371
///| - 372
/// 提取手写体字符区域 - 373
fn extract_handwriting_char_region( - 374
img : @types.Image, - 375
x : Int32, - 376
y : Int32, - 377
width : Int32, - 378
height : Int32, - 379
target_size : Int32, - 380
) -> @types.Image { - 381●
let w = img.width - 382
let h = img.height - 383●
let crop_w = if x + width > w { w - x } else { width } - 384●
let crop_h = if y + height > h { h - y } else { height } - 385
if crop_w <= 0 || crop_h <= 0 { - 386●
let empty : Array[Byte] = Array::make(target_size * target_size, b'\x00') - 387
return @types.Image::{ - 388
width: target_size, - 389
height: target_size, - 390
channels: 1, - 391●
data: Bytes::from_array(empty), - 392
} - 393
} - 394●
let out : Array[Byte] = Array::make(target_size * target_size, b'\x00') - 395
let data = img.data - 396
for py in 0..<target_size { - 397●
for px in 0..<target_size { - 398●
let src_x = x + px * crop_w / target_size - 399
let src_y = y + py * crop_h / target_size - 400
if src_x < w && src_y < h { - 401●
out[py * target_size + px] = data[src_y * w + src_x] - 402
} - 403
} - 404
} - 405
@types.Image::{ - 406
width: target_size, - 407
height: target_size, - 408
channels: 1, - 409●
data: Bytes::from_array(out), - 410
} - 411
} - 412
- 413
///| - 414
/// 提取手写体字符特征 - 415
fn extract_handwriting_char_features( - 416
char_img : @types.Image, - 417
grid_size : Int32, - 418
) -> Array[Double] { - 419●
let w = char_img.width - 420
let h = char_img.height - 421
let data = char_img.data - 422
let cell_w = w / grid_size - 423
let cell_h = h / grid_size - 424
let features : Array[Double] = [] - 425
for r in 0..<grid_size { - 426●
for c in 0..<grid_size { - 427●
let mut count = 0 - 428
let mut total = 0 - 429
for py in 0..<cell_h { - 430●
for px in 0..<cell_w { - 431●
let sx = c * cell_w + px - 432
let sy = r * cell_h + py - 433
if sx < w && sy < h { - 434●
total += 1 - 435●
if data[sy * w + sx].to_int() > 128 { - 436●
count += 1 - 437
} - 438
} - 439
} - 440
} - 441
let density = if total > 0 { - 442●
count.to_double() / total.to_double() - 443
} else { - 444●
0.0 - 445
} - 446●
features.push(density) - 447
} - 448
} - 449
features - 450
} - 451
- 452
///| - 453
/// 手写体模板匹配(多变体投票) - 454
fn match_handwriting_template( - 455
features : Array[Double], - 456
templates : Array[(String, Array[Double])], - 457
distance_metric : String, - 458
) -> (String, Double) { - 459
// 收集所有变体的预测 - 460●
let label_votes : Array[(String, Double)] = [] - 461
for _tup1 in templates { - 462●
let (label_full, template) = _tup1 - 463●
let dist = match distance_metric { - 464●
"manhattan" => manhattan_hw(features, template) - 465●
"cosine" => cosine_hw(features, template) - 466●
_ => euclidean_hw(features, template) - 467
} - 468
// 取第一个码点作为基础标签(数字 0-9),按字符还原而不是码点数字 - 469●
let base_label = if label_full.length() > 0 { - 470●
hw_char_str(label_full[0]) - 471
} else { - 472○
label_full - 473
} - 474●
let confidence = if dist > 0.0 { 1.0 / (1.0 + dist) } else { 1.0 } - 475
// 投票 - 476
let mut found = false - 477●
for i in 0..<label_votes.length() { - 478●
if label_votes[i].0 == base_label { - 479●
label_votes[i] = (base_label, label_votes[i].1 + confidence) - 480
found = true - 481
} - 482
} - 483
if !found { - 484●
label_votes.push((base_label, confidence)) - 485
} - 486
} - 487
// 找得票最多的标签 - 488
let mut best_label = "?" - 489
let mut best_votes = 0.0 - 490
for _tup2 in label_votes { - 491●
let (label, votes) = _tup2 - 492
if votes > best_votes { - 493●
best_votes = votes - 494
best_label = label - 495
} - 496
} - 497●
let total_votes = if templates.length() > 0 { - 498●
templates.length().to_double() / 3.0 - 499
} else { - 500●
1.0 - 501
} - 502
let confidence = best_votes / total_votes - 503
(best_label, confidence) - 504
} - 505
- 506
///| - 507
/// 把字符串索引(码点 UInt16)还原成单字符字符串 - 508
fn hw_char_str(raw : UInt16) -> String { - 509●
raw.to_int().to_char().map(c => c.to_string()).unwrap_or("") - 510
} - 511
- 512
///| - 513
/// 局部欧氏距离 - 514
fn euclidean_hw(a : Array[Double], b : Array[Double]) -> Double { - 515◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 516
let mut sum_sq = 0.0 - 517
for i in 0..<n { - 518●
let diff = a[i] - b[i] - 519
sum_sq += diff * diff - 520
} - 521●
sum_sq.sqrt() - 522
} - 523
- 524
///| - 525
/// 局部曼哈顿距离 - 526
fn manhattan_hw(a : Array[Double], b : Array[Double]) -> Double { - 527◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 528
let mut sum = 0.0 - 529
for i in 0..<n { - 530●
sum += (a[i] - b[i]).abs() - 531
} - 532
sum - 533
} - 534
- 535
///| - 536
/// 局部余弦距离 - 537
fn cosine_hw(a : Array[Double], b : Array[Double]) -> Double { - 538◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 539
let mut dot = 0.0 - 540
let mut norm_a = 0.0 - 541
let mut norm_b = 0.0 - 542
for i in 0..<n { - 543●
dot += a[i] * b[i] - 544
norm_a += a[i] * a[i] - 545
norm_b += b[i] * b[i] - 546
} - 547●
let denom = norm_a.sqrt() * norm_b.sqrt() - 548
if denom > 0.0 { - 549●
1.0 - dot / denom - 550
} else { - 551○
1.0 - 552
} - 553
}