image.vision\ocr\ocr_accuracy_enhanced.mbt

93.9% · 291 / 310 points · 813 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

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