image.vision\ocr\handwriting_ocr.mbt

94.1% · 159 / 169 points · 553 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/handwriting_ocr
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 手写体识别
  7. 7// 手写体专用模板、灵活的字符分割、手写体识别流水线
  8. 8
  9. 9///|
  10. 10/// 手写体识别配置
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct HandwritingOcrConfig {
  13. 13 min_char_width : Int32
  14. 14 max_char_width : Int32
  15. 15 min_char_height : Int32
  16. 16 max_char_height : Int32
  17. 17 target_size : Int32
  18. 18 distance_metric : String
  19. 19 flexibility : Double // 0.0-1.0,越高越灵活
  20. 20 use_slant_correction : Bool
  21. 21}
  22. 22
  23. 23///|
  24. 24pub extend HandwritingOcrConfig with Eq::{not_equal, equal}
  25. 25
  26. 26///|
  27. 27pub extend HandwritingOcrConfig with @debug.Debug::{to_repr}
  28. 28
  29. 29///|
  30. 30/// 创建默认手写体识别配置
  31. 31pub fn handwriting_ocr_default_config() -> HandwritingOcrConfig {
  32. 32● HandwritingOcrConfig::{
  33. 33 min_char_width: 8,
  34. 34 max_char_width: 80,
  35. 35 min_char_height: 10,
  36. 36 max_char_height: 100,
  37. 37 target_size: 48,
  38. 38 distance_metric: "euclidean",
  39. 39 flexibility: 0.7,
  40. 40 use_slant_correction: true,
  41. 41 }
  42. 42}
  43. 43
  44. 44///|
  45. 45/// 生成手写体数字模板(更灵活的形状)
  46. 46pub fn generate_handwriting_templates(
  47. 47 char_set~ : String = "digits",
  48. 48) -> Array[(String, Array[Double])] {
  49. 49● let templates : Array[(String, Array[Double])] = []
  50. 50 let chars = if char_set == "digits+letters" {
  51. 51● [
  52. 52 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E",
  53. 53 "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
  54. 54 "U", "V", "W", "X", "Y", "Z",
  55. 55 ]
  56. 56 } else {
  57. 57● ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
  58. 58 }
  59. 59 for char in chars {
  60. 60 // 生成多个变体(手写体有多种写法)
  61. 61● for variant in 0..<3 {
  62. 62● let template = generate_handwriting_char_template(char, variant)
  63. 63● let label = char + "_v" + variant.to_string()
  64. 64● templates.push((label, template))
  65. 65 }
  66. 66 }
  67. 67 templates
  68. 68}
  69. 69
  70. 70///|
  71. 71/// 生成手写体字符模板(带变体)
  72. 72fn generate_handwriting_char_template(
  73. 73 char : String,
  74. 74 variant : Int32,
  75. 75) -> Array[Double] {
  76. 76● let size = 16
  77. 77● let features : Array[Double] = Array::make(size * size, 0.0)
  78. 78● let seed = if char.length() > 0 {
  79. 79● char[0].to_int() + variant * 100
  80. 80 } else {
  81. 81○ 0
  82. 82 }
  83. 83 // 手写体特征:更随机、更灵活的形状
  84. 84 for y in 0..<size {
  85. 85● for x in 0..<size {
  86. 86 // 基础哈希
  87. 87● let h1 = (seed * 31 + x * 17 + y * 13) % 100
  88. 88 // 变体哈希
  89. 89 let h2 = (seed * 7 + (x + variant * 3) * 11 + (y + variant * 2) * 19) %
  90. 90 100
  91. 91 // 中心权重(手写体通常居中但有偏移)
  92. 92 let center_x = 8 + (variant - 1) * 2
  93. 93 let center_y = 8 + variant % 2 * 2
  94. 94 let center_dist = ((x - center_x) * (x - center_x) +
  95. 95● (y - center_y) * (y - center_y)).to_double()
  96. 96 let center_factor = 1.0 - center_dist / 128.0
  97. 97 // 手写体灵活性:更宽松的阈值
  98. 98● let threshold = 35 + (center_factor * 30.0).to_int() + h2 / 5
  99. 99 if h1 < threshold {
  100. 100● features[y * size + x] = 1.0
  101. 101 }
  102. 102 }
  103. 103 }
  104. 104 features
  105. 105}
  106. 106
  107. 107///|
  108. 108/// 倾斜校正(手写体专用)
  109. 109pub fn correct_slant(
  110. 110 img : @types.Image,
  111. 111 max_slant~ : Double = 15.0,
  112. 112) -> @types.Image raise @types.LoadError {
  113. 113● ignore(max_slant)
  114. 114 // 输入验证
  115. 115 if img.width <= 0 || img.height <= 0 {
  116. 116● raise @types.LoadError::DecodeFailed(
  117. 117 "correct_slant: 图像尺寸必须大于0",
  118. 118 )
  119. 119 }
  120. 120 if img.channels != 1 {
  121. 121● raise @types.LoadError::DecodeFailed(
  122. 122 "correct_slant: 仅支持单通道灰度图",
  123. 123 )
  124. 124 }
  125. 125 let expected_size = img.width * img.height
  126. 126● if img.data.length() != expected_size {
  127. 127● raise @types.LoadError::DecodeFailed(
  128. 128 "correct_slant: 数据大小不匹配,期望 " +
  129. 129● expected_size.to_string() +
  130. 130 ",实际 " +
  131. 131● img.data.length().to_string(),
  132. 132 )
  133. 133 }
  134. 134
  135. 135 // 简化版:检测主要倾斜角度并校正
  136. 136● let angle = estimate_slant_angle(img)
  137. 137● if angle.abs() > 1.0 {
  138. 138● rotate_document(img, -angle)
  139. 139 } else {
  140. 140● img
  141. 141 }
  142. 142}
  143. 143
  144. 144///|
  145. 145/// 估计倾斜角度(手写体专用)
  146. 146fn estimate_slant_angle(img : @types.Image) -> Double {
  147. 147● let w = img.width
  148. 148 let h = img.height
  149. 149 let data = img.data
  150. 150 // 简化:基于垂直投影的倾斜估计
  151. 151 let mut best_angle = 0.0
  152. 152 let mut best_score = 0.0
  153. 153 let mut angle = -15.0
  154. 154 while angle <= 15.0 {
  155. 155● let angle_rad = angle * 3.141592653589793 / 180.0
  156. 156● let cos_a = @math.cos(angle_rad)
  157. 157● let sin_a = @math.sin(angle_rad)
  158. 158 // 计算旋转后的垂直投影方差
  159. 159● let projection : Array[Int32] = Array::make(w, 0)
  160. 160 for y in 0..<h {
  161. 161● for x in 0..<w {
  162. 162● if data[y * w + x].to_int() > 128 {
  163. 163● let new_x = ((x.to_double() - w.to_double() / 2.0) * cos_a -
  164. 164● (y.to_double() - h.to_double() / 2.0) * sin_a +
  165. 165● w.to_double() / 2.0).to_int()
  166. 166 if new_x >= 0 && new_x < w {
  167. 167● projection[new_x] += 1
  168. 168 }
  169. 169 }
  170. 170 }
  171. 171 }
  172. 172 // 计算方差
  173. 173 let mut sum = 0
  174. 174 let mut sum_sq = 0
  175. 175 for i in 0..<w {
  176. 176● sum += projection[i]
  177. 177 sum_sq += projection[i] * projection[i]
  178. 178 }
  179. 179● let mean = sum.to_double() / w.to_double()
  180. 180● let variance = sum_sq.to_double() / w.to_double() - mean * mean
  181. 181 if variance > best_score {
  182. 182● best_score = variance
  183. 183 best_angle = angle
  184. 184 }
  185. 185 angle += 1.0
  186. 186 }
  187. 187 best_angle
  188. 188}
  189. 189
  190. 190///|
  191. 191/// 手写体字符分割(更宽松的参数)
  192. 192fn segment_handwriting_chars(
  193. 193 img : @types.Image,
  194. 194 cfg : HandwritingOcrConfig,
  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 let min_ratio = 0.3 * (1.0 + cfg.flexibility)
  256. 256 let max_ratio = 3.0 * (1.0 + cfg.flexibility)
  257. 257 if rw >= cfg.min_char_width &&
  258. 258 rw <= cfg.max_char_width &&
  259. 259 rh >= cfg.min_char_height &&
  260. 260 rh <= cfg.max_char_height &&
  261. 261 ratio > min_ratio &&
  262. 262 ratio < max_ratio &&
  263. 263 area[label] > 15 {
  264. 264● regions.push((min_x[label], min_y[label], rw, rh))
  265. 265 }
  266. 266 }
  267. 267 regions
  268. 268}
  269. 269
  270. 270///|
  271. 271/// 手写体识别(完整流水线)
  272. 272/// @deprecated 已废弃,请使用 recognize_handwriting_enhanced 代替
  273. 273#deprecated("Use recognize_handwriting_enhanced instead", skip_current_package=true)
  274. 274pub fn recognize_handwriting(
  275. 275 img : @types.Image,
  276. 276 config? : HandwritingOcrConfig,
  277. 277) -> OcrResult raise @types.LoadError {
  278. 278 // 输入验证
  279. 279 if img.width <= 0 || img.height <= 0 {
  280. 280 raise @types.LoadError::DecodeFailed(
  281. 281 "recognize_handwriting: 图像尺寸必须大于0",
  282. 282 )
  283. 283 }
  284. 284 if img.channels < 1 || img.channels > 4 {
  285. 285 raise @types.LoadError::DecodeFailed(
  286. 286 "recognize_handwriting: 通道数必须在1-4之间",
  287. 287 )
  288. 288 }
  289. 289 let expected_size = img.width * img.height * img.channels
  290. 290 if img.data.length() != expected_size {
  291. 291 raise @types.LoadError::DecodeFailed(
  292. 292 "recognize_handwriting: 数据大小不匹配,期望 " +
  293. 293 expected_size.to_string() +
  294. 294 ",实际 " +
  295. 295 img.data.length().to_string(),
  296. 296 )
  297. 297 }
  298. 298
  299. 299 let cfg = match config {
  300. 300 Some(c) => c
  301. 301 None => handwriting_ocr_default_config()
  302. 302 }
  303. 303 // 配置验证
  304. 304 if cfg.min_char_width <= 0 {
  305. 305 raise @types.LoadError::DecodeFailed(
  306. 306 "recognize_handwriting: min_char_width必须大于0",
  307. 307 )
  308. 308 }
  309. 309 if cfg.max_char_width < cfg.min_char_width {
  310. 310 raise @types.LoadError::DecodeFailed(
  311. 311 "recognize_handwriting: max_char_width不能小于min_char_width",
  312. 312 )
  313. 313 }
  314. 314 if cfg.target_size <= 0 {
  315. 315 raise @types.LoadError::DecodeFailed(
  316. 316 "recognize_handwriting: target_size必须大于0",
  317. 317 )
  318. 318 }
  319. 319 // 1. 预处理
  320. 320 let mut preprocessed = ocr_preprocess(img)
  321. 321 // 2. 倾斜校正(手写体专用)
  322. 322 if cfg.use_slant_correction {
  323. 323 preprocessed = correct_slant(preprocessed)
  324. 324 }
  325. 325 // 3. 字符分割(手写体更宽松)
  326. 326 let char_regions = segment_handwriting_chars(preprocessed, cfg)
  327. 327 // 4. 生成手写体模板
  328. 328 let templates = generate_handwriting_templates(char_set="digits")
  329. 329 // 5. 对每个字符进行识别
  330. 330 let char_results : Array[OcrCharResult] = []
  331. 331 let mut text = ""
  332. 332 let mut total_confidence = 0.0
  333. 333 for _tup0 in char_regions {
  334. 334 let (x, y, w, h) = _tup0
  335. 335 // 提取字符图像
  336. 336 let char_img = extract_handwriting_char_region(
  337. 337 preprocessed,
  338. 338 x,
  339. 339 y,
  340. 340 w,
  341. 341 h,
  342. 342 cfg.target_size,
  343. 343 )
  344. 344 // 提取特征
  345. 345 let features = extract_handwriting_char_features(char_img, 16)
  346. 346 // 模板匹配(多变体投票)
  347. 347 let result = match_handwriting_template(
  348. 348 features,
  349. 349 templates,
  350. 350 cfg.distance_metric,
  351. 351 )
  352. 352 text += result.0
  353. 353 total_confidence += result.1
  354. 354 char_results.push(OcrCharResult::{
  355. 355 char: result.0,
  356. 356 confidence: result.1,
  357. 357 x,
  358. 358 y,
  359. 359 width: w,
  360. 360 height: h,
  361. 361 })
  362. 362 }
  363. 363 let avg_confidence = if char_results.length() > 0 {
  364. 364 total_confidence / char_results.length().to_double()
  365. 365 } else {
  366. 366 0.0
  367. 367 }
  368. 368 OcrResult::{ text, confidence: avg_confidence, characters: char_results, }
  369. 369}
  370. 370
  371. 371///|
  372. 372/// 提取手写体字符区域
  373. 373fn extract_handwriting_char_region(
  374. 374 img : @types.Image,
  375. 375 x : Int32,
  376. 376 y : Int32,
  377. 377 width : Int32,
  378. 378 height : Int32,
  379. 379 target_size : Int32,
  380. 380) -> @types.Image {
  381. 381● let w = img.width
  382. 382 let h = img.height
  383. 383● let crop_w = if x + width > w { w - x } else { width }
  384. 384● let crop_h = if y + height > h { h - y } else { height }
  385. 385 if crop_w <= 0 || crop_h <= 0 {
  386. 386● let empty : Array[Byte] = Array::make(target_size * target_size, b'\x00')
  387. 387 return @types.Image::{
  388. 388 width: target_size,
  389. 389 height: target_size,
  390. 390 channels: 1,
  391. 391● data: Bytes::from_array(empty),
  392. 392 }
  393. 393 }
  394. 394● let out : Array[Byte] = Array::make(target_size * target_size, b'\x00')
  395. 395 let data = img.data
  396. 396 for py in 0..<target_size {
  397. 397● for px in 0..<target_size {
  398. 398● let src_x = x + px * crop_w / target_size
  399. 399 let src_y = y + py * crop_h / target_size
  400. 400 if src_x < w && src_y < h {
  401. 401● out[py * target_size + px] = data[src_y * w + src_x]
  402. 402 }
  403. 403 }
  404. 404 }
  405. 405 @types.Image::{
  406. 406 width: target_size,
  407. 407 height: target_size,
  408. 408 channels: 1,
  409. 409● data: Bytes::from_array(out),
  410. 410 }
  411. 411}
  412. 412
  413. 413///|
  414. 414/// 提取手写体字符特征
  415. 415fn extract_handwriting_char_features(
  416. 416 char_img : @types.Image,
  417. 417 grid_size : Int32,
  418. 418) -> Array[Double] {
  419. 419● let w = char_img.width
  420. 420 let h = char_img.height
  421. 421 let data = char_img.data
  422. 422 let cell_w = w / grid_size
  423. 423 let cell_h = h / grid_size
  424. 424 let features : Array[Double] = []
  425. 425 for r in 0..<grid_size {
  426. 426● for c in 0..<grid_size {
  427. 427● let mut count = 0
  428. 428 let mut total = 0
  429. 429 for py in 0..<cell_h {
  430. 430● for px in 0..<cell_w {
  431. 431● let sx = c * cell_w + px
  432. 432 let sy = r * cell_h + py
  433. 433 if sx < w && sy < h {
  434. 434● total += 1
  435. 435● if data[sy * w + sx].to_int() > 128 {
  436. 436● count += 1
  437. 437 }
  438. 438 }
  439. 439 }
  440. 440 }
  441. 441 let density = if total > 0 {
  442. 442● count.to_double() / total.to_double()
  443. 443 } else {
  444. 444● 0.0
  445. 445 }
  446. 446● features.push(density)
  447. 447 }
  448. 448 }
  449. 449 features
  450. 450}
  451. 451
  452. 452///|
  453. 453/// 手写体模板匹配(多变体投票)
  454. 454fn match_handwriting_template(
  455. 455 features : Array[Double],
  456. 456 templates : Array[(String, Array[Double])],
  457. 457 distance_metric : String,
  458. 458) -> (String, Double) {
  459. 459 // 收集所有变体的预测
  460. 460● let label_votes : Array[(String, Double)] = []
  461. 461 for _tup1 in templates {
  462. 462● let (label_full, template) = _tup1
  463. 463● let dist = match distance_metric {
  464. 464● "manhattan" => manhattan_hw(features, template)
  465. 465● "cosine" => cosine_hw(features, template)
  466. 466● _ => euclidean_hw(features, template)
  467. 467 }
  468. 468 // 取第一个码点作为基础标签(数字 0-9),按字符还原而不是码点数字
  469. 469● let base_label = if label_full.length() > 0 {
  470. 470● hw_char_str(label_full[0])
  471. 471 } else {
  472. 472○ label_full
  473. 473 }
  474. 474● let confidence = if dist > 0.0 { 1.0 / (1.0 + dist) } else { 1.0 }
  475. 475 // 投票
  476. 476 let mut found = false
  477. 477● for i in 0..<label_votes.length() {
  478. 478● if label_votes[i].0 == base_label {
  479. 479● label_votes[i] = (base_label, label_votes[i].1 + confidence)
  480. 480 found = true
  481. 481 }
  482. 482 }
  483. 483 if !found {
  484. 484● label_votes.push((base_label, confidence))
  485. 485 }
  486. 486 }
  487. 487 // 找得票最多的标签
  488. 488 let mut best_label = "?"
  489. 489 let mut best_votes = 0.0
  490. 490 for _tup2 in label_votes {
  491. 491● let (label, votes) = _tup2
  492. 492 if votes > best_votes {
  493. 493● best_votes = votes
  494. 494 best_label = label
  495. 495 }
  496. 496 }
  497. 497● let total_votes = if templates.length() > 0 {
  498. 498● templates.length().to_double() / 3.0
  499. 499 } else {
  500. 500● 1.0
  501. 501 }
  502. 502 let confidence = best_votes / total_votes
  503. 503 (best_label, confidence)
  504. 504}
  505. 505
  506. 506///|
  507. 507/// 把字符串索引(码点 UInt16)还原成单字符字符串
  508. 508fn hw_char_str(raw : UInt16) -> String {
  509. 509● raw.to_int().to_char().map(c => c.to_string()).unwrap_or("")
  510. 510}
  511. 511
  512. 512///|
  513. 513/// 局部欧氏距离
  514. 514fn euclidean_hw(a : Array[Double], b : Array[Double]) -> Double {
  515. 515◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  516. 516 let mut sum_sq = 0.0
  517. 517 for i in 0..<n {
  518. 518● let diff = a[i] - b[i]
  519. 519 sum_sq += diff * diff
  520. 520 }
  521. 521● sum_sq.sqrt()
  522. 522}
  523. 523
  524. 524///|
  525. 525/// 局部曼哈顿距离
  526. 526fn manhattan_hw(a : Array[Double], b : Array[Double]) -> Double {
  527. 527◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  528. 528 let mut sum = 0.0
  529. 529 for i in 0..<n {
  530. 530● sum += (a[i] - b[i]).abs()
  531. 531 }
  532. 532 sum
  533. 533}
  534. 534
  535. 535///|
  536. 536/// 局部余弦距离
  537. 537fn cosine_hw(a : Array[Double], b : Array[Double]) -> Double {
  538. 538◐ let n = if a.length() < b.length() { a.length() } else { b.length() }
  539. 539 let mut dot = 0.0
  540. 540 let mut norm_a = 0.0
  541. 541 let mut norm_b = 0.0
  542. 542 for i in 0..<n {
  543. 543● dot += a[i] * b[i]
  544. 544 norm_a += a[i] * a[i]
  545. 545 norm_b += b[i] * b[i]
  546. 546 }
  547. 547● let denom = norm_a.sqrt() * norm_b.sqrt()
  548. 548 if denom > 0.0 {
  549. 549● 1.0 - dot / denom
  550. 550 } else {
  551. 551○ 1.0
  552. 552 }
  553. 553}