image.vision\ocr\english_ocr.mbt

95.9% · 142 / 148 points · 400 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/english_ocr
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 英文 OCR
  7. 7// 数字+字母识别(0-9, A-Z, a-z)
  8. 8
  9. 9///|
  10. 10/// 英文 OCR 配置
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct EnglishOcrConfig {
  13. 13 min_char_width : Int32
  14. 14 max_char_width : Int32
  15. 15 target_size : Int32
  16. 16 distance_metric : String
  17. 17 case_sensitive : Bool
  18. 18}
  19. 19
  20. 20///|
  21. 21pub extend EnglishOcrConfig with Eq::{not_equal, equal}
  22. 22
  23. 23///|
  24. 24pub extend EnglishOcrConfig with @debug.Debug::{to_repr}
  25. 25
  26. 26///|
  27. 27/// 创建默认英文 OCR 配置
  28. 28pub fn english_ocr_default_config() -> EnglishOcrConfig {
  29. 29● EnglishOcrConfig::{
  30. 30 min_char_width: 5,
  31. 31 max_char_width: 60,
  32. 32 target_size: 32,
  33. 33 distance_metric: "euclidean",
  34. 34 case_sensitive: false,
  35. 35 }
  36. 36}
  37. 37
  38. 38///|
  39. 39/// 生成英文字符模板(0-9, A-Z / 可选 a-z)。
  40. 40///
  41. 41/// 模板不是手画形状,而是从内建 5×7 字库(`glyph_bank.mbt`)**用与样本同一条链路渲染**:
  42. 42/// 渲染 → 裁到墨迹包围盒 → 缩放到 `target_size` → 取 `grid×grid` 密度。
  43. 43/// 每个字符给 `scales` 里的每个整数倍各出一份模板(默认 3/4/5),匹配时取最小距离,
  44. 44/// 用来吸收"同一字符被渲染成不同像素密度"时的取整抖动。
  45. 45pub fn generate_english_templates(
  46. 46 case_sensitive~ : Bool = false,
  47. 47 target_size~ : Int32 = 32,
  48. 48 grid_size~ : Int32 = 8,
  49. 49 scales~ : Array[Int32] = [3, 4, 5],
  50. 50) -> Array[(String, Array[Double])] {
  51. 51● let templates : Array[(String, Array[Double])] = []
  52. 52● let push_char = (label : String, ch : Char) => {
  53. 53 for scale in scales {
  54. 54● match glyph_template_features(ch, scale, target_size, grid_size) {
  55. 55● Some(features) => templates.push((label, features))
  56. 56○ None => ()
  57. 57 }
  58. 58 }
  59. 59 }
  60. 60 // 数字 0-9
  61. 61 for digit in 0..<10 {
  62. 62● match (48 + digit).to_char() {
  63. 63● Some(ch) => push_char(ch.to_string(), ch)
  64. 64○ None => ()
  65. 65 }
  66. 66 }
  67. 67 // 大写字母 A-Z
  68. 68 for code in 65..<91 {
  69. 69● match code.to_char() {
  70. 70● Some(ch) => push_char(ch.to_string(), ch)
  71. 71○ None => ()
  72. 72 }
  73. 73 }
  74. 74 // 区分大小写时补小写(字库折叠到大写,但标签要保留小写)
  75. 75 if case_sensitive {
  76. 76● for code in 97..<123 {
  77. 77● match code.to_char() {
  78. 78● Some(ch) => push_char(ch.to_string(), ch)
  79. 79○ None => ()
  80. 80 }
  81. 81 }
  82. 82 }
  83. 83 templates
  84. 84}
  85. 85
  86. 86///|
  87. 87/// 墨迹包围盒(白底 255 / 黑字 <= 128)。
  88. 88fn glyph_ink_box(img : @types.Image) -> (Int32, Int32, Int32, Int32) {
  89. 89● let w = img.width
  90. 90 let h = img.height
  91. 91 let mut min_x = w
  92. 92 let mut min_y = h
  93. 93 let mut max_x = -1
  94. 94 let mut max_y = -1
  95. 95 for y in 0..<h {
  96. 96● for x in 0..<w {
  97. 97● if img.data[y * w + x].to_int() > 128 {
  98. 98● if x < min_x {
  99. 99● min_x = x
  100. 100 }
  101. 101 if y < min_y {
  102. 102● min_y = y
  103. 103 }
  104. 104 if x > max_x {
  105. 105● max_x = x
  106. 106 }
  107. 107 if y > max_y {
  108. 108● max_y = y
  109. 109 }
  110. 110 }
  111. 111 }
  112. 112 }
  113. 113 if max_x < 0 || max_y < 0 {
  114. 114○ return (0, 0, w, h)
  115. 115 }
  116. 116 (min_x, min_y, max_x - min_x + 1, max_y - min_y + 1)
  117. 117}
  118. 118
  119. 119///|
  120. 120/// 单个字符在给定渲染倍率下的模板特征。
  121. 121///
  122. 122/// 与 `recognize_english` 的样本路径逐段对齐:同一渲染器 → 同一 bbox 裁剪 →
  123. 123/// 同一 `extract_char_region_english` 缩放 → 同一 `extract_char_features_english` 密度。
  124. 124fn glyph_template_features(
  125. 125 ch : Char,
  126. 126 scale : Int32,
  127. 127 target_size : Int32,
  128. 128 grid_size : Int32,
  129. 129) -> Array[Double]? {
  130. 130● match render_glyph(ch, scale~, margin=4) {
  131. 131○ None => None
  132. 132● Some(img) => {
  133. 133● let (bx, by, bw, bh) = glyph_ink_box(img)
  134. 134● let norm = extract_char_region_english(img, bx, by, bw, bh, target_size)
  135. 135● Some(extract_char_features_english(norm, grid_size))
  136. 136 }
  137. 137 }
  138. 138}
  139. 139
  140. 140///|
  141. 141/// 英文 OCR 识别(完整流水线)
  142. 142pub fn recognize_english(
  143. 143 img : @types.Image,
  144. 144 config? : EnglishOcrConfig,
  145. 145) -> OcrResult raise @types.LoadError {
  146. 146 // 输入验证
  147. 147● if img.width <= 0 || img.height <= 0 {
  148. 148● raise @types.LoadError::DecodeFailed(
  149. 149 "recognize_english: 图像尺寸必须大于0",
  150. 150 )
  151. 151 }
  152. 152 if img.channels != 1 {
  153. 153● raise @types.LoadError::DecodeFailed(
  154. 154 "recognize_english: 仅支持单通道灰度图",
  155. 155 )
  156. 156 }
  157. 157 let expected_size = img.width * img.height
  158. 158● if img.data.length() != expected_size {
  159. 159● raise @types.LoadError::DecodeFailed(
  160. 160 "recognize_english: 数据大小不匹配,期望 " +
  161. 161● expected_size.to_string() +
  162. 162 ",实际 " +
  163. 163● img.data.length().to_string(),
  164. 164 )
  165. 165 }
  166. 166
  167. 167● let cfg = match config {
  168. 168● Some(c) => c
  169. 169● None => english_ocr_default_config()
  170. 170 }
  171. 171 // 配置验证
  172. 172 if cfg.min_char_width <= 0 {
  173. 173● raise @types.LoadError::DecodeFailed(
  174. 174 "recognize_english: min_char_width必须大于0",
  175. 175 )
  176. 176 }
  177. 177 if cfg.max_char_width < cfg.min_char_width {
  178. 178● raise @types.LoadError::DecodeFailed(
  179. 179 "recognize_english: max_char_width不能小于min_char_width",
  180. 180 )
  181. 181 }
  182. 182 if cfg.target_size <= 0 {
  183. 183● raise @types.LoadError::DecodeFailed(
  184. 184 "recognize_english: target_size必须大于0",
  185. 185 )
  186. 186 }
  187. 187 // 1. 预处理
  188. 188 // 极性归一 + 二值快路径:整链前景约定是「墨=亮」,输入可能是白底黑字
  189. 189● let preprocessed = ocr_prepare_ink(img)
  190. 190 // 2. 字符分割
  191. 191● let char_regions = complete_char_segmentation(
  192. 192 preprocessed,
  193. 193 min_char_width=cfg.min_char_width,
  194. 194 max_char_width=cfg.max_char_width,
  195. 195 )
  196. 196 // 3. 生成模板
  197. 197● let templates = generate_english_templates(
  198. 198 case_sensitive=cfg.case_sensitive,
  199. 199 target_size=cfg.target_size,
  200. 200 )
  201. 201 // 4. 对每个字符进行识别
  202. 202 let char_results : Array[OcrCharResult] = []
  203. 203 let mut text = ""
  204. 204 let mut total_confidence = 0.0
  205. 205 for _tup0 in char_regions {
  206. 206● let (x, y, w, h) = _tup0
  207. 207 // 提取字符图像
  208. 208● let char_img = extract_char_region_english(
  209. 209 preprocessed,
  210. 210 x,
  211. 211 y,
  212. 212 w,
  213. 213 h,
  214. 214 cfg.target_size,
  215. 215 )
  216. 216 // 提取特征
  217. 217● let features = extract_char_features_english(char_img, 8)
  218. 218 // 模板匹配
  219. 219● let result = match_template_english(
  220. 220 features,
  221. 221 templates,
  222. 222 cfg.distance_metric,
  223. 223 )
  224. 224 text += result.0
  225. 225 total_confidence += result.1
  226. 226● char_results.push(OcrCharResult::{
  227. 227 char: result.0,
  228. 228 confidence: result.1,
  229. 229 x,
  230. 230 y,
  231. 231 width: w,
  232. 232 height: h,
  233. 233 })
  234. 234 }
  235. 235● let avg_confidence = if char_results.length() > 0 {
  236. 236● total_confidence / char_results.length().to_double()
  237. 237 } else {
  238. 238● 0.0
  239. 239 }
  240. 240 OcrResult::{ text, confidence: avg_confidence, characters: char_results, }
  241. 241}
  242. 242
  243. 243///|
  244. 244/// 提取字符区域(英文OCR专用)
  245. 245fn extract_char_region_english(
  246. 246 img : @types.Image,
  247. 247 x : Int32,
  248. 248 y : Int32,
  249. 249 width : Int32,
  250. 250 height : Int32,
  251. 251 target_size : Int32,
  252. 252) -> @types.Image {
  253. 253● let w = img.width
  254. 254 let h = img.height
  255. 255● let crop_w = if x + width > w { w - x } else { width }
  256. 256● let crop_h = if y + height > h { h - y } else { height }
  257. 257 if crop_w <= 0 || crop_h <= 0 {
  258. 258● let empty : Array[Byte] = Array::make(target_size * target_size, b'\x00')
  259. 259 return @types.Image::{
  260. 260 width: target_size,
  261. 261 height: target_size,
  262. 262 channels: 1,
  263. 263● data: Bytes::from_array(empty),
  264. 264 }
  265. 265 }
  266. 266 let scale = if crop_w > crop_h {
  267. 267● target_size.to_double() / crop_w.to_double()
  268. 268 } else {
  269. 269● target_size.to_double() / crop_h.to_double()
  270. 270 }
  271. 271● let new_w = @types.int_max(1, (crop_w.to_double() * scale).to_int())
  272. 272● let new_h = @types.int_max(1, (crop_h.to_double() * scale).to_int())
  273. 273 let offset_x = (target_size - new_w) / 2
  274. 274 let offset_y = (target_size - new_h) / 2
  275. 275● let out : Array[Byte] = Array::make(target_size * target_size, b'\x00')
  276. 276 let data = img.data
  277. 277 for py in 0..<new_h {
  278. 278● for px in 0..<new_w {
  279. 279● let src_x = x + px * crop_w / new_w
  280. 280 let src_y = y + py * crop_h / new_h
  281. 281 if src_x < w && src_y < h {
  282. 282● out[(offset_y + py) * target_size + (offset_x + px)] = data[src_y * w +
  283. 283 src_x]
  284. 284 }
  285. 285 }
  286. 286 }
  287. 287 @types.Image::{
  288. 288 width: target_size,
  289. 289 height: target_size,
  290. 290 channels: 1,
  291. 291● data: Bytes::from_array(out),
  292. 292 }
  293. 293}
  294. 294
  295. 295///|
  296. 296/// 提取字符特征(英文OCR专用)
  297. 297fn extract_char_features_english(
  298. 298 char_img : @types.Image,
  299. 299 grid_size : Int32,
  300. 300) -> Array[Double] {
  301. 301● let w = char_img.width
  302. 302 let h = char_img.height
  303. 303 let data = char_img.data
  304. 304 let cell_w = w / grid_size
  305. 305 let cell_h = h / grid_size
  306. 306 let features : Array[Double] = []
  307. 307 for r in 0..<grid_size {
  308. 308● for c in 0..<grid_size {
  309. 309● let mut count = 0
  310. 310 let mut total = 0
  311. 311 for py in 0..<cell_h {
  312. 312● for px in 0..<cell_w {
  313. 313● let sx = c * cell_w + px
  314. 314 let sy = r * cell_h + py
  315. 315 if sx < w && sy < h {
  316. 316● total += 1
  317. 317● if data[sy * w + sx].to_int() > 128 {
  318. 318● count += 1
  319. 319 }
  320. 320 }
  321. 321 }
  322. 322 }
  323. 323 let density = if total > 0 {
  324. 324● count.to_double() / total.to_double()
  325. 325 } else {
  326. 326● 0.0
  327. 327 }
  328. 328● features.push(density)
  329. 329 }
  330. 330 }
  331. 331 features
  332. 332}
  333. 333
  334. 334///|
  335. 335/// 模板匹配(英文OCR专用)
  336. 336fn match_template_english(
  337. 337 features : Array[Double],
  338. 338 templates : Array[(String, Array[Double])],
  339. 339 distance_metric : String,
  340. 340) -> (String, Double) {
  341. 341● let mut best_label = "?"
  342. 342 let mut best_dist = 1000000.0
  343. 343 for _tup1 in templates {
  344. 344● let (label, template) = _tup1
  345. 345● let dist = match distance_metric {
  346. 346● "manhattan" => manhattan_distance_eng(features, template)
  347. 347● "cosine" => cosine_distance_eng(features, template)
  348. 348● _ => euclidean_distance_eng(features, template)
  349. 349 }
  350. 350 if dist < best_dist {
  351. 351● best_dist = dist
  352. 352 best_label = label
  353. 353 }
  354. 354 }
  355. 355● let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 }
  356. 356 (best_label, confidence)
  357. 357}
  358. 358
  359. 359///|
  360. 360/// 局部欧氏距离
  361. 361fn euclidean_distance_eng(a : Array[Double], b : Array[Double]) -> Double {
  362. 362● let n = if a.length() < b.length() { a.length() } else { b.length() }
  363. 363 let mut sum_sq = 0.0
  364. 364 for i in 0..<n {
  365. 365● let diff = a[i] - b[i]
  366. 366 sum_sq += diff * diff
  367. 367 }
  368. 368● sum_sq.sqrt()
  369. 369}
  370. 370
  371. 371///|
  372. 372/// 局部曼哈顿距离
  373. 373fn manhattan_distance_eng(a : Array[Double], b : Array[Double]) -> Double {
  374. 374● let n = if a.length() < b.length() { a.length() } else { b.length() }
  375. 375 let mut sum = 0.0
  376. 376 for i in 0..<n {
  377. 377● sum += (a[i] - b[i]).abs()
  378. 378 }
  379. 379 sum
  380. 380}
  381. 381
  382. 382///|
  383. 383/// 局部余弦距离
  384. 384fn cosine_distance_eng(a : Array[Double], b : Array[Double]) -> Double {
  385. 385● let n = if a.length() < b.length() { a.length() } else { b.length() }
  386. 386 let mut dot = 0.0
  387. 387 let mut norm_a = 0.0
  388. 388 let mut norm_b = 0.0
  389. 389 for i in 0..<n {
  390. 390● dot += a[i] * b[i]
  391. 391 norm_a += a[i] * a[i]
  392. 392 norm_b += b[i] * b[i]
  393. 393 }
  394. 394● let denom = norm_a.sqrt() * norm_b.sqrt()
  395. 395 if denom > 0.0 {
  396. 396● 1.0 - dot / denom
  397. 397 } else {
  398. 398● 1.0
  399. 399 }
  400. 400}