image.vision\ocr\multilingual_ocr_enhanced.mbt

83.3% · 245 / 294 points · 806 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/multilingual_ocr_enhanced
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 多语言混合识别增强版(v10.4.0)
  7. 7// 更准确语言检测、智能字符分割、混排优化、标点处理、语言模型后处理
  8. 8
  9. 9///|
  10. 10/// 增强多语言识别配置
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct MultilingualOcrEnhancedConfig {
  13. 13 enable_chinese : Bool
  14. 14 enable_english : Bool
  15. 15 enable_digits : Bool
  16. 16 enable_punctuation : Bool
  17. 17 enable_japanese : Bool
  18. 18 enable_korean : Bool
  19. 19 target_size : Int32
  20. 20 distance_metric : String
  21. 21 auto_language_detection : Bool
  22. 22 smart_spacing : Bool // 中英文之间自动加空格
  23. 23 punctuation_normalization : Bool // 标点符号规范化
  24. 24 use_language_model : Bool // 使用语言模型后处理
  25. 25}
  26. 26
  27. 27///|
  28. 28pub extend MultilingualOcrEnhancedConfig with Eq::{not_equal, equal}
  29. 29
  30. 30///|
  31. 31pub extend MultilingualOcrEnhancedConfig with @debug.Debug::{to_repr}
  32. 32
  33. 33///|
  34. 34/// 创建默认增强多语言识别配置
  35. 35pub fn multilingual_ocr_enhanced_default_config() -> MultilingualOcrEnhancedConfig {
  36. 36● MultilingualOcrEnhancedConfig::{
  37. 37 enable_chinese: true,
  38. 38 enable_english: true,
  39. 39 enable_digits: true,
  40. 40 enable_punctuation: true,
  41. 41 enable_japanese: false,
  42. 42 enable_korean: false,
  43. 43 target_size: 48,
  44. 44 distance_metric: "euclidean",
  45. 45 auto_language_detection: true,
  46. 46 smart_spacing: true,
  47. 47 punctuation_normalization: true,
  48. 48 use_language_model: true,
  49. 49 }
  50. 50}
  51. 51
  52. 52///|
  53. 53/// 语言检测结果
  54. 54#derive(Eq, @debug.Debug)
  55. 55pub(all) struct LanguageDetectionResult {
  56. 56 language : String // "chinese" / "english" / "digit" / "punctuation" / "japanese" / "korean" / "mixed" / "unknown"
  57. 57 confidence : Double
  58. 58 probabilities : Array[(String, Double)]
  59. 59}
  60. 60
  61. 61///|
  62. 62pub extend LanguageDetectionResult with Eq::{not_equal, equal}
  63. 63
  64. 64///|
  65. 65pub extend LanguageDetectionResult with @debug.Debug::{to_repr}
  66. 66
  67. 67///|
  68. 68/// 增强语言检测(基于多特征的分类器)
  69. 69pub fn detect_language_enhanced(
  70. 70 char_img : @types.Image,
  71. 71) -> LanguageDetectionResult raise @types.LoadError {
  72. 72 // 输入验证
  73. 73● if char_img.width <= 0 || char_img.height <= 0 {
  74. 74● raise @types.LoadError::DecodeFailed(
  75. 75 "detect_language_enhanced: 图像尺寸必须大于0",
  76. 76 )
  77. 77 }
  78. 78 if char_img.channels != 1 {
  79. 79● raise @types.LoadError::DecodeFailed(
  80. 80 "detect_language_enhanced: 仅支持单通道灰度图",
  81. 81 )
  82. 82 }
  83. 83 let expected_size = char_img.width * char_img.height
  84. 84● if char_img.data.length() != expected_size {
  85. 85● raise @types.LoadError::DecodeFailed(
  86. 86 "detect_language_enhanced: 数据大小不匹配,期望 " +
  87. 87● expected_size.to_string() +
  88. 88 ",实际 " +
  89. 89● char_img.data.length().to_string(),
  90. 90 )
  91. 91 }
  92. 92 let w = char_img.width
  93. 93 let h = char_img.height
  94. 94 let data = char_img.data
  95. 95 // 特征1:宽高比
  96. 96◐ let ratio = if h > 0 { w.to_double() / h.to_double() } else { 1.0 }
  97. 97 // 特征2:密度
  98. 98 let mut ink_pixels = 0
  99. 99 for i in 0..<(w * h) {
  100. 100● if data[i].to_int() > 128 {
  101. 101● ink_pixels += 1
  102. 102 }
  103. 103 }
  104. 104 let density = if w * h > 0 {
  105. 105● ink_pixels.to_double() / (w * h).to_double()
  106. 106 } else {
  107. 107○ 0.0
  108. 108 }
  109. 109 // 特征3:水平投影方差(中文字符通常更均匀)
  110. 110● let h_proj : Array[Int32] = Array::make(h, 0)
  111. 111 for y in 0..<h {
  112. 112● let mut count = 0
  113. 113 for x in 0..<w {
  114. 114● if data[y * w + x].to_int() > 128 {
  115. 115● count += 1
  116. 116 }
  117. 117 }
  118. 118 h_proj[y] = count
  119. 119 }
  120. 120 let mut h_mean = 0.0
  121. 121 for y in 0..<h {
  122. 122● h_mean += h_proj[y].to_double()
  123. 123 }
  124. 124● h_mean = h_mean / h.to_double()
  125. 125 let mut h_var = 0.0
  126. 126 for y in 0..<h {
  127. 127● let diff = h_proj[y].to_double() - h_mean
  128. 128 h_var += diff * diff
  129. 129 }
  130. 130● h_var = h_var / h.to_double()
  131. 131 // 特征4:垂直投影方差
  132. 132● let v_proj : Array[Int32] = Array::make(w, 0)
  133. 133 for x in 0..<w {
  134. 134● let mut count = 0
  135. 135 for y in 0..<h {
  136. 136● if data[y * w + x].to_int() > 128 {
  137. 137● count += 1
  138. 138 }
  139. 139 }
  140. 140 v_proj[x] = count
  141. 141 }
  142. 142 let mut v_mean = 0.0
  143. 143 for x in 0..<w {
  144. 144● v_mean += v_proj[x].to_double()
  145. 145 }
  146. 146● v_mean = v_mean / w.to_double()
  147. 147 let mut v_var = 0.0
  148. 148 for x in 0..<w {
  149. 149● let diff = v_proj[x].to_double() - v_mean
  150. 150 v_var += diff * diff
  151. 151 }
  152. 152● v_var = v_var / w.to_double()
  153. 153 // 基于特征的语言分类(简单规则分类器)
  154. 154 let probabilities : Array[(String, Double)] = []
  155. 155 // 中文:接近正方形、密度适中、投影均匀
  156. 156 let chinese_score = if ratio > 0.7 &&
  157. 157 ratio < 1.4 &&
  158. 158 density > 0.15 &&
  159. 159 density < 0.5 {
  160. 160● 0.8
  161. 161● } else if ratio > 0.6 && ratio < 1.5 {
  162. 162● 0.5
  163. 163 } else {
  164. 164● 0.2
  165. 165 }
  166. 166● probabilities.push(("chinese", chinese_score))
  167. 167 // 英文:较窄、密度较低、垂直投影方差大
  168. 168 let english_score = if ratio > 0.3 &&
  169. 169 ratio < 0.75 &&
  170. 170 density > 0.1 &&
  171. 171 density < 0.4 {
  172. 172● 0.75
  173. 173● } else if ratio > 0.25 && ratio < 0.85 {
  174. 174● 0.45
  175. 175 } else {
  176. 176● 0.15
  177. 177 }
  178. 178● probabilities.push(("english", english_score))
  179. 179 // 数字:较窄、密度适中
  180. 180 let digit_score = if ratio > 0.35 &&
  181. 181 ratio < 0.65 &&
  182. 182 density > 0.15 &&
  183. 183 density < 0.45 {
  184. 184● 0.7
  185. 185● } else if ratio > 0.3 && ratio < 0.75 {
  186. 186● 0.4
  187. 187 } else {
  188. 188● 0.15
  189. 189 }
  190. 190● probabilities.push(("digit", digit_score))
  191. 191 // 标点:很窄或很宽、密度低
  192. 192 let punctuation_score = if ratio < 0.35 || ratio > 1.4 || density < 0.12 {
  193. 193● 0.8
  194. 194● } else if ratio < 0.4 || ratio > 1.3 {
  195. 195● 0.5
  196. 196 } else {
  197. 197● 0.1
  198. 198 }
  199. 199● probabilities.push(("punctuation", punctuation_score))
  200. 200 // 找最高分
  201. 201 let mut best_language = "unknown"
  202. 202 let mut best_score = 0.0
  203. 203 let mut total_score = 0.0
  204. 204 for _tup0 in probabilities {
  205. 205● let (lang, score) = _tup0
  206. 206 total_score += score
  207. 207 if score > best_score {
  208. 208● best_score = score
  209. 209 best_language = lang
  210. 210 }
  211. 211 }
  212. 212 let confidence = if total_score > 0.0 {
  213. 213● best_score / total_score
  214. 214 } else {
  215. 215○ 0.0
  216. 216 }
  217. 217 LanguageDetectionResult::{
  218. 218 language: best_language,
  219. 219 confidence,
  220. 220 probabilities,
  221. 221 }
  222. 222}
  223. 223
  224. 224///|
  225. 225/// 智能字符分割(根据语言类型选择分割策略)
  226. 226pub fn smart_segment_chars(
  227. 227 img : @types.Image,
  228. 228 config : MultilingualOcrEnhancedConfig,
  229. 229) -> Array[(Int32, Int32, Int32, Int32, String)] raise @types.LoadError {
  230. 230 // 输入验证
  231. 231● if img.width <= 0 || img.height <= 0 {
  232. 232● raise @types.LoadError::DecodeFailed(
  233. 233 "smart_segment_chars: 图像尺寸必须大于0",
  234. 234 )
  235. 235 }
  236. 236 if img.channels != 1 {
  237. 237● raise @types.LoadError::DecodeFailed(
  238. 238 "smart_segment_chars: 仅支持单通道灰度图",
  239. 239 )
  240. 240 }
  241. 241 let expected_size = img.width * img.height
  242. 242● if img.data.length() != expected_size {
  243. 243● raise @types.LoadError::DecodeFailed(
  244. 244 "smart_segment_chars: 数据大小不匹配,期望 " +
  245. 245● expected_size.to_string() +
  246. 246 ",实际 " +
  247. 247● img.data.length().to_string(),
  248. 248 )
  249. 249 }
  250. 250 let w = img.width
  251. 251 let h = img.height
  252. 252 let data = img.data
  253. 253 // 先进行连通域分割
  254. 254● let labels : Array[Int32] = Array::make(w * h, 0)
  255. 255 let mut next_label = 1
  256. 256 for y in 0..<h {
  257. 257● for x in 0..<w {
  258. 258● if data[y * w + x].to_int() > 128 {
  259. 259● let mut label = 0
  260. 260 if x > 0 && labels[y * w + x - 1] > 0 {
  261. 261● label = labels[y * w + x - 1]
  262. 262 }
  263. 263 if y > 0 && labels[(y - 1) * w + x] > 0 {
  264. 264● if label == 0 {
  265. 265● label = labels[(y - 1) * w + x]
  266. 266 }
  267. 267 }
  268. 268 if label == 0 {
  269. 269● label = next_label
  270. 270 next_label += 1
  271. 271 }
  272. 272 labels[y * w + x] = label
  273. 273 }
  274. 274 }
  275. 275 }
  276. 276 // 计算边界框
  277. 277● let min_x : Array[Int32] = Array::make(next_label, w)
  278. 278● let max_x : Array[Int32] = Array::make(next_label, 0)
  279. 279● let min_y : Array[Int32] = Array::make(next_label, h)
  280. 280● let max_y : Array[Int32] = Array::make(next_label, 0)
  281. 281● let area : Array[Int32] = Array::make(next_label, 0)
  282. 282 for y in 0..<h {
  283. 283● for x in 0..<w {
  284. 284● let label = labels[y * w + x]
  285. 285 if label > 0 {
  286. 286● area[label] += 1
  287. 287 if x < min_x[label] {
  288. 288● min_x[label] = x
  289. 289 }
  290. 290 if x > max_x[label] {
  291. 291● max_x[label] = x
  292. 292 }
  293. 293 if y < min_y[label] {
  294. 294● min_y[label] = y
  295. 295 }
  296. 296 if y > max_y[label] {
  297. 297● max_y[label] = y
  298. 298 }
  299. 299 }
  300. 300 }
  301. 301 }
  302. 302 // 对每个连通域进行语言检测和分类
  303. 303 let regions : Array[(Int32, Int32, Int32, Int32, String)] = []
  304. 304 for label in 1..<next_label {
  305. 305● let rw = max_x[label] - min_x[label] + 1
  306. 306 let rh = max_y[label] - min_y[label] + 1
  307. 307 if rw >= 5 && rw <= 100 && rh >= 8 && rh <= 100 && area[label] > 10 {
  308. 308 // 提取字符图像进行语言检测
  309. 309● let char_img = extract_char_region_for_smart(
  310. 310 img,
  311. 311 min_x[label],
  312. 312 min_y[label],
  313. 313 rw,
  314. 314 rh,
  315. 315 32,
  316. 316 )
  317. 317 let lang_result = if config.auto_language_detection {
  318. 318● detect_language_enhanced(char_img)
  319. 319 } else {
  320. 320● LanguageDetectionResult::{
  321. 321 language: "unknown",
  322. 322 confidence: 0.0,
  323. 323 probabilities: [],
  324. 324 }
  325. 325 }
  326. 326● regions.push((min_x[label], min_y[label], rw, rh, lang_result.language))
  327. 327 }
  328. 328 }
  329. 329 regions
  330. 330}
  331. 331
  332. 332///|
  333. 333/// 提取字符区域(智能分割用)
  334. 334fn extract_char_region_for_smart(
  335. 335 img : @types.Image,
  336. 336 x : Int32,
  337. 337 y : Int32,
  338. 338 width : Int32,
  339. 339 height : Int32,
  340. 340 target_size : Int32,
  341. 341) -> @types.Image {
  342. 342● let w = img.width
  343. 343 let h = img.height
  344. 344● let crop_w = if x + width > w { w - x } else { width }
  345. 345● let crop_h = if y + height > h { h - y } else { height }
  346. 346 if crop_w <= 0 || crop_h <= 0 {
  347. 347● let empty : Array[Byte] = Array::make(target_size * target_size, b'\x00')
  348. 348 return @types.Image::{
  349. 349 width: target_size,
  350. 350 height: target_size,
  351. 351 channels: 1,
  352. 352● data: Bytes::from_array(empty),
  353. 353 }
  354. 354 }
  355. 355● let out : Array[Byte] = Array::make(target_size * target_size, b'\x00')
  356. 356 let data = img.data
  357. 357 for py in 0..<target_size {
  358. 358● for px in 0..<target_size {
  359. 359● let src_x = x + px * crop_w / target_size
  360. 360 let src_y = y + py * crop_h / target_size
  361. 361 if src_x < w && src_y < h {
  362. 362● out[py * target_size + px] = data[src_y * w + src_x]
  363. 363 }
  364. 364 }
  365. 365 }
  366. 366 @types.Image::{
  367. 367 width: target_size,
  368. 368 height: target_size,
  369. 369 channels: 1,
  370. 370● data: Bytes::from_array(out),
  371. 371 }
  372. 372}
  373. 373
  374. 374///|
  375. 375/// 智能空格处理(中英文之间自动加空格)
  376. 376fn moe_char_str(raw : UInt16) -> String {
  377. 377● raw.to_int().to_char().map(c => c.to_string()).unwrap_or("")
  378. 378}
  379. 379
  380. 380///|
  381. 381pub fn smart_spacing_process(
  382. 382 text : String,
  383. 383 char_languages : Array[String],
  384. 384) -> String {
  385. 385● if text.length() != char_languages.length() || text.length() == 0 {
  386. 386● return text
  387. 387 }
  388. 388 let mut result = ""
  389. 389● for i in 0..<text.length() {
  390. 390● result += moe_char_str(text[i])
  391. 391 // 在中英文之间加空格
  392. 392● if i < text.length() - 1 {
  393. 393● let curr_lang = char_languages[i]
  394. 394 let next_lang = char_languages[i + 1]
  395. 395 let is_cjk = curr_lang == "chinese" ||
  396. 396 curr_lang == "japanese" ||
  397. 397 curr_lang == "korean"
  398. 398 let next_is_cjk = next_lang == "chinese" ||
  399. 399 next_lang == "japanese" ||
  400. 400 next_lang == "korean"
  401. 401 let is_latin = curr_lang == "english" || curr_lang == "digit"
  402. 402 let next_is_latin = next_lang == "english" || next_lang == "digit"
  403. 403 // CJK 和 Latin 之间加空格
  404. 404 if (is_cjk && next_is_latin) || (is_latin && next_is_cjk) {
  405. 405● result += " "
  406. 406 }
  407. 407 }
  408. 408 }
  409. 409 result
  410. 410}
  411. 411
  412. 412///|
  413. 413/// 标点符号规范化(中英文标点自动转换)
  414. 414pub fn normalize_punctuation(
  415. 415 text : String,
  416. 416 char_languages : Array[String],
  417. 417) -> String {
  418. 418● if text.length() != char_languages.length() || text.length() == 0 {
  419. 419● return text
  420. 420 }
  421. 421 let mut result = ""
  422. 422● for i in 0..<text.length() {
  423. 423● let c = moe_char_str(text[i])
  424. 424 let lang = char_languages[i]
  425. 425 // 中文语境下使用中文标点
  426. 426 if lang == "chinese" {
  427. 427● match c {
  428. 428● "," => result += ","
  429. 429● "." => result += "。"
  430. 430● "!" => result += "!"
  431. 431● "?" => result += "?"
  432. 432● ";" => result += ";"
  433. 433● ":" => result += ":"
  434. 434● "(" => result += "("
  435. 435● ")" => result += ")"
  436. 436● _ => result += c
  437. 437 }
  438. 438 } else {
  439. 439 // 英文语境下使用英文标点
  440. 440● match c {
  441. 441● "," => result += ","
  442. 442● "。" => result += "."
  443. 443● "!" => result += "!"
  444. 444● "?" => result += "?"
  445. 445● ";" => result += ";"
  446. 446● ":" => result += ":"
  447. 447● "(" => result += "("
  448. 448● ")" => result += ")"
  449. 449● _ => result += c
  450. 450 }
  451. 451 }
  452. 452 }
  453. 453 result
  454. 454}
  455. 455
  456. 456///|
  457. 457/// 语言模型后处理(基于N-gram的混排纠错)
  458. 458pub fn language_model_postprocess(
  459. 459 text : String,
  460. 460 char_languages : Array[String],
  461. 461 confidences : Array[Double],
  462. 462) -> (String, Array[Double]) {
  463. 463● ignore(char_languages)
  464. 464 // 简化版语言模型:基于常见模式的纠错
  465. 465 let corrected_text = text
  466. 466 let adjusted_confidences = confidences
  467. 467 // 常见纠错规则(简化版)
  468. 468 // 规则1:中文后面跟英文标点,改为中文标点
  469. 469 // 规则2:英文单词中间插入中文字符,可能是识别错误
  470. 470 // 规则3:连续相同字符可能是重复
  471. 471 // 这里只做简单的置信度调整
  472. 472● for i in 0..<adjusted_confidences.length() {
  473. 473 // 低置信度字符的置信度进一步降低
  474. 474● if adjusted_confidences[i] < 0.3 {
  475. 475● adjusted_confidences[i] = adjusted_confidences[i] * 0.9
  476. 476 }
  477. 477 }
  478. 478 (corrected_text, adjusted_confidences)
  479. 479}
  480. 480
  481. 481///|
  482. 482/// 增强多语言混合识别(完整流水线)
  483. 483pub fn recognize_multilingual_enhanced(
  484. 484 img : @types.Image,
  485. 485 config? : MultilingualOcrEnhancedConfig,
  486. 486) -> OcrResult raise @types.LoadError {
  487. 487 // 输入验证
  488. 488● if img.width <= 0 || img.height <= 0 {
  489. 489● raise @types.LoadError::DecodeFailed(
  490. 490 "recognize_multilingual_enhanced: 图像尺寸必须大于0",
  491. 491 )
  492. 492 }
  493. 493 if img.channels < 1 || img.channels > 4 {
  494. 494● raise @types.LoadError::DecodeFailed(
  495. 495 "recognize_multilingual_enhanced: 通道数必须在1-4之间",
  496. 496 )
  497. 497 }
  498. 498 let expected_size = img.width * img.height * img.channels
  499. 499● if img.data.length() != expected_size {
  500. 500● raise @types.LoadError::DecodeFailed(
  501. 501 "recognize_multilingual_enhanced: 数据大小不匹配,期望 " +
  502. 502● expected_size.to_string() +
  503. 503 ",实际 " +
  504. 504● img.data.length().to_string(),
  505. 505 )
  506. 506 }
  507. 507● let cfg = match config {
  508. 508● Some(c) => c
  509. 509● None => multilingual_ocr_enhanced_default_config()
  510. 510 }
  511. 511 // 1. 预处理
  512. 512● let preprocessed = ocr_preprocess(img)
  513. 513 // 2. 智能字符分割(带语言检测)
  514. 514● let char_regions = smart_segment_chars(preprocessed, cfg)
  515. 515 // 3. 生成各语言模板
  516. 516 let chinese_templates = if cfg.enable_chinese {
  517. 517● generate_enhanced_chinese_templates(char_set_size=500)
  518. 518 } else {
  519. 519● []
  520. 520 }
  521. 521 let english_templates = if cfg.enable_english {
  522. 522● generate_enhanced_handwriting_templates(
  523. 523 char_set="digits+letters",
  524. 524 num_variants=3,
  525. 525 )
  526. 526 } else {
  527. 527● []
  528. 528 }
  529. 529 let digit_templates = if cfg.enable_digits {
  530. 530● generate_digit_templates()
  531. 531 } else {
  532. 532● []
  533. 533 }
  534. 534 let punctuation_templates = if cfg.enable_punctuation {
  535. 535● generate_punctuation_templates()
  536. 536 } else {
  537. 537● []
  538. 538 }
  539. 539 // 4. 对每个字符进行识别
  540. 540 let char_results : Array[OcrCharResult] = []
  541. 541 let mut text = ""
  542. 542 let mut total_confidence = 0.0
  543. 543 let char_languages : Array[String] = []
  544. 544 let confidences : Array[Double] = []
  545. 545 for _tup1 in char_regions {
  546. 546● let (x, y, w, h, detected_lang) = _tup1
  547. 547 // 提取字符图像
  548. 548● let char_img = extract_char_region_for_smart(
  549. 549 preprocessed,
  550. 550 x,
  551. 551 y,
  552. 552 w,
  553. 553 h,
  554. 554 cfg.target_size,
  555. 555 )
  556. 556 // 根据检测到的语言选择模板
  557. 557● let result = match detected_lang {
  558. 558 "chinese" =>
  559. 559● if chinese_templates.length() > 0 {
  560. 560● match_multilingual_enhanced(
  561. 561 char_img,
  562. 562 chinese_templates,
  563. 563 cfg.distance_metric,
  564. 564 )
  565. 565 } else {
  566. 566○ ("?", 0.0)
  567. 567 }
  568. 568 "english" =>
  569. 569○ if english_templates.length() > 0 {
  570. 570○ match_multilingual_enhanced(
  571. 571 char_img,
  572. 572 english_templates,
  573. 573 cfg.distance_metric,
  574. 574 )
  575. 575 } else {
  576. 576○ ("?", 0.0)
  577. 577 }
  578. 578 "digit" =>
  579. 579○ if digit_templates.length() > 0 {
  580. 580○ match_multilingual_enhanced(
  581. 581 char_img,
  582. 582 digit_templates,
  583. 583 cfg.distance_metric,
  584. 584 )
  585. 585 } else {
  586. 586○ ("?", 0.0)
  587. 587 }
  588. 588 "punctuation" =>
  589. 589○ if punctuation_templates.length() > 0 {
  590. 590○ match_punctuation_enhanced(char_img, punctuation_templates)
  591. 591 } else {
  592. 592○ ("?", 0.0)
  593. 593 }
  594. 594● _ => {
  595. 595 // 未知语言,尝试所有模板
  596. 596 let all_templates : Array[(String, Array[Double])] = []
  597. 597 for t in chinese_templates {
  598. 598● all_templates.push(t)
  599. 599 }
  600. 600 for t in english_templates {
  601. 601● all_templates.push(t)
  602. 602 }
  603. 603 for t in digit_templates {
  604. 604● all_templates.push(t)
  605. 605 }
  606. 606● if all_templates.length() > 0 {
  607. 607● match_multilingual_enhanced(
  608. 608 char_img,
  609. 609 all_templates,
  610. 610 cfg.distance_metric,
  611. 611 )
  612. 612 } else {
  613. 613● ("?", 0.0)
  614. 614 }
  615. 615 }
  616. 616 }
  617. 617 text += result.0
  618. 618 total_confidence += result.1
  619. 619● char_languages.push(detected_lang)
  620. 620● confidences.push(result.1)
  621. 621● char_results.push(OcrCharResult::{
  622. 622 char: result.0,
  623. 623 confidence: result.1,
  624. 624 x,
  625. 625 y,
  626. 626 width: w,
  627. 627 height: h,
  628. 628 })
  629. 629 }
  630. 630 // 5. 后处理
  631. 631● let final_text = if char_results.length() > 0 {
  632. 632● let mut processed = text
  633. 633 // 智能空格处理
  634. 634 if cfg.smart_spacing {
  635. 635● processed = smart_spacing_process(processed, char_languages)
  636. 636 }
  637. 637 // 标点符号规范化
  638. 638 if cfg.punctuation_normalization {
  639. 639● processed = normalize_punctuation(processed, char_languages)
  640. 640 }
  641. 641 // 语言模型后处理
  642. 642 if cfg.use_language_model {
  643. 643● let (t, _) = language_model_postprocess(
  644. 644 processed, char_languages, confidences,
  645. 645 )
  646. 646 processed = t
  647. 647 }
  648. 648 processed
  649. 649 } else {
  650. 650● text
  651. 651 }
  652. 652● let avg_confidence = if char_results.length() > 0 {
  653. 653● total_confidence / char_results.length().to_double()
  654. 654 } else {
  655. 655● 0.0
  656. 656 }
  657. 657 OcrResult::{
  658. 658 text: final_text,
  659. 659 confidence: avg_confidence,
  660. 660 characters: char_results,
  661. 661 }
  662. 662}
  663. 663
  664. 664///|
  665. 665/// 增强多语言模板匹配
  666. 666fn match_multilingual_enhanced(
  667. 667 char_img : @types.Image,
  668. 668 templates : Array[(String, Array[Double])],
  669. 669 distance_metric : String,
  670. 670) -> (String, Double) {
  671. 671● let w = char_img.width
  672. 672 let h = char_img.height
  673. 673 let data = char_img.data
  674. 674 // 提取网格特征
  675. 675 let grid_size = 16
  676. 676 let cell_w = w / grid_size
  677. 677 let cell_h = h / grid_size
  678. 678 let features : Array[Double] = []
  679. 679 for r in 0..<grid_size {
  680. 680● for c in 0..<grid_size {
  681. 681● let mut count = 0
  682. 682 let mut total = 0
  683. 683 for py in 0..<cell_h {
  684. 684● for px in 0..<cell_w {
  685. 685● let sx = c * cell_w + px
  686. 686 let sy = r * cell_h + py
  687. 687 if sx < w && sy < h {
  688. 688● total += 1
  689. 689● if data[sy * w + sx].to_int() > 128 {
  690. 690● count += 1
  691. 691 }
  692. 692 }
  693. 693 }
  694. 694 }
  695. 695 let density = if total > 0 {
  696. 696● count.to_double() / total.to_double()
  697. 697 } else {
  698. 698○ 0.0
  699. 699 }
  700. 700● features.push(density)
  701. 701 }
  702. 702 }
  703. 703 // 模板匹配
  704. 704 let mut best_label = "?"
  705. 705 let mut best_dist = 1000000.0
  706. 706 for _tup2 in templates {
  707. 707● let (label, template) = _tup2
  708. 708● let n = if features.length() < template.length() {
  709. 709● features.length()
  710. 710 } else {
  711. 711● template.length()
  712. 712 }
  713. 713 let mut dist = 0.0
  714. 714● match distance_metric {
  715. 715 "manhattan" =>
  716. 716● for i in 0..<n {
  717. 717● dist += (features[i] - template[i]).abs()
  718. 718 }
  719. 719○ "cosine" => {
  720. 720 let mut dot = 0.0
  721. 721 let mut norm_a = 0.0
  722. 722 let mut norm_b = 0.0
  723. 723 for i in 0..<n {
  724. 724○ dot += features[i] * template[i]
  725. 725 norm_a += features[i] * features[i]
  726. 726 norm_b += template[i] * template[i]
  727. 727 }
  728. 728○ let denom = norm_a.sqrt() * norm_b.sqrt()
  729. 729○ dist = if denom > 0.0 { 1.0 - dot / denom } else { 1.0 }
  730. 730 }
  731. 731● _ => {
  732. 732 for i in 0..<n {
  733. 733● let diff = features[i] - template[i]
  734. 734 dist += diff * diff
  735. 735 }
  736. 736● dist = dist.sqrt()
  737. 737 }
  738. 738 }
  739. 739 if dist < best_dist {
  740. 740● best_dist = dist
  741. 741 best_label = label
  742. 742 }
  743. 743 }
  744. 744◐ let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 }
  745. 745 (best_label, confidence)
  746. 746}
  747. 747
  748. 748///|
  749. 749/// 增强标点符号模板匹配
  750. 750fn match_punctuation_enhanced(
  751. 751 char_img : @types.Image,
  752. 752 templates : Array[PunctuationTemplate],
  753. 753) -> (String, Double) {
  754. 754○ let w = char_img.width
  755. 755 let h = char_img.height
  756. 756 let data = char_img.data
  757. 757 let grid_size = 16
  758. 758 let cell_w = w / grid_size
  759. 759 let cell_h = h / grid_size
  760. 760 let features : Array[Double] = []
  761. 761 for r in 0..<grid_size {
  762. 762○ for c in 0..<grid_size {
  763. 763○ let mut count = 0
  764. 764 let mut total = 0
  765. 765 for py in 0..<cell_h {
  766. 766○ for px in 0..<cell_w {
  767. 767○ let sx = c * cell_w + px
  768. 768 let sy = r * cell_h + py
  769. 769 if sx < w && sy < h {
  770. 770○ total += 1
  771. 771○ if data[sy * w + sx].to_int() > 128 {
  772. 772○ count += 1
  773. 773 }
  774. 774 }
  775. 775 }
  776. 776 }
  777. 777 let density = if total > 0 {
  778. 778○ count.to_double() / total.to_double()
  779. 779 } else {
  780. 780○ 0.0
  781. 781 }
  782. 782○ features.push(density)
  783. 783 }
  784. 784 }
  785. 785 let mut best_label = "?"
  786. 786 let mut best_dist = 1000000.0
  787. 787 for template in templates {
  788. 788○ let n = if features.length() < template.features.length() {
  789. 789○ features.length()
  790. 790 } else {
  791. 791○ template.features.length()
  792. 792 }
  793. 793 let mut dist = 0.0
  794. 794 for i in 0..<n {
  795. 795○ let diff = features[i] - template.features[i]
  796. 796 dist += diff * diff
  797. 797 }
  798. 798○ dist = dist.sqrt()
  799. 799 if dist < best_dist {
  800. 800○ best_dist = dist
  801. 801 best_label = template.char
  802. 802 }
  803. 803 }
  804. 804○ let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 }
  805. 805 (best_label, confidence)
  806. 806}