image.vision\ocr\ocr_prepare.mbt

91.7% · 22 / 24 points · 65 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/// # 极性归一到「墨 = 亮」(S30)
  3. 3///
  4. 4/// 整条英文识别链里,**前景约定是亮像素**:`segment_by_connected_components` 以 `>128` 标记连通域、
  5. 5/// `extract_char_features_english` 以 `>128` 统计墨密度。而多数真实图像是**白底黑字**(墨是暗的),
  6. 6/// 直接喂进链路会把整片背景当成一个字、把字当成孔洞——实测 `A` 被切成 8 段,识别结果是空串。
  7. 7///
  8. 8/// 这里补上极性归一:先把图转成单通道,再判断"少数派"是哪一侧(墨永远比背景少),
  9. 9/// 输出一张 `墨=255 / 底=0` 的二值图。
  10. 10///
  11. 11/// **快路径**:图像本身已经接近二值(中间灰 `(64,192)` 占比 ≤ 5%)时**不走 `ocr_preprocess`**。
  12. 12/// 原因是 `ocr_preprocess` 是给真实扫描件设计的(`document_enhance` + `deskew` + `sauvola`),
  13. 13/// 对已经干净的合成图属于过度处理:实测把一张 84×92 的清晰 `A` 削成顶部一小块。
  14. 14/// 灰阶图仍走完整预处理链,行为与旧版一致。
  15. 15pub fn ocr_prepare_ink(
  16. 16 img : @types.Image,
  17. 17) -> @types.Image raise @types.LoadError {
  18. 18● if img.width <= 0 || img.height <= 0 {
  19. 19○ raise @types.LoadError::DecodeFailed(
  20. 20 "ocr_prepare_ink: 图像尺寸必须大于0",
  21. 21 )
  22. 22 }
  23. 23◐ let gray = if img.channels == 1 { img } else { to_grayscale_ocr(img) }
  24. 24● let n = gray.data.length()
  25. 25 let mut mid = 0
  26. 26 for i in 0..<n {
  27. 27● let v = gray.data[i].to_int()
  28. 28 if v > 64 && v < 192 {
  29. 29● mid += 1
  30. 30 }
  31. 31 }
  32. 32 // 已经够二值:只做极性归一,压掉预处理链带来的信息损失
  33. 33 if n > 0 && mid * 20 <= n {
  34. 34● return ink_from_luminance(gray)
  35. 35 }
  36. 36● ink_from_luminance(ocr_preprocess(gray))
  37. 37}
  38. 38
  39. 39///|
  40. 40/// 亮度 → 墨:少数派当墨。`墨=255 / 底=0`。
  41. 41fn ink_from_luminance(img : @types.Image) -> @types.Image {
  42. 42● let n = img.data.length()
  43. 43 let mut dark = 0
  44. 44 for i in 0..<n {
  45. 45● if img.data[i].to_int() <= 128 {
  46. 46● dark += 1
  47. 47 }
  48. 48 }
  49. 49 // dark 少 → 墨是暗的(白底黑字)→ 用 `<=128`;dark 多 → 墨是亮的(黑底白字)→ 用 `>128`
  50. 50 let ink_is_dark = dark * 2 <= n
  51. 51● let out : Array[Byte] = Array::make(n, b'\x00')
  52. 52 for i in 0..<n {
  53. 53● let v = img.data[i].to_int()
  54. 54● let is_ink = if ink_is_dark { v <= 128 } else { v > 128 }
  55. 55 if is_ink {
  56. 56● out[i] = b'\xFF'
  57. 57 }
  58. 58 }
  59. 59 @types.Image::{
  60. 60 width: img.width,
  61. 61 height: img.height,
  62. 62 channels: 1,
  63. 63● data: Bytes::from_array(out),
  64. 64 }
  65. 65}