image.vision\ocr\chinese_ocr.mbt

93.5% · 130 / 139 points · 416 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/chinese_ocr
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 中文 OCR 基础
  7. 7// 常用汉字识别(基于点阵模板)
  8. 8
  9. 9///|
  10. 10/// 中文 OCR 配置
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct ChineseOcrConfig {
  13. 13 min_char_width : Int32
  14. 14 max_char_width : Int32
  15. 15 target_size : Int32
  16. 16 distance_metric : String
  17. 17 char_set : String // "common" / "full"
  18. 18}
  19. 19
  20. 20///|
  21. 21pub extend ChineseOcrConfig with Eq::{not_equal, equal}
  22. 22
  23. 23///|
  24. 24pub extend ChineseOcrConfig with @debug.Debug::{to_repr}
  25. 25
  26. 26///|
  27. 27/// 创建默认中文 OCR 配置
  28. 28pub fn chinese_ocr_default_config() -> ChineseOcrConfig {
  29. 29● ChineseOcrConfig::{
  30. 30 min_char_width: 10,
  31. 31 max_char_width: 100,
  32. 32 target_size: 48,
  33. 33 distance_metric: "euclidean",
  34. 34 char_set: "common",
  35. 35 }
  36. 36}
  37. 37
  38. 38///|
  39. 39/// 生成常用汉字模板(100个常用汉字)
  40. 40pub fn generate_chinese_templates(
  41. 41 char_set~ : String = "common",
  42. 42) -> Array[(String, Array[Double])] {
  43. 43● let templates : Array[(String, Array[Double])] = []
  44. 44 // 常用汉字列表(100个最常用汉字)
  45. 45 let common_chars : Array[String] = [
  46. 46 "的", "一", "是", "在", "不", "了", "有", "和", "人", "这", "中",
  47. 47 "大", "为", "上", "个", "国", "我", "以", "要", "他", "时", "来",
  48. 48 "用", "们", "生", "到", "作", "地", "于", "出", "就", "分", "对",
  49. 49 "成", "会", "可", "主", "发", "年", "动", "同", "工", "也", "能",
  50. 50 "下", "过", "子", "说", "产", "种", "面", "而", "方", "后", "多",
  51. 51 "定", "行", "学", "法", "所", "民", "得", "经", "十", "三", "之",
  52. 52 "进", "着", "等", "部", "度", "家", "电", "力", "里", "如", "水",
  53. 53 "化", "高", "自", "二", "理", "起", "小", "物", "现", "实", "加",
  54. 54 "量", "都", "两", "体", "重", "机", "当", "使", "点", "从", "业",
  55. 55 "本",
  56. 56 ]
  57. 57 let chars = if char_set == "full" {
  58. 58 // 完整字符集(这里简化,仍然用常用汉字)
  59. 59● common_chars
  60. 60 } else {
  61. 61● common_chars
  62. 62 }
  63. 63 for char in chars {
  64. 64● let template = generate_chinese_char_template(char)
  65. 65● templates.push((char, template))
  66. 66 }
  67. 67 templates
  68. 68}
  69. 69
  70. 70///|
  71. 71/// 生成单个汉字模板(基于16x16点阵简化模式)
  72. 72fn generate_chinese_char_template(char : String) -> Array[Double] {
  73. 73● let size = 16
  74. 74● let features : Array[Double] = Array::make(size * size, 0.0)
  75. 75 // 简化的汉字模式(基于常见汉字结构)
  76. 76 // 这里使用字符的Unicode码点作为种子,生成伪随机但稳定的模式
  77. 77◐ let seed = if char.length() > 0 { char[0].to_int() } else { 0 }
  78. 78 // 基于种子生成模式(简化版,实际应该使用真实点阵字体)
  79. 79 for y in 0..<size {
  80. 80● for x in 0..<size {
  81. 81 // 使用简单的哈希函数生成模式
  82. 82● let hash = (seed * 31 + x * 17 + y * 13) % 100
  83. 83 // 中心区域更可能有像素
  84. 84● let center_dist = ((x - 8) * (x - 8) + (y - 8) * (y - 8)).to_double()
  85. 85 let center_factor = 1.0 - center_dist / 128.0
  86. 86● let threshold = 30 + (center_factor * 40.0).to_int()
  87. 87 if hash < threshold {
  88. 88● features[y * size + x] = 1.0
  89. 89 }
  90. 90 }
  91. 91 }
  92. 92 features
  93. 93}
  94. 94
  95. 95///|
  96. 96/// 中文 OCR 识别(完整流水线)
  97. 97pub fn recognize_chinese(
  98. 98 img : @types.Image,
  99. 99 config? : ChineseOcrConfig,
  100. 100) -> OcrResult raise @types.LoadError {
  101. 101 // 输入验证
  102. 102● if img.width <= 0 || img.height <= 0 {
  103. 103● raise @types.LoadError::DecodeFailed(
  104. 104 "recognize_chinese: 图像尺寸必须大于0",
  105. 105 )
  106. 106 }
  107. 107 if img.channels != 1 {
  108. 108● raise @types.LoadError::DecodeFailed(
  109. 109 "recognize_chinese: 仅支持单通道灰度图",
  110. 110 )
  111. 111 }
  112. 112 let expected_size = img.width * img.height
  113. 113● if img.data.length() != expected_size {
  114. 114● raise @types.LoadError::DecodeFailed(
  115. 115 "recognize_chinese: 数据大小不匹配,期望 " +
  116. 116● expected_size.to_string() +
  117. 117 ",实际 " +
  118. 118● img.data.length().to_string(),
  119. 119 )
  120. 120 }
  121. 121
  122. 122● let cfg = match config {
  123. 123● Some(c) => c
  124. 124● None => chinese_ocr_default_config()
  125. 125 }
  126. 126 // 配置验证
  127. 127 if cfg.min_char_width <= 0 {
  128. 128● raise @types.LoadError::DecodeFailed(
  129. 129 "recognize_chinese: min_char_width必须大于0",
  130. 130 )
  131. 131 }
  132. 132 if cfg.max_char_width < cfg.min_char_width {
  133. 133● raise @types.LoadError::DecodeFailed(
  134. 134 "recognize_chinese: max_char_width不能小于min_char_width",
  135. 135 )
  136. 136 }
  137. 137 if cfg.target_size <= 0 {
  138. 138● raise @types.LoadError::DecodeFailed(
  139. 139 "recognize_chinese: target_size必须大于0",
  140. 140 )
  141. 141 }
  142. 142 // 1. 预处理
  143. 143● let preprocessed = ocr_preprocess(img)
  144. 144 // 2. 字符分割(中文字符通常是方块形,使用连通域分割)
  145. 145● let char_regions = segment_chinese_chars(preprocessed, cfg)
  146. 146 // 3. 生成模板
  147. 147● let templates = generate_chinese_templates(char_set=cfg.char_set)
  148. 148 // 4. 对每个字符进行识别
  149. 149 let char_results : Array[OcrCharResult] = []
  150. 150 let mut text = ""
  151. 151 let mut total_confidence = 0.0
  152. 152 for _tup0 in char_regions {
  153. 153● let (x, y, w, h) = _tup0
  154. 154 // 提取字符图像
  155. 155● let char_img = extract_chinese_char_region(
  156. 156 preprocessed,
  157. 157 x,
  158. 158 y,
  159. 159 w,
  160. 160 h,
  161. 161 cfg.target_size,
  162. 162 )
  163. 163 // 提取特征
  164. 164● let features = extract_chinese_char_features(char_img, 16)
  165. 165 // 模板匹配
  166. 166● let result = match_chinese_template(
  167. 167 features,
  168. 168 templates,
  169. 169 cfg.distance_metric,
  170. 170 )
  171. 171 text += result.0
  172. 172 total_confidence += result.1
  173. 173● char_results.push(OcrCharResult::{
  174. 174 char: result.0,
  175. 175 confidence: result.1,
  176. 176 x,
  177. 177 y,
  178. 178 width: w,
  179. 179 height: h,
  180. 180 })
  181. 181 }
  182. 182● let avg_confidence = if char_results.length() > 0 {
  183. 183● total_confidence / char_results.length().to_double()
  184. 184 } else {
  185. 185● 0.0
  186. 186 }
  187. 187 OcrResult::{ text, confidence: avg_confidence, characters: char_results, }
  188. 188}
  189. 189
  190. 190///|
  191. 191/// 中文字符分割(基于连通域和方块特征)
  192. 192fn segment_chinese_chars(
  193. 193 img : @types.Image,
  194. 194 cfg : ChineseOcrConfig,
  195. 195) -> Array[(Int32, Int32, Int32, Int32)] {
  196. 196● let w = img.width
  197. 197 let h = img.height
  198. 198 let data = img.data
  199. 199 // 简单连通域标记
  200. 200● let labels : Array[Int32] = Array::make(w * h, 0)
  201. 201 let mut next_label = 1
  202. 202 for y in 0..<h {
  203. 203● for x in 0..<w {
  204. 204● if data[y * w + x].to_int() > 128 {
  205. 205● let mut label = 0
  206. 206 if x > 0 && labels[y * w + x - 1] > 0 {
  207. 207● label = labels[y * w + x - 1]
  208. 208 }
  209. 209 if y > 0 && labels[(y - 1) * w + x] > 0 {
  210. 210● if label == 0 {
  211. 211● label = labels[(y - 1) * w + x]
  212. 212 }
  213. 213 }
  214. 214 if label == 0 {
  215. 215● label = next_label
  216. 216 next_label += 1
  217. 217 }
  218. 218 labels[y * w + x] = label
  219. 219 }
  220. 220 }
  221. 221 }
  222. 222 // 计算每个连通域的边界框
  223. 223● let min_x : Array[Int32] = Array::make(next_label, w)
  224. 224● let max_x : Array[Int32] = Array::make(next_label, 0)
  225. 225● let min_y : Array[Int32] = Array::make(next_label, h)
  226. 226● let max_y : Array[Int32] = Array::make(next_label, 0)
  227. 227● let area : Array[Int32] = Array::make(next_label, 0)
  228. 228 for y in 0..<h {
  229. 229● for x in 0..<w {
  230. 230● let label = labels[y * w + x]
  231. 231 if label > 0 {
  232. 232● area[label] += 1
  233. 233 if x < min_x[label] {
  234. 234● min_x[label] = x
  235. 235 }
  236. 236 if x > max_x[label] {
  237. 237● max_x[label] = x
  238. 238 }
  239. 239 if y < min_y[label] {
  240. 240● min_y[label] = y
  241. 241 }
  242. 242 if y > max_y[label] {
  243. 243● max_y[label] = y
  244. 244 }
  245. 245 }
  246. 246 }
  247. 247 }
  248. 248 // 过滤并返回(中文字符通常接近正方形)
  249. 249 let regions : Array[(Int32, Int32, Int32, Int32)] = []
  250. 250 for label in 1..<next_label {
  251. 251● let rw = max_x[label] - min_x[label] + 1
  252. 252 let rh = max_y[label] - min_y[label] + 1
  253. 253 // 中文字符过滤:接近正方形,尺寸在合理范围内
  254. 254◐ let ratio = if rh > 0 { rw.to_double() / rh.to_double() } else { 0.0 }
  255. 255 if rw >= cfg.min_char_width &&
  256. 256 rw <= cfg.max_char_width &&
  257. 257 rh >= cfg.min_char_width &&
  258. 258 rh <= cfg.max_char_width &&
  259. 259 ratio > 0.5 &&
  260. 260 ratio < 2.0 &&
  261. 261 area[label] > 20 {
  262. 262● regions.push((min_x[label], min_y[label], rw, rh))
  263. 263 }
  264. 264 }
  265. 265 regions
  266. 266}
  267. 267
  268. 268///|
  269. 269/// 提取中文字符区域
  270. 270fn extract_chinese_char_region(
  271. 271 img : @types.Image,
  272. 272 x : Int32,
  273. 273 y : Int32,
  274. 274 width : Int32,
  275. 275 height : Int32,
  276. 276 target_size : Int32,
  277. 277) -> @types.Image {
  278. 278● let w = img.width
  279. 279 let h = img.height
  280. 280● let crop_w = if x + width > w { w - x } else { width }
  281. 281● let crop_h = if y + height > h { h - y } else { height }
  282. 282 if crop_w <= 0 || crop_h <= 0 {
  283. 283● let empty : Array[Byte] = Array::make(target_size * target_size, b'\x00')
  284. 284 return @types.Image::{
  285. 285 width: target_size,
  286. 286 height: target_size,
  287. 287 channels: 1,
  288. 288● data: Bytes::from_array(empty),
  289. 289 }
  290. 290 }
  291. 291 // 缩放到目标尺寸(中文字符保持正方形)
  292. 292● let out : Array[Byte] = Array::make(target_size * target_size, b'\x00')
  293. 293 let data = img.data
  294. 294 for py in 0..<target_size {
  295. 295● for px in 0..<target_size {
  296. 296● let src_x = x + px * crop_w / target_size
  297. 297 let src_y = y + py * crop_h / target_size
  298. 298 if src_x < w && src_y < h {
  299. 299● out[py * target_size + px] = data[src_y * w + src_x]
  300. 300 }
  301. 301 }
  302. 302 }
  303. 303 @types.Image::{
  304. 304 width: target_size,
  305. 305 height: target_size,
  306. 306 channels: 1,
  307. 307● data: Bytes::from_array(out),
  308. 308 }
  309. 309}
  310. 310
  311. 311///|
  312. 312/// 提取中文字符特征(16x16网格特征)
  313. 313fn extract_chinese_char_features(
  314. 314 char_img : @types.Image,
  315. 315 grid_size : Int32,
  316. 316) -> Array[Double] {
  317. 317● let w = char_img.width
  318. 318 let h = char_img.height
  319. 319 let data = char_img.data
  320. 320 let cell_w = w / grid_size
  321. 321 let cell_h = h / grid_size
  322. 322 let features : Array[Double] = []
  323. 323 for r in 0..<grid_size {
  324. 324● for c in 0..<grid_size {
  325. 325● let mut count = 0
  326. 326 let mut total = 0
  327. 327 for py in 0..<cell_h {
  328. 328● for px in 0..<cell_w {
  329. 329● let sx = c * cell_w + px
  330. 330 let sy = r * cell_h + py
  331. 331 if sx < w && sy < h {
  332. 332● total += 1
  333. 333● if data[sy * w + sx].to_int() > 128 {
  334. 334● count += 1
  335. 335 }
  336. 336 }
  337. 337 }
  338. 338 }
  339. 339 let density = if total > 0 {
  340. 340● count.to_double() / total.to_double()
  341. 341 } else {
  342. 342● 0.0
  343. 343 }
  344. 344● features.push(density)
  345. 345 }
  346. 346 }
  347. 347 features
  348. 348}
  349. 349
  350. 350///|
  351. 351/// 中文模板匹配
  352. 352fn match_chinese_template(
  353. 353 features : Array[Double],
  354. 354 templates : Array[(String, Array[Double])],
  355. 355 distance_metric : String,
  356. 356) -> (String, Double) {
  357. 357● let mut best_label = "?"
  358. 358 let mut best_dist = 1000000.0
  359. 359 for _tup1 in templates {
  360. 360● let (label, template) = _tup1
  361. 361● let dist = match distance_metric {
  362. 362● "manhattan" => manhattan_distance_chi(features, template)
  363. 363● "cosine" => cosine_distance_chi(features, template)
  364. 364● _ => euclidean_distance_chi(features, template)
  365. 365 }
  366. 366 if dist < best_dist {
  367. 367● best_dist = dist
  368. 368 best_label = label
  369. 369 }
  370. 370 }
  371. 371● let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 }
  372. 372 (best_label, confidence)
  373. 373}
  374. 374
  375. 375///|
  376. 376/// 局部欧氏距离
  377. 377fn euclidean_distance_chi(a : Array[Double], b : Array[Double]) -> Double {
  378. 378◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  379. 379 let mut sum_sq = 0.0
  380. 380 for i in 0..<n {
  381. 381● let diff = a[i] - b[i]
  382. 382 sum_sq += diff * diff
  383. 383 }
  384. 384● sum_sq.sqrt()
  385. 385}
  386. 386
  387. 387///|
  388. 388/// 局部曼哈顿距离
  389. 389fn manhattan_distance_chi(a : Array[Double], b : Array[Double]) -> Double {
  390. 390◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  391. 391 let mut sum = 0.0
  392. 392 for i in 0..<n {
  393. 393● sum += (a[i] - b[i]).abs()
  394. 394 }
  395. 395 sum
  396. 396}
  397. 397
  398. 398///|
  399. 399/// 局部余弦距离
  400. 400fn cosine_distance_chi(a : Array[Double], b : Array[Double]) -> Double {
  401. 401◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  402. 402 let mut dot = 0.0
  403. 403 let mut norm_a = 0.0
  404. 404 let mut norm_b = 0.0
  405. 405 for i in 0..<n {
  406. 406● dot += a[i] * b[i]
  407. 407 norm_a += a[i] * a[i]
  408. 408 norm_b += b[i] * b[i]
  409. 409 }
  410. 410● let denom = norm_a.sqrt() * norm_b.sqrt()
  411. 411 if denom > 0.0 {
  412. 412● 1.0 - dot / denom
  413. 413 } else {
  414. 414○ 1.0
  415. 415 }
  416. 416}