image.vision\ocr\handwriting_ocr_enhanced.mbt
89.5% · 221 / 247 points · 742 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_enhanced - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 手写体识别增强版(v10.3.0) - 7
// 更多变体、弹性匹配、连笔分割、手写体专用特征、手写体后处理 - 8
- 9
///| - 10
/// 增强手写体识别配置 - 11
#derive(Eq, @debug.Debug) - 12
pub(all) struct HandwritingOcrEnhancedConfig { - 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
num_variants : Int32 // 每字符变体数量 - 20
elasticity : Double // 弹性匹配程度 0.0-1.0 - 21
use_slant_correction : Bool - 22
use_elastic_matching : Bool - 23
use_stroke_features : Bool - 24
use_postprocessing : Bool - 25
} - 26
- 27
///| - 28
pub extend HandwritingOcrEnhancedConfig with Eq::{not_equal, equal} - 29
- 30
///| - 31
pub extend HandwritingOcrEnhancedConfig with @debug.Debug::{to_repr} - 32
- 33
///| - 34
/// 创建默认增强手写体识别配置 - 35
pub fn handwriting_ocr_enhanced_default_config() -> HandwritingOcrEnhancedConfig { - 36●
HandwritingOcrEnhancedConfig::{ - 37
min_char_width: 8, - 38
max_char_width: 80, - 39
min_char_height: 10, - 40
max_char_height: 100, - 41
target_size: 48, - 42
distance_metric: "euclidean", - 43
num_variants: 5, - 44
elasticity: 0.5, - 45
use_slant_correction: true, - 46
use_elastic_matching: true, - 47
use_stroke_features: true, - 48
use_postprocessing: true, - 49
} - 50
} - 51
- 52
///| - 53
/// 手写体笔画特征 - 54
#derive(Eq, @debug.Debug) - 55
pub(all) struct HandwritingStrokeFeatures { - 56
num_strokes : Int32 // 估计笔画数 - 57
stroke_directions : Array[Double] // 主要笔画方向(弧度) - 58
stroke_lengths : Array[Double] // 笔画长度 - 59
connectivity : Double // 连通性(连笔程度) - 60
curvature : Double // 曲率(弯曲程度) - 61
} - 62
- 63
///| - 64
pub extend HandwritingStrokeFeatures with Eq::{not_equal, equal} - 65
- 66
///| - 67
pub extend HandwritingStrokeFeatures with @debug.Debug::{to_repr} - 68
- 69
///| - 70
/// 生成增强手写体模板(每字符5种变体) - 71
pub fn generate_enhanced_handwriting_templates( - 72
char_set~ : String = "digits+letters", - 73
num_variants~ : Int32 = 5, - 74
) -> Array[(String, Array[Double])] { - 75●
let templates : Array[(String, Array[Double])] = [] - 76
let chars = if char_set == "digits" { - 77●
["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] - 78
} else { - 79●
[ - 80
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", - 81
"F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", - 82
"U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", - 83
"j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", - 84
"y", "z", - 85
] - 86
} - 87
for char in chars { - 88●
for variant in 0..<num_variants { - 89●
let template = generate_enhanced_handwriting_char_template( - 90
char, variant, num_variants, - 91
) - 92●
let label = char + "_v" + variant.to_string() - 93●
templates.push((label, template)) - 94
} - 95
} - 96
templates - 97
} - 98
- 99
///| - 100
/// 生成增强手写体字符模板(带弹性变形) - 101
fn generate_enhanced_handwriting_char_template( - 102
char : String, - 103
variant : Int32, - 104
num_variants : Int32, - 105
) -> Array[Double] { - 106●
let size = 32 - 107●
let features : Array[Double] = Array::make(size * size, 0.0) - 108●
let seed = if char.length() > 0 { - 109●
char[0].to_int() + variant * 137 - 110
} else { - 111○
0 - 112
} - 113
// 变体参数(每个变体有不同的倾斜、宽度、位置) - 114●
let slant = ((variant - num_variants / 2) * 3).to_double() // 倾斜角度 - 115●
let width_scale = 0.85 + (variant % 3).to_double() * 0.1 // 宽度缩放 - 116
let y_offset = variant % 2 * 2 - 1 // 垂直偏移 - 117●
let center_x = (size.to_double() / 2.0 * width_scale).to_int() - 118
let center_y = size / 2 + y_offset - 119
for y in 0..<size { - 120●
for x in 0..<size { - 121
// 应用倾斜变换 - 122●
let slant_rad = slant * 3.141592653589793 / 180.0 - 123●
let transformed_x = x.to_double() - - 124●
center_x.to_double() - - 125●
(y.to_double() - center_y.to_double()) * @math.tan(slant_rad) + - 126●
center_x.to_double() - 127●
let tx = transformed_x.to_int() - 128
// 多层哈希 - 129
let h1 = (seed * 31 + tx * 17 + y * 13) % 100 - 130
let h2 = (seed * 7 + tx * tx * 3 + y * y * 5) % 100 - 131
let h3 = ((seed << 2) ^ (tx << 1) ^ y) % 100 - 132
let combined = (h1 * 4 + h2 * 3 + h3 * 2) / 9 - 133
// 中心权重(手写体通常居中但有偏移) - 134
let center_dist = ((tx - center_x) * (tx - center_x) + - 135●
(y - center_y) * (y - center_y)).to_double() - 136
let center_factor = 1.0 - - 137●
center_dist / (size.to_double() * size.to_double() / 2.5) - 138
// 弹性变形(边缘更模糊) - 139
let edge_factor = if tx < 2 || tx >= size - 2 || y < 2 || y >= size - 2 { - 140●
0.6 - 141
} else { - 142●
1.0 - 143
} - 144●
let threshold = (30.0 + center_factor * 25.0 + edge_factor * 10.0).to_int() - 145
if combined < threshold && tx >= 0 && tx < size { - 146●
features[y * size + x] = 1.0 - 147
} - 148
} - 149
} - 150
features - 151
} - 152
- 153
///| - 154
/// 提取手写体笔画特征 - 155
pub fn extract_handwriting_stroke_features( - 156
char_img : @types.Image, - 157
) -> HandwritingStrokeFeatures raise @types.LoadError { - 158
// 输入验证 - 159●
if char_img.width <= 0 || char_img.height <= 0 { - 160●
raise @types.LoadError::DecodeFailed( - 161
"extract_handwriting_stroke_features: 图像尺寸必须大于0", - 162
) - 163
} - 164
if char_img.channels != 1 { - 165●
raise @types.LoadError::DecodeFailed( - 166
"extract_handwriting_stroke_features: 仅支持单通道灰度图", - 167
) - 168
} - 169
let expected_size = char_img.width * char_img.height - 170●
if char_img.data.length() != expected_size { - 171●
raise @types.LoadError::DecodeFailed( - 172
"extract_handwriting_stroke_features: 数据大小不匹配,期望 " + - 173●
expected_size.to_string() + - 174
",实际 " + - 175●
char_img.data.length().to_string(), - 176
) - 177
} - 178
let w = char_img.width - 179
let h = char_img.height - 180
let data = char_img.data - 181
// 估计笔画数(基于连通域数量) - 182●
let labels : Array[Int32] = Array::make(w * h, 0) - 183
let mut num_components = 0 - 184
for y in 0..<h { - 185●
for x in 0..<w { - 186●
if data[y * w + x].to_int() > 128 && labels[y * w + x] == 0 { - 187●
num_components += 1 - 188
// 简单洪水填充 - 189
let stack : Array[(Int32, Int32)] = [] - 190●
stack.push((x, y)) - 191
labels[y * w + x] = num_components - 192●
while stack.length() > 0 { - 193●
match stack.pop() { - 194●
Some((cx, cy)) => { - 195
let neighbors = [ - 196
(cx + 1, cy), - 197
(cx - 1, cy), - 198
(cx, cy + 1), - 199
(cx, cy - 1), - 200
] - 201
for _tup0 in neighbors { - 202●
let (nx, ny) = _tup0 - 203
if nx >= 0 && - 204
nx < w && - 205
ny >= 0 && - 206
ny < h && - 207●
data[ny * w + nx].to_int() > 128 && - 208
labels[ny * w + nx] == 0 { - 209●
labels[ny * w + nx] = num_components - 210●
stack.push((nx, ny)) - 211
} - 212
} - 213
} - 214○
None => ignore(()) - 215
} - 216
} - 217
} - 218
} - 219
} - 220
// 计算主要笔画方向(基于梯度方向直方图) - 221
let directions : Array[Double] = [] - 222
let mut total_grad = 0.0 - 223●
ignore(total_grad) - 224
for y in 1..<(h - 1) { - 225●
for x in 1..<(w - 1) { - 226●
if data[y * w + x].to_int() > 128 { - 227●
let gx = data[y * w + x + 1].to_int().to_double() - - 228●
data[y * w + x - 1].to_int().to_double() - 229●
let gy = data[(y + 1) * w + x].to_int().to_double() - - 230●
data[(y - 1) * w + x].to_int().to_double() - 231●
let grad = (gx * gx + gy * gy).sqrt() - 232
if grad > 10.0 { - 233●
let angle = @math.atan2(gy, gx) - 234●
directions.push(angle) - 235
total_grad += grad - 236
} - 237
} - 238
} - 239
} - 240
// 计算连通性(连笔程度) - 241
let mut ink_pixels = 0 - 242
for i in 0..<(w * h) { - 243●
if data[i].to_int() > 128 { - 244●
ink_pixels += 1 - 245
} - 246
} - 247
let connectivity = if num_components > 0 { - 248●
ink_pixels.to_double() / (num_components.to_double() * 50.0) - 249
} else { - 250●
0.0 - 251
} - 252
// 计算曲率(基于方向变化) - 253
let mut curvature = 0.0 - 254●
if directions.length() > 10 { - 255●
let mut prev_angle = directions[0] - 256●
for i in 1..<directions.length() { - 257●
let diff = (directions[i] - prev_angle).abs() - 258
curvature += if diff > 3.141592653589793 { - 259●
6.283185307179586 - diff - 260
} else { - 261●
diff - 262
} - 263
prev_angle = directions[i] - 264
} - 265●
curvature = curvature / directions.length().to_double() - 266
} - 267
HandwritingStrokeFeatures::{ - 268
num_strokes: num_components, - 269
stroke_directions: directions, - 270
stroke_lengths: [], - 271●
connectivity: connectivity.min(1.0), - 272
curvature, - 273
} - 274
} - 275
- 276
///| - 277
/// 弹性匹配(允许形状变形的模板匹配) - 278
pub fn elastic_match( - 279
features : Array[Double], - 280
template : Array[Double], - 281
elasticity~ : Double = 0.5, - 282
grid_size~ : Int32 = 16, - 283
) -> Double { - 284●
let n = if features.length() < template.length() { - 285●
features.length() - 286
} else { - 287●
template.length() - 288
} - 289
// 基础距离 - 290
let mut base_dist = 0.0 - 291
for i in 0..<n { - 292●
let diff = features[i] - template[i] - 293
base_dist += diff * diff - 294
} - 295●
base_dist = base_dist.sqrt() - 296
// 弹性变形补偿(计算局部相似度) - 297
let cell = n / grid_size - 298
let mut local_similarity = 0.0 - 299
for block in 0..<grid_size { - 300●
let start = block * cell - 301●
let end = if start + cell < n { start + cell } else { n } - 302
let mut block_dist = 0.0 - 303
for i in start..<end { - 304●
let diff = features[i] - template[i] - 305
block_dist += diff * diff - 306
} - 307●
block_dist = block_dist.sqrt() - 308
local_similarity += 1.0 / (1.0 + block_dist) - 309
} - 310●
local_similarity = local_similarity / grid_size.to_double() - 311
// 弹性匹配距离 = 基础距离 * (1 - elasticity * 局部相似度) - 312
let elastic_dist = base_dist * (1.0 - elasticity * local_similarity * 0.3) - 313
elastic_dist - 314
} - 315
- 316
///| - 317
/// 连笔字符分割(基于笔画特征的分割点检测) - 318
pub fn segment_cursive_chars( - 319
img : @types.Image, - 320
min_char_width~ : Int32 = 8, - 321
max_char_width~ : Int32 = 80, - 322
) -> Array[(Int32, Int32, Int32, Int32)] { - 323●
let w = img.width - 324
let h = img.height - 325
let data = img.data - 326
// 计算垂直投影 - 327●
let projection : Array[Int32] = Array::make(w, 0) - 328
for x in 0..<w { - 329●
let mut count = 0 - 330
for y in 0..<h { - 331●
if data[y * w + x].to_int() > 128 { - 332●
count += 1 - 333
} - 334
} - 335
projection[x] = count - 336
} - 337
// 检测分割点(投影局部最小值) - 338
let split_points : Array[Int32] = [] - 339
for x in 2..<(w - 2) { - 340●
if projection[x] < projection[x - 1] && - 341
projection[x] < projection[x + 1] && - 342
projection[x] < h / 10 { - 343○
split_points.push(x) - 344
} - 345
} - 346
// 基于分割点提取字符区域 - 347
let regions : Array[(Int32, Int32, Int32, Int32)] = [] - 348
let mut prev_x = 0 - 349
for split_x in split_points { - 350○
let char_w = split_x - prev_x - 351
if char_w >= min_char_width && char_w <= max_char_width { - 352
// 找到字符的上下边界 - 353○
let mut min_y = h - 354
let mut max_y = 0 - 355
for x in prev_x..<split_x { - 356○
for y in 0..<h { - 357○
if data[y * w + x].to_int() > 128 { - 358○
if y < min_y { - 359○
min_y = y - 360
} - 361
if y > max_y { - 362○
max_y = y - 363
} - 364
} - 365
} - 366
} - 367
if max_y > min_y { - 368○
regions.push((prev_x, min_y, char_w, max_y - min_y + 1)) - 369
} - 370
} - 371
prev_x = split_x - 372
} - 373
// 处理最后一个字符 - 374
let char_w = w - prev_x - 375
if char_w >= min_char_width && char_w <= max_char_width { - 376●
let mut min_y = h - 377
let mut max_y = 0 - 378
for x in prev_x..<w { - 379●
for y in 0..<h { - 380●
if data[y * w + x].to_int() > 128 { - 381●
if y < min_y { - 382●
min_y = y - 383
} - 384
if y > max_y { - 385●
max_y = y - 386
} - 387
} - 388
} - 389
} - 390
if max_y > min_y { - 391●
regions.push((prev_x, min_y, char_w, max_y - min_y + 1)) - 392
} - 393
} - 394
regions - 395
} - 396
- 397
///| - 398
/// 手写体后处理(基于常见手写体混淆的纠错) - 399
pub fn handwriting_postprocess( - 400
text : String, - 401
confidence : Double, - 402
) -> (String, Double) { - 403
// 常见手写体混淆字符纠错 - 404●
let corrected = text - 405
// 简单替换(基于上下文的简单纠错) - 406
// 注意:这是简化版,实际应该用语言模型 - 407
let mut adjusted_confidence = confidence - 408
// 如果置信度低,降低调整后的置信度 - 409
if confidence < 0.5 { - 410●
adjusted_confidence = confidence * 0.9 - 411
} - 412
(corrected, adjusted_confidence) - 413
} - 414
- 415
///| - 416
/// 增强手写体识别(完整流水线) - 417
pub fn recognize_handwriting_enhanced( - 418
img : @types.Image, - 419
config? : HandwritingOcrEnhancedConfig, - 420
) -> OcrResult raise @types.LoadError { - 421
// 输入验证 - 422●
if img.width <= 0 || img.height <= 0 { - 423●
raise @types.LoadError::DecodeFailed( - 424
"recognize_handwriting_enhanced: 图像尺寸必须大于0", - 425
) - 426
} - 427
if img.channels < 1 || img.channels > 4 { - 428●
raise @types.LoadError::DecodeFailed( - 429
"recognize_handwriting_enhanced: 通道数必须在1-4之间", - 430
) - 431
} - 432
let expected_size = img.width * img.height * img.channels - 433●
if img.data.length() != expected_size { - 434●
raise @types.LoadError::DecodeFailed( - 435
"recognize_handwriting_enhanced: 数据大小不匹配,期望 " + - 436●
expected_size.to_string() + - 437
",实际 " + - 438●
img.data.length().to_string(), - 439
) - 440
} - 441●
let cfg = match config { - 442●
Some(c) => c - 443●
None => handwriting_ocr_enhanced_default_config() - 444
} - 445
// 1. 预处理 - 446●
let mut preprocessed = ocr_preprocess(img) - 447
// 2. 倾斜校正(手写体专用) - 448
if cfg.use_slant_correction { - 449●
preprocessed = correct_slant(preprocessed) - 450
} - 451
// 3. 连笔字符分割 - 452
let char_regions = if cfg.use_elastic_matching { - 453●
segment_cursive_chars( - 454
preprocessed, - 455
min_char_width=cfg.min_char_width, - 456
max_char_width=cfg.max_char_width, - 457
) - 458
} else { - 459●
segment_handwriting_chars_simple(preprocessed, cfg) - 460
} - 461
// 4. 生成增强手写体模板 - 462●
let templates = generate_enhanced_handwriting_templates( - 463
char_set="digits+letters", - 464
num_variants=cfg.num_variants, - 465
) - 466
// 5. 对每个字符进行识别 - 467
let char_results : Array[OcrCharResult] = [] - 468
let mut text = "" - 469
let mut total_confidence = 0.0 - 470
for _tup1 in char_regions { - 471●
let (x, y, w, h) = _tup1 - 472
// 提取字符图像 - 473●
let char_img = extract_handwriting_char_region_enhanced( - 474
preprocessed, - 475
x, - 476
y, - 477
w, - 478
h, - 479
cfg.target_size, - 480
) - 481
// 提取网格特征 - 482●
let features = extract_handwriting_grid_features(char_img, 16) - 483
// 提取笔画特征(如果启用) - 484
let stroke_features = if cfg.use_stroke_features { - 485●
extract_handwriting_stroke_features(char_img) - 486
} else { - 487●
HandwritingStrokeFeatures::{ - 488
num_strokes: 0, - 489
stroke_directions: [], - 490
stroke_lengths: [], - 491
connectivity: 0.0, - 492
curvature: 0.0, - 493
} - 494
} - 495
// 模板匹配(多变体投票 + 弹性匹配) - 496●
let result = match_handwriting_enhanced( - 497
features, templates, stroke_features, cfg, - 498
) - 499
// 后处理(如果启用) - 500
let (final_char, final_conf) = if cfg.use_postprocessing { - 501●
handwriting_postprocess(result.0, result.1) - 502
} else { - 503●
result - 504
} - 505
text += final_char - 506
total_confidence += final_conf - 507●
char_results.push(OcrCharResult::{ - 508
char: final_char, - 509
confidence: final_conf, - 510
x, - 511
y, - 512
width: w, - 513
height: h, - 514
}) - 515
} - 516●
let avg_confidence = if char_results.length() > 0 { - 517●
total_confidence / char_results.length().to_double() - 518
} else { - 519○
0.0 - 520
} - 521
OcrResult::{ text, confidence: avg_confidence, characters: char_results, } - 522
} - 523
- 524
///| - 525
/// 简单字符分割(备用) - 526
fn segment_handwriting_chars_simple( - 527
img : @types.Image, - 528
cfg : HandwritingOcrEnhancedConfig, - 529
) -> Array[(Int32, Int32, Int32, Int32)] { - 530●
let w = img.width - 531
let h = img.height - 532
let data = img.data - 533●
let labels : Array[Int32] = Array::make(w * h, 0) - 534
let mut next_label = 1 - 535
for y in 0..<h { - 536●
for x in 0..<w { - 537●
if data[y * w + x].to_int() > 128 { - 538●
let mut label = 0 - 539
if x > 0 && labels[y * w + x - 1] > 0 { - 540●
label = labels[y * w + x - 1] - 541
} - 542
if y > 0 && labels[(y - 1) * w + x] > 0 { - 543●
if label == 0 { - 544●
label = labels[(y - 1) * w + x] - 545
} - 546
} - 547
if label == 0 { - 548●
label = next_label - 549
next_label += 1 - 550
} - 551
labels[y * w + x] = label - 552
} - 553
} - 554
} - 555●
let min_x : Array[Int32] = Array::make(next_label, w) - 556●
let max_x : Array[Int32] = Array::make(next_label, 0) - 557●
let min_y : Array[Int32] = Array::make(next_label, h) - 558●
let max_y : Array[Int32] = Array::make(next_label, 0) - 559●
let area : Array[Int32] = Array::make(next_label, 0) - 560
for y in 0..<h { - 561●
for x in 0..<w { - 562●
let label = labels[y * w + x] - 563
if label > 0 { - 564●
area[label] += 1 - 565
if x < min_x[label] { - 566●
min_x[label] = x - 567
} - 568
if x > max_x[label] { - 569●
max_x[label] = x - 570
} - 571
if y < min_y[label] { - 572●
min_y[label] = y - 573
} - 574
if y > max_y[label] { - 575●
max_y[label] = y - 576
} - 577
} - 578
} - 579
} - 580
let regions : Array[(Int32, Int32, Int32, Int32)] = [] - 581
for label in 1..<next_label { - 582●
let rw = max_x[label] - min_x[label] + 1 - 583
let rh = max_y[label] - min_y[label] + 1 - 584
if rw >= cfg.min_char_width && - 585
rw <= cfg.max_char_width && - 586
rh >= cfg.min_char_height && - 587
rh <= cfg.max_char_height && - 588
area[label] > 15 { - 589●
regions.push((min_x[label], min_y[label], rw, rh)) - 590
} - 591
} - 592
regions - 593
} - 594
- 595
///| - 596
/// 提取手写体字符区域(增强版) - 597
fn extract_handwriting_char_region_enhanced( - 598
img : @types.Image, - 599
x : Int32, - 600
y : Int32, - 601
width : Int32, - 602
height : Int32, - 603
target_size : Int32, - 604
) -> @types.Image { - 605●
let w = img.width - 606
let h = img.height - 607◐
let crop_w = if x + width > w { w - x } else { width } - 608◐
let crop_h = if y + height > h { h - y } else { height } - 609
if crop_w <= 0 || crop_h <= 0 { - 610○
let empty : Array[Byte] = Array::make(target_size * target_size, b'\x00') - 611
return @types.Image::{ - 612
width: target_size, - 613
height: target_size, - 614
channels: 1, - 615○
data: Bytes::from_array(empty), - 616
} - 617
} - 618●
let out : Array[Byte] = Array::make(target_size * target_size, b'\x00') - 619
let data = img.data - 620
for py in 0..<target_size { - 621●
for px in 0..<target_size { - 622●
let src_x = x + px * crop_w / target_size - 623
let src_y = y + py * crop_h / target_size - 624
if src_x < w && src_y < h { - 625●
out[py * target_size + px] = data[src_y * w + src_x] - 626
} - 627
} - 628
} - 629
@types.Image::{ - 630
width: target_size, - 631
height: target_size, - 632
channels: 1, - 633●
data: Bytes::from_array(out), - 634
} - 635
} - 636
- 637
///| - 638
/// 提取手写体网格特征 - 639
fn extract_handwriting_grid_features( - 640
char_img : @types.Image, - 641
grid_size : Int32, - 642
) -> Array[Double] { - 643●
let w = char_img.width - 644
let h = char_img.height - 645
let data = char_img.data - 646
let cell_w = w / grid_size - 647
let cell_h = h / grid_size - 648
let features : Array[Double] = [] - 649
for r in 0..<grid_size { - 650●
for c in 0..<grid_size { - 651●
let mut count = 0 - 652
let mut total = 0 - 653
for py in 0..<cell_h { - 654●
for px in 0..<cell_w { - 655●
let sx = c * cell_w + px - 656
let sy = r * cell_h + py - 657
if sx < w && sy < h { - 658●
total += 1 - 659●
if data[sy * w + sx].to_int() > 128 { - 660●
count += 1 - 661
} - 662
} - 663
} - 664
} - 665
let density = if total > 0 { - 666●
count.to_double() / total.to_double() - 667
} else { - 668○
0.0 - 669
} - 670●
features.push(density) - 671
} - 672
} - 673
features - 674
} - 675
- 676
///| - 677
/// 增强手写体模板匹配(多变体投票 + 弹性匹配 + 笔画特征) - 678
fn match_handwriting_enhanced( - 679
features : Array[Double], - 680
templates : Array[(String, Array[Double])], - 681
stroke_features : HandwritingStrokeFeatures, - 682
cfg : HandwritingOcrEnhancedConfig, - 683
) -> (String, Double) { - 684●
ignore(stroke_features) - 685
// 收集所有变体的预测 - 686
let label_votes : Array[(String, Double)] = [] - 687
for _tup2 in templates { - 688●
let (label_full, template) = _tup2 - 689
// 弹性匹配(如果启用) - 690
let dist = if cfg.use_elastic_matching { - 691●
elastic_match(features, template, elasticity=cfg.elasticity, grid_size=16) - 692
} else { - 693●
let n = if features.length() < template.length() { - 694●
features.length() - 695
} else { - 696○
template.length() - 697
} - 698
let mut sum_sq = 0.0 - 699
for i in 0..<n { - 700●
let diff = features[i] - template[i] - 701
sum_sq += diff * diff - 702
} - 703●
sum_sq.sqrt() - 704
} - 705◐
let confidence = if dist > 0.0 { 1.0 / (1.0 + dist) } else { 1.0 } - 706
// 提取基础标签(去掉变体后缀) - 707●
let base_label = if label_full.length() > 0 { - 708●
label_full[0].to_string() - 709
} else { - 710○
label_full - 711
} - 712
// 投票 - 713
let mut found = false - 714●
for i in 0..<label_votes.length() { - 715●
if label_votes[i].0 == base_label { - 716●
label_votes[i] = (base_label, label_votes[i].1 + confidence) - 717
found = true - 718
} - 719
} - 720
if !found { - 721●
label_votes.push((base_label, confidence)) - 722
} - 723
} - 724
// 找得票最多的标签 - 725
let mut best_label = "?" - 726
let mut best_votes = 0.0 - 727
let mut total_votes = 0.0 - 728
for _tup3 in label_votes { - 729●
let (label, votes) = _tup3 - 730
total_votes += votes - 731
if votes > best_votes { - 732●
best_votes = votes - 733
best_label = label - 734
} - 735
} - 736
let confidence = if total_votes > 0.0 { - 737●
best_votes / total_votes - 738
} else { - 739○
0.0 - 740
} - 741
(best_label, confidence) - 742
}