image.vision\ocr\ocr_accuracy_enhanced.mbt
93.9% · 291 / 310 points · 813 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/ocr_accuracy_enhanced - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// OCR 准确率提升增强版(v10.1.0) - 7
// Zernike矩、Gabor特征、加权KNN、置信度校准、多尺度融合 - 8
- 9
///| - 10
/// 准确率提升配置 - 11
#derive(Eq, @debug.Debug) - 12
pub(all) struct OcrAccuracyEnhancedConfig { - 13
use_zernike_moments : Bool - 14
use_gabor_features : Bool - 15
use_directional_features : Bool - 16
use_weighted_knn : Bool - 17
use_confidence_calibration : Bool - 18
use_multi_scale : Bool - 19
knn_k : Int32 - 20
scales : Array[Int32] // 多尺度识别的尺寸列表 - 21
} - 22
- 23
///| - 24
pub extend OcrAccuracyEnhancedConfig with Eq::{not_equal, equal} - 25
- 26
///| - 27
pub extend OcrAccuracyEnhancedConfig with @debug.Debug::{to_repr} - 28
- 29
///| - 30
/// 创建默认准确率提升配置 - 31
pub fn ocr_accuracy_enhanced_default_config() -> OcrAccuracyEnhancedConfig { - 32●
OcrAccuracyEnhancedConfig::{ - 33
use_zernike_moments: true, - 34
use_gabor_features: true, - 35
use_directional_features: true, - 36
use_weighted_knn: true, - 37
use_confidence_calibration: true, - 38
use_multi_scale: false, - 39
knn_k: 5, - 40
scales: [24, 32, 48], - 41
} - 42
} - 43
- 44
///| - 45
/// 提取 Zernike 矩特征(旋转不变性,前6阶) - 46
pub fn extract_zernike_moments( - 47
char_img : @types.Image, - 48
max_order~ : Int32 = 4, - 49
) -> Array[Double] raise @types.LoadError { - 50
// 输入验证 - 51●
if char_img.width <= 0 || char_img.height <= 0 { - 52●
raise @types.LoadError::DecodeFailed( - 53
"extract_zernike_moments: 图像尺寸必须大于0", - 54
) - 55
} - 56
if char_img.channels != 1 { - 57●
raise @types.LoadError::DecodeFailed( - 58
"extract_zernike_moments: 仅支持单通道灰度图", - 59
) - 60
} - 61
let expected_size = char_img.width * char_img.height - 62●
if char_img.data.length() != expected_size { - 63●
raise @types.LoadError::DecodeFailed( - 64
"extract_zernike_moments: 数据大小不匹配,期望 " + - 65●
expected_size.to_string() + - 66
",实际 " + - 67●
char_img.data.length().to_string(), - 68
) - 69
} - 70
if max_order <= 0 { - 71●
raise @types.LoadError::DecodeFailed( - 72
"extract_zernike_moments: 最大阶数必须大于0", - 73
) - 74
} - 75
let w = char_img.width - 76
let h = char_img.height - 77
let data = char_img.data - 78
let features : Array[Double] = [] - 79
// 计算质心 - 80
let mut sum_x = 0.0 - 81
let mut sum_y = 0.0 - 82
let mut total = 0.0 - 83
for y in 0..<h { - 84●
for x in 0..<w { - 85●
if data[y * w + x].to_int() > 128 { - 86●
sum_x += x.to_double() - 87●
sum_y += y.to_double() - 88
total += 1.0 - 89
} - 90
} - 91
} - 92●
let cx = if total > 0.0 { sum_x / total } else { w.to_double() / 2.0 } - 93●
let cy = if total > 0.0 { sum_y / total } else { h.to_double() / 2.0 } - 94
// 计算半径(归一化) - 95●
let max_r = w.to_double().max(h.to_double()) / 2.0 - 96
// 计算 Zernike 矩(简化版:前几阶的径向矩) - 97
for n in 0..<(max_order + 1) { - 98●
for m in 0..<(n + 1) { - 99●
if (n - m) % 2 == 0 { - 100●
let mut z_real = 0.0 - 101
let mut z_imag = 0.0 - 102
for y in 0..<h { - 103●
for x in 0..<w { - 104●
if data[y * w + x].to_int() > 128 { - 105
// 归一化坐标 - 106●
let nx = (x.to_double() - cx) / max_r - 107●
let ny = (y.to_double() - cy) / max_r - 108●
let r = (nx * nx + ny * ny).sqrt() - 109●
let theta = @math.atan2(ny, nx) - 110
if r <= 1.0 { - 111
// 简化的径向多项式 - 112●
let mut radial = 0.0 - 113
let k_max = (n - m) / 2 - 114
for k in 0..<(k_max + 1) { - 115●
let sign = if k % 2 == 0 { 1.0 } else { -1.0 } - 116●
let numerator = factorial(n - k) - 117●
let denominator = factorial(k) * - 118●
factorial((n + m) / 2 - k) * - 119●
factorial((n - m) / 2 - k) - 120
if denominator > 0.0 { - 121●
radial += sign * - 122
numerator / - 123
denominator * - 124●
@math.pow(r, (n - 2 * k).to_double()) - 125
} - 126
} - 127●
z_real += radial * @math.cos(m.to_double() * theta) - 128●
z_imag += radial * @math.sin(m.to_double() * theta) - 129
} - 130
} - 131
} - 132
} - 133
// 归一化 - 134●
let magnitude = (z_real * z_real + z_imag * z_imag).sqrt() - 135●
features.push(magnitude / (w * h).to_double()) - 136
} - 137
} - 138
} - 139
features - 140
} - 141
- 142
///| - 143
/// 计算阶乘 - 144
fn factorial(n : Int32) -> Double { - 145●
let mut result = 1.0 - 146
for i in 1..<(n + 1) { - 147●
result *= i.to_double() - 148
} - 149
result - 150
} - 151
- 152
///| - 153
/// 提取 Gabor 特征(多方向多频率) - 154
pub fn extract_gabor_ocr_features( - 155
char_img : @types.Image, - 156
num_orientations~ : Int32 = 4, - 157
num_frequencies~ : Int32 = 2, - 158
) -> Array[Double] { - 159●
let w = char_img.width - 160
let h = char_img.height - 161
let data = char_img.data - 162
let features : Array[Double] = [] - 163
// 对每个方向和频率计算 Gabor 响应能量 - 164
for o in 0..<num_orientations { - 165●
let theta = o.to_double() * 3.141592653589793 / num_orientations.to_double() - 166
for f in 0..<num_frequencies { - 167●
let frequency = (f + 1).to_double() * 0.1 - 168
let _ = 1.0 / (frequency * 2.0) - 169
// 计算 Gabor 滤波响应(简化版:统计方向能量) - 170
let mut energy = 0.0 - 171
let mut count = 0 - 172
for y in 2..<(h - 2) { - 173●
for x in 2..<(w - 2) { - 174●
if data[y * w + x].to_int() > 128 { - 175
// 计算该方向的梯度能量 - 176●
let dx = @math.cos(theta) - 177●
let dy = @math.sin(theta) - 178●
let x1 = (x.to_double() + dx).to_int() - 179●
let y1 = (y.to_double() + dy).to_int() - 180●
let x2 = (x.to_double() - dx).to_int() - 181●
let y2 = (y.to_double() - dy).to_int() - 182
if x1 >= 0 && - 183
x1 < w && - 184
y1 >= 0 && - 185
y1 < h && - 186
x2 >= 0 && - 187
x2 < w && - 188
y2 >= 0 && - 189
y2 < h { - 190●
let g1 = data[y1 * w + x1].to_int().to_double() - 191●
let g2 = data[y2 * w + x2].to_int().to_double() - 192●
let grad = (g1 - g2).abs() - 193
energy += grad * grad * frequency - 194
count += 1 - 195
} - 196
} - 197
} - 198
} - 199●
let avg_energy = if count > 0 { energy / count.to_double() } else { 0.0 } - 200●
features.push(avg_energy / 255.0) - 201
} - 202
} - 203
features - 204
} - 205
- 206
///| - 207
/// 提取方向特征(8个方向的笔画密度) - 208
pub fn extract_directional_features(char_img : @types.Image) -> Array[Double] { - 209●
let w = char_img.width - 210
let h = char_img.height - 211
let data = char_img.data - 212
let features : Array[Double] = [] - 213
// 8个方向:0°(水平)、45°、90°(垂直)、135°、180°、225°、270°、315° - 214
let directions : Array[(Double, Double)] = [ - 215
(1.0, 0.0), // 0° 水平 - 216
(0.707, 0.707), // 45° - 217
(0.0, 1.0), // 90° 垂直 - 218
(-0.707, 0.707), // 135° - 219
(-1.0, 0.0), // 180° - 220
(-0.707, -0.707), // 225° - 221
(0.0, -1.0), // 270° - 222
(0.707, -0.707), // 315° - 223
] - 224
for _tup0 in directions { - 225●
let (dx, dy) = _tup0 - 226
let mut energy = 0.0 - 227
let mut count = 0 - 228
for y in 2..<(h - 2) { - 229●
for x in 2..<(w - 2) { - 230●
if data[y * w + x].to_int() > 128 { - 231●
let x1 = (x.to_double() + dx * 2.0).to_int() - 232●
let y1 = (y.to_double() + dy * 2.0).to_int() - 233●
let x2 = (x.to_double() - dx * 2.0).to_int() - 234●
let y2 = (y.to_double() - dy * 2.0).to_int() - 235
if x1 >= 0 && - 236
x1 < w && - 237
y1 >= 0 && - 238
y1 < h && - 239
x2 >= 0 && - 240
x2 < w && - 241
y2 >= 0 && - 242
y2 < h { - 243●
let g1 = data[y1 * w + x1].to_int().to_double() - 244●
let g2 = data[y2 * w + x2].to_int().to_double() - 245●
energy += (g1 - g2).abs() - 246
count += 1 - 247
} - 248
} - 249
} - 250
} - 251●
let avg = if count > 0 { energy / count.to_double() } else { 0.0 } - 252●
features.push(avg / 255.0) - 253
} - 254
features - 255
} - 256
- 257
///| - 258
/// 加权 KNN 分类(距离加权投票) - 259
pub fn weighted_knn_classify( - 260
features : Array[Double], - 261
training_data : Array[(String, Array[Double])], - 262
k~ : Int32 = 5, - 263
distance_metric~ : String = "euclidean", - 264
) -> (String, Double, Array[(String, Double)]) { - 265
// 计算所有训练样本的距离 - 266●
let distances : Array[(String, Double)] = [] - 267
for _tup1 in training_data { - 268●
let (label, sample) = _tup1 - 269●
let dist = calculate_distance(features, sample, distance_metric) - 270●
distances.push((label, dist)) - 271
} - 272
// 按距离排序(冒泡排序) - 273●
for _ in 0..<distances.length() { - 274●
for j in 0..<(distances.length() - 1) { - 275●
if distances[j].1 > distances[j + 1].1 { - 276●
let temp = distances[j] - 277
distances[j] = distances[j + 1] - 278
distances[j + 1] = temp - 279
} - 280
} - 281
} - 282
// 取前 k 个最近邻 - 283●
let k_actual = if k < distances.length() { k } else { distances.length() } - 284
// 距离加权投票 - 285
let votes : Array[(String, Double)] = [] - 286
for i in 0..<k_actual { - 287●
let (label, dist) = distances[i] - 288●
let weight = if dist > 0.001 { 1.0 / dist } else { 1000.0 } - 289
let mut found = false - 290●
for j in 0..<votes.length() { - 291●
if votes[j].0 == label { - 292●
votes[j] = (label, votes[j].1 + weight) - 293
found = true - 294
} - 295
} - 296
if !found { - 297●
votes.push((label, weight)) - 298
} - 299
} - 300
// 找得票最多的标签 - 301
let mut best_label = "?" - 302
let mut best_votes = 0.0 - 303
let mut total_votes = 0.0 - 304
for _tup2 in votes { - 305●
let (label, v) = _tup2 - 306
total_votes += v - 307
if v > best_votes { - 308●
best_votes = v - 309
best_label = label - 310
} - 311
} - 312
let confidence = if total_votes > 0.0 { - 313●
best_votes / total_votes - 314
} else { - 315●
0.0 - 316
} - 317
(best_label, confidence, votes) - 318
} - 319
- 320
///| - 321
/// 计算距离 - 322
fn calculate_distance( - 323
a : Array[Double], - 324
b : Array[Double], - 325
metric : String, - 326
) -> Double { - 327◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 328●
match metric { - 329●
"manhattan" => { - 330
let mut sum = 0.0 - 331
for i in 0..<n { - 332●
sum += (a[i] - b[i]).abs() - 333
} - 334
sum - 335
} - 336●
"cosine" => { - 337
let mut dot = 0.0 - 338
let mut norm_a = 0.0 - 339
let mut norm_b = 0.0 - 340
for i in 0..<n { - 341●
dot += a[i] * b[i] - 342
norm_a += a[i] * a[i] - 343
norm_b += b[i] * b[i] - 344
} - 345●
let denom = norm_a.sqrt() * norm_b.sqrt() - 346
if denom > 0.0 { - 347●
1.0 - dot / denom - 348
} else { - 349○
1.0 - 350
} - 351
} - 352●
_ => { - 353
let mut sum_sq = 0.0 - 354
for i in 0..<n { - 355●
let diff = a[i] - b[i] - 356
sum_sq += diff * diff - 357
} - 358●
sum_sq.sqrt() - 359
} - 360
} - 361
} - 362
- 363
///| - 364
/// 置信度校准(基于距离分布的 Platt 缩放简化版) - 365
pub fn calibrate_confidence_enhanced( - 366
raw_confidence : Double, - 367
distance_distribution : Array[Double], - 368
) -> Double { - 369●
if distance_distribution.length() == 0 { - 370●
return raw_confidence - 371
} - 372
// 计算距离分布的统计量 - 373
let mut mean = 0.0 - 374
let mut min_dist = 1000000.0 - 375
let mut max_dist = 0.0 - 376
for d in distance_distribution { - 377●
mean += d - 378
if d < min_dist { - 379●
min_dist = d - 380
} - 381
if d > max_dist { - 382●
max_dist = d - 383
} - 384
} - 385●
mean = mean / distance_distribution.length().to_double() - 386
// 基于距离分布的校准 - 387●
let range = if max_dist > min_dist { max_dist - min_dist } else { 1.0 } - 388
let normalized_mean = (mean - min_dist) / range - 389
// 如果平均距离较小,说明匹配质量高,提升置信度 - 390
let calibration_factor = 1.0 + (1.0 - normalized_mean) * 0.3 - 391
let calibrated = raw_confidence * calibration_factor - 392
if calibrated > 1.0 { - 393●
1.0 - 394●
} else if calibrated < 0.0 { - 395○
0.0 - 396
} else { - 397●
calibrated - 398
} - 399
} - 400
- 401
///| - 402
/// 多尺度识别融合(不同尺寸下的识别结果加权融合) - 403
pub fn multi_scale_recognize( - 404
char_img : @types.Image, - 405
templates : Array[(String, Array[Double])], - 406
scales : Array[Int32], - 407
distance_metric~ : String = "euclidean", - 408
) -> (String, Double) { - 409●
let _ = char_img.width - 410
let _ = char_img.height - 411
let _ = char_img.data - 412
// 对每个尺度进行识别 - 413
let all_results : Array[(String, Double)] = [] - 414
for scale in scales { - 415
// 缩放到目标尺寸 - 416●
let scaled = resize_char_image(char_img, scale, scale) - 417
// 提取特征 - 418●
let features = extract_grid_features(scaled, 16) - 419
// 模板匹配 - 420
let mut best_label = "?" - 421
let mut best_dist = 1000000.0 - 422
for _tup3 in templates { - 423●
let (label, template) = _tup3 - 424●
let dist = calculate_distance(features, template, distance_metric) - 425
if dist < best_dist { - 426●
best_dist = dist - 427
best_label = label - 428
} - 429
} - 430◐
let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 } - 431●
all_results.push((best_label, confidence)) - 432
} - 433
// 加权融合(所有尺度等权) - 434
let votes : Array[(String, Double)] = [] - 435
for _tup4 in all_results { - 436●
let (label, conf) = _tup4 - 437
let mut found = false - 438●
for i in 0..<votes.length() { - 439●
if votes[i].0 == label { - 440●
votes[i] = (label, votes[i].1 + conf) - 441
found = true - 442
} - 443
} - 444
if !found { - 445●
votes.push((label, conf)) - 446
} - 447
} - 448
// 找得票最多的 - 449
let mut best_label = "?" - 450
let mut best_votes = 0.0 - 451
let mut total = 0.0 - 452
for _tup5 in votes { - 453●
let (label, v) = _tup5 - 454
total += v - 455
if v > best_votes { - 456●
best_votes = v - 457
best_label = label - 458
} - 459
} - 460◐
let confidence = if total > 0.0 { best_votes / total } else { 0.0 } - 461
(best_label, confidence) - 462
} - 463
- 464
///| - 465
/// 缩放字符图像 - 466
fn resize_char_image( - 467
img : @types.Image, - 468
new_w : Int32, - 469
new_h : Int32, - 470
) -> @types.Image { - 471●
let w = img.width - 472
let h = img.height - 473
let data = img.data - 474●
let out : Array[Byte] = Array::make(new_w * new_h, b'\x00') - 475
for y in 0..<new_h { - 476●
for x in 0..<new_w { - 477●
let src_x = x * w / new_w - 478
let src_y = y * h / new_h - 479
if src_x < w && src_y < h { - 480●
out[y * new_w + x] = data[src_y * w + src_x] - 481
} - 482
} - 483
} - 484
@types.Image::{ - 485
width: new_w, - 486
height: new_h, - 487
channels: 1, - 488●
data: Bytes::from_array(out), - 489
} - 490
} - 491
- 492
///| - 493
/// 提取网格特征 - 494
fn extract_grid_features( - 495
char_img : @types.Image, - 496
grid_size : Int32, - 497
) -> Array[Double] { - 498●
let w = char_img.width - 499
let h = char_img.height - 500
let data = char_img.data - 501
let cell_w = w / grid_size - 502
let cell_h = h / grid_size - 503
let features : Array[Double] = [] - 504
for r in 0..<grid_size { - 505●
for c in 0..<grid_size { - 506●
let mut count = 0 - 507
let mut total = 0 - 508
for py in 0..<cell_h { - 509●
for px in 0..<cell_w { - 510●
let sx = c * cell_w + px - 511
let sy = r * cell_h + py - 512
if sx < w && sy < h { - 513●
total += 1 - 514●
if data[sy * w + sx].to_int() > 128 { - 515●
count += 1 - 516
} - 517
} - 518
} - 519
} - 520
let density = if total > 0 { - 521●
count.to_double() / total.to_double() - 522
} else { - 523●
0.0 - 524
} - 525●
features.push(density) - 526
} - 527
} - 528
features - 529
} - 530
- 531
///| - 532
/// 组合多种特征(网格+HOG+LBP+Zernike+Gabor+方向特征) - 533
pub fn extract_combined_enhanced_features( - 534
char_img : @types.Image, - 535
config : OcrAccuracyEnhancedConfig, - 536
) -> Array[Double] raise @types.LoadError { - 537
// 输入验证 - 538●
if char_img.width <= 0 || char_img.height <= 0 { - 539●
raise @types.LoadError::DecodeFailed( - 540
"extract_combined_enhanced_features: 图像尺寸必须大于0", - 541
) - 542
} - 543
if char_img.channels != 1 { - 544●
raise @types.LoadError::DecodeFailed( - 545
"extract_combined_enhanced_features: 仅支持单通道灰度图", - 546
) - 547
} - 548
let expected_size = char_img.width * char_img.height - 549●
if char_img.data.length() != expected_size { - 550●
raise @types.LoadError::DecodeFailed( - 551
"extract_combined_enhanced_features: 数据大小不匹配,期望 " + - 552●
expected_size.to_string() + - 553
",实际 " + - 554●
char_img.data.length().to_string(), - 555
) - 556
} - 557
let features : Array[Double] = [] - 558
// 网格特征(基础) - 559●
let grid = extract_grid_features(char_img, 16) - 560
for f in grid { - 561●
features.push(f) - 562
} - 563
// Zernike 矩(旋转不变) - 564
if config.use_zernike_moments { - 565●
let zernike = extract_zernike_moments(char_img, max_order=4) - 566
for f in zernike { - 567●
features.push(f) - 568
} - 569
} - 570
// Gabor 特征(多方向多频率) - 571
if config.use_gabor_features { - 572●
let gabor = extract_gabor_ocr_features( - 573
char_img, - 574
num_orientations=4, - 575
num_frequencies=2, - 576
) - 577
for f in gabor { - 578●
features.push(f) - 579
} - 580
} - 581
// 方向特征(8方向) - 582
if config.use_directional_features { - 583●
let directional = extract_directional_features(char_img) - 584
for f in directional { - 585●
features.push(f) - 586
} - 587
} - 588
features - 589
} - 590
- 591
///| - 592
/// 增强 OCR 识别(完整准确率提升流水线) - 593
pub fn recognize_ocr_enhanced( - 594
img : @types.Image, - 595
templates : Array[(String, Array[Double])], - 596
config? : OcrAccuracyEnhancedConfig, - 597
) -> OcrResult raise @types.LoadError { - 598
// 输入验证 - 599●
if img.width <= 0 || img.height <= 0 { - 600●
raise @types.LoadError::DecodeFailed( - 601
"recognize_ocr_enhanced: 图像尺寸必须大于0", - 602
) - 603
} - 604
if img.channels < 1 || img.channels > 4 { - 605●
raise @types.LoadError::DecodeFailed( - 606
"recognize_ocr_enhanced: 通道数必须在1-4之间", - 607
) - 608
} - 609
let expected_size = img.width * img.height * img.channels - 610●
if img.data.length() != expected_size { - 611●
raise @types.LoadError::DecodeFailed( - 612
"recognize_ocr_enhanced: 数据大小不匹配,期望 " + - 613●
expected_size.to_string() + - 614
",实际 " + - 615●
img.data.length().to_string(), - 616
) - 617
} - 618●
if templates.length() == 0 { - 619●
raise @types.LoadError::DecodeFailed( - 620
"recognize_ocr_enhanced: 模板列表不能为空", - 621
) - 622
} - 623●
let cfg = match config { - 624●
Some(c) => c - 625●
None => ocr_accuracy_enhanced_default_config() - 626
} - 627
// 1. 预处理 - 628●
let preprocessed = ocr_preprocess(img) - 629
// 2. 字符分割 - 630●
let char_regions = segment_chars_for_enhanced(preprocessed) - 631
// 3. 对每个字符进行识别 - 632
let char_results : Array[OcrCharResult] = [] - 633
let mut text = "" - 634
let mut total_confidence = 0.0 - 635
for _tup6 in char_regions { - 636●
let (x, y, w, h) = _tup6 - 637
// 提取字符图像 - 638●
let char_img = extract_char_region_for_enhanced( - 639
preprocessed, x, y, w, h, 48, - 640
) - 641
// 多尺度识别(如果启用) - 642
let result = if cfg.use_multi_scale { - 643○
multi_scale_recognize( - 644
char_img, - 645
templates, - 646
cfg.scales, - 647
distance_metric="euclidean", - 648
) - 649
} else { - 650
// 单尺度识别 - 651●
let features = extract_combined_enhanced_features(char_img, cfg) - 652
// 加权 KNN(如果启用) - 653
if cfg.use_weighted_knn { - 654●
let (label, conf, _) = weighted_knn_classify( - 655
features, - 656
templates, - 657
k=cfg.knn_k, - 658
distance_metric="euclidean", - 659
) - 660
// 置信度校准(如果启用) - 661
let final_conf = if cfg.use_confidence_calibration { - 662●
let dists : Array[Double] = [] - 663
for _tup7 in templates { - 664●
let (_, sample) = _tup7 - 665●
dists.push(calculate_distance(features, sample, "euclidean")) - 666
} - 667●
calibrate_confidence_enhanced(conf, dists) - 668
} else { - 669○
conf - 670
} - 671
(label, final_conf) - 672
} else { - 673
// 简单模板匹配 - 674○
let mut best_label = "?" - 675
let mut best_dist = 1000000.0 - 676
for _tup8 in templates { - 677○
let (label, template) = _tup8 - 678○
let dist = calculate_distance(features, template, "euclidean") - 679
if dist < best_dist { - 680○
best_dist = dist - 681
best_label = label - 682
} - 683
} - 684○
let conf = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 } - 685
(best_label, conf) - 686
} - 687
} - 688
text += result.0 - 689
total_confidence += result.1 - 690●
char_results.push(OcrCharResult::{ - 691
char: result.0, - 692
confidence: result.1, - 693
x, - 694
y, - 695
width: w, - 696
height: h, - 697
}) - 698
} - 699●
let avg_confidence = if char_results.length() > 0 { - 700●
total_confidence / char_results.length().to_double() - 701
} else { - 702●
0.0 - 703
} - 704
OcrResult::{ text, confidence: avg_confidence, characters: char_results, } - 705
} - 706
- 707
///| - 708
/// 字符分割(增强版用) - 709
fn segment_chars_for_enhanced( - 710
img : @types.Image, - 711
) -> Array[(Int32, Int32, Int32, Int32)] { - 712●
let w = img.width - 713
let h = img.height - 714
let data = img.data - 715●
let labels : Array[Int32] = Array::make(w * h, 0) - 716
let mut next_label = 1 - 717
for y in 0..<h { - 718●
for x in 0..<w { - 719●
if data[y * w + x].to_int() > 128 { - 720●
let mut label = 0 - 721
if x > 0 && labels[y * w + x - 1] > 0 { - 722●
label = labels[y * w + x - 1] - 723
} - 724
if y > 0 && labels[(y - 1) * w + x] > 0 { - 725●
if label == 0 { - 726●
label = labels[(y - 1) * w + x] - 727
} - 728
} - 729
if label == 0 { - 730●
label = next_label - 731
next_label += 1 - 732
} - 733
labels[y * w + x] = label - 734
} - 735
} - 736
} - 737●
let min_x : Array[Int32] = Array::make(next_label, w) - 738●
let max_x : Array[Int32] = Array::make(next_label, 0) - 739●
let min_y : Array[Int32] = Array::make(next_label, h) - 740●
let max_y : Array[Int32] = Array::make(next_label, 0) - 741●
let area : Array[Int32] = Array::make(next_label, 0) - 742
for y in 0..<h { - 743●
for x in 0..<w { - 744●
let label = labels[y * w + x] - 745
if label > 0 { - 746●
area[label] += 1 - 747
if x < min_x[label] { - 748●
min_x[label] = x - 749
} - 750
if x > max_x[label] { - 751●
max_x[label] = x - 752
} - 753
if y < min_y[label] { - 754●
min_y[label] = y - 755
} - 756
if y > max_y[label] { - 757●
max_y[label] = y - 758
} - 759
} - 760
} - 761
} - 762
let regions : Array[(Int32, Int32, Int32, Int32)] = [] - 763
for label in 1..<next_label { - 764●
let rw = max_x[label] - min_x[label] + 1 - 765
let rh = max_y[label] - min_y[label] + 1 - 766
if rw >= 5 && rw <= 100 && rh >= 8 && rh <= 100 && area[label] > 10 { - 767●
regions.push((min_x[label], min_y[label], rw, rh)) - 768
} - 769
} - 770
regions - 771
} - 772
- 773
///| - 774
/// 提取字符区域(增强版用) - 775
fn extract_char_region_for_enhanced( - 776
img : @types.Image, - 777
x : Int32, - 778
y : Int32, - 779
width : Int32, - 780
height : Int32, - 781
target_size : Int32, - 782
) -> @types.Image { - 783●
let w = img.width - 784
let h = img.height - 785◐
let crop_w = if x + width > w { w - x } else { width } - 786◐
let crop_h = if y + height > h { h - y } else { height } - 787
if crop_w <= 0 || crop_h <= 0 { - 788○
let empty : Array[Byte] = Array::make(target_size * target_size, b'\x00') - 789
return @types.Image::{ - 790
width: target_size, - 791
height: target_size, - 792
channels: 1, - 793○
data: Bytes::from_array(empty), - 794
} - 795
} - 796●
let out : Array[Byte] = Array::make(target_size * target_size, b'\x00') - 797
let data = img.data - 798
for py in 0..<target_size { - 799●
for px in 0..<target_size { - 800●
let src_x = x + px * crop_w / target_size - 801
let src_y = y + py * crop_h / target_size - 802
if src_x < w && src_y < h { - 803●
out[py * target_size + px] = data[src_y * w + src_x] - 804
} - 805
} - 806
} - 807
@types.Image::{ - 808
width: target_size, - 809
height: target_size, - 810
channels: 1, - 811●
data: Bytes::from_array(out), - 812
} - 813
}