image.vision\ocr\handwriting_ocr_enhanced.mbt

89.5% · 221 / 247 points · 742 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_enhanced
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 手写体识别增强版(v10.3.0)
  7. 7// 更多变体、弹性匹配、连笔分割、手写体专用特征、手写体后处理
  8. 8
  9. 9///|
  10. 10/// 增强手写体识别配置
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct HandwritingOcrEnhancedConfig {
  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 num_variants : Int32 // 每字符变体数量
  20. 20 elasticity : Double // 弹性匹配程度 0.0-1.0
  21. 21 use_slant_correction : Bool
  22. 22 use_elastic_matching : Bool
  23. 23 use_stroke_features : Bool
  24. 24 use_postprocessing : Bool
  25. 25}
  26. 26
  27. 27///|
  28. 28pub extend HandwritingOcrEnhancedConfig with Eq::{not_equal, equal}
  29. 29
  30. 30///|
  31. 31pub extend HandwritingOcrEnhancedConfig with @debug.Debug::{to_repr}
  32. 32
  33. 33///|
  34. 34/// 创建默认增强手写体识别配置
  35. 35pub fn handwriting_ocr_enhanced_default_config() -> HandwritingOcrEnhancedConfig {
  36. 36● HandwritingOcrEnhancedConfig::{
  37. 37 min_char_width: 8,
  38. 38 max_char_width: 80,
  39. 39 min_char_height: 10,
  40. 40 max_char_height: 100,
  41. 41 target_size: 48,
  42. 42 distance_metric: "euclidean",
  43. 43 num_variants: 5,
  44. 44 elasticity: 0.5,
  45. 45 use_slant_correction: true,
  46. 46 use_elastic_matching: true,
  47. 47 use_stroke_features: true,
  48. 48 use_postprocessing: true,
  49. 49 }
  50. 50}
  51. 51
  52. 52///|
  53. 53/// 手写体笔画特征
  54. 54#derive(Eq, @debug.Debug)
  55. 55pub(all) struct HandwritingStrokeFeatures {
  56. 56 num_strokes : Int32 // 估计笔画数
  57. 57 stroke_directions : Array[Double] // 主要笔画方向(弧度)
  58. 58 stroke_lengths : Array[Double] // 笔画长度
  59. 59 connectivity : Double // 连通性(连笔程度)
  60. 60 curvature : Double // 曲率(弯曲程度)
  61. 61}
  62. 62
  63. 63///|
  64. 64pub extend HandwritingStrokeFeatures with Eq::{not_equal, equal}
  65. 65
  66. 66///|
  67. 67pub extend HandwritingStrokeFeatures with @debug.Debug::{to_repr}
  68. 68
  69. 69///|
  70. 70/// 生成增强手写体模板(每字符5种变体)
  71. 71pub fn generate_enhanced_handwriting_templates(
  72. 72 char_set~ : String = "digits+letters",
  73. 73 num_variants~ : Int32 = 5,
  74. 74) -> Array[(String, Array[Double])] {
  75. 75● let templates : Array[(String, Array[Double])] = []
  76. 76 let chars = if char_set == "digits" {
  77. 77● ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
  78. 78 } else {
  79. 79● [
  80. 80 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E",
  81. 81 "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
  82. 82 "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i",
  83. 83 "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
  84. 84 "y", "z",
  85. 85 ]
  86. 86 }
  87. 87 for char in chars {
  88. 88● for variant in 0..<num_variants {
  89. 89● let template = generate_enhanced_handwriting_char_template(
  90. 90 char, variant, num_variants,
  91. 91 )
  92. 92● let label = char + "_v" + variant.to_string()
  93. 93● templates.push((label, template))
  94. 94 }
  95. 95 }
  96. 96 templates
  97. 97}
  98. 98
  99. 99///|
  100. 100/// 生成增强手写体字符模板(带弹性变形)
  101. 101fn generate_enhanced_handwriting_char_template(
  102. 102 char : String,
  103. 103 variant : Int32,
  104. 104 num_variants : Int32,
  105. 105) -> Array[Double] {
  106. 106● let size = 32
  107. 107● let features : Array[Double] = Array::make(size * size, 0.0)
  108. 108● let seed = if char.length() > 0 {
  109. 109● char[0].to_int() + variant * 137
  110. 110 } else {
  111. 111○ 0
  112. 112 }
  113. 113 // 变体参数(每个变体有不同的倾斜、宽度、位置)
  114. 114● let slant = ((variant - num_variants / 2) * 3).to_double() // 倾斜角度
  115. 115● let width_scale = 0.85 + (variant % 3).to_double() * 0.1 // 宽度缩放
  116. 116 let y_offset = variant % 2 * 2 - 1 // 垂直偏移
  117. 117● let center_x = (size.to_double() / 2.0 * width_scale).to_int()
  118. 118 let center_y = size / 2 + y_offset
  119. 119 for y in 0..<size {
  120. 120● for x in 0..<size {
  121. 121 // 应用倾斜变换
  122. 122● let slant_rad = slant * 3.141592653589793 / 180.0
  123. 123● let transformed_x = x.to_double() -
  124. 124● center_x.to_double() -
  125. 125● (y.to_double() - center_y.to_double()) * @math.tan(slant_rad) +
  126. 126● center_x.to_double()
  127. 127● let tx = transformed_x.to_int()
  128. 128 // 多层哈希
  129. 129 let h1 = (seed * 31 + tx * 17 + y * 13) % 100
  130. 130 let h2 = (seed * 7 + tx * tx * 3 + y * y * 5) % 100
  131. 131 let h3 = ((seed << 2) ^ (tx << 1) ^ y) % 100
  132. 132 let combined = (h1 * 4 + h2 * 3 + h3 * 2) / 9
  133. 133 // 中心权重(手写体通常居中但有偏移)
  134. 134 let center_dist = ((tx - center_x) * (tx - center_x) +
  135. 135● (y - center_y) * (y - center_y)).to_double()
  136. 136 let center_factor = 1.0 -
  137. 137● center_dist / (size.to_double() * size.to_double() / 2.5)
  138. 138 // 弹性变形(边缘更模糊)
  139. 139 let edge_factor = if tx < 2 || tx >= size - 2 || y < 2 || y >= size - 2 {
  140. 140● 0.6
  141. 141 } else {
  142. 142● 1.0
  143. 143 }
  144. 144● let threshold = (30.0 + center_factor * 25.0 + edge_factor * 10.0).to_int()
  145. 145 if combined < threshold && tx >= 0 && tx < size {
  146. 146● features[y * size + x] = 1.0
  147. 147 }
  148. 148 }
  149. 149 }
  150. 150 features
  151. 151}
  152. 152
  153. 153///|
  154. 154/// 提取手写体笔画特征
  155. 155pub fn extract_handwriting_stroke_features(
  156. 156 char_img : @types.Image,
  157. 157) -> HandwritingStrokeFeatures raise @types.LoadError {
  158. 158 // 输入验证
  159. 159● if char_img.width <= 0 || char_img.height <= 0 {
  160. 160● raise @types.LoadError::DecodeFailed(
  161. 161 "extract_handwriting_stroke_features: 图像尺寸必须大于0",
  162. 162 )
  163. 163 }
  164. 164 if char_img.channels != 1 {
  165. 165● raise @types.LoadError::DecodeFailed(
  166. 166 "extract_handwriting_stroke_features: 仅支持单通道灰度图",
  167. 167 )
  168. 168 }
  169. 169 let expected_size = char_img.width * char_img.height
  170. 170● if char_img.data.length() != expected_size {
  171. 171● raise @types.LoadError::DecodeFailed(
  172. 172 "extract_handwriting_stroke_features: 数据大小不匹配,期望 " +
  173. 173● expected_size.to_string() +
  174. 174 ",实际 " +
  175. 175● char_img.data.length().to_string(),
  176. 176 )
  177. 177 }
  178. 178 let w = char_img.width
  179. 179 let h = char_img.height
  180. 180 let data = char_img.data
  181. 181 // 估计笔画数(基于连通域数量)
  182. 182● let labels : Array[Int32] = Array::make(w * h, 0)
  183. 183 let mut num_components = 0
  184. 184 for y in 0..<h {
  185. 185● for x in 0..<w {
  186. 186● if data[y * w + x].to_int() > 128 && labels[y * w + x] == 0 {
  187. 187● num_components += 1
  188. 188 // 简单洪水填充
  189. 189 let stack : Array[(Int32, Int32)] = []
  190. 190● stack.push((x, y))
  191. 191 labels[y * w + x] = num_components
  192. 192● while stack.length() > 0 {
  193. 193● match stack.pop() {
  194. 194● Some((cx, cy)) => {
  195. 195 let neighbors = [
  196. 196 (cx + 1, cy),
  197. 197 (cx - 1, cy),
  198. 198 (cx, cy + 1),
  199. 199 (cx, cy - 1),
  200. 200 ]
  201. 201 for _tup0 in neighbors {
  202. 202● let (nx, ny) = _tup0
  203. 203 if nx >= 0 &&
  204. 204 nx < w &&
  205. 205 ny >= 0 &&
  206. 206 ny < h &&
  207. 207● data[ny * w + nx].to_int() > 128 &&
  208. 208 labels[ny * w + nx] == 0 {
  209. 209● labels[ny * w + nx] = num_components
  210. 210● stack.push((nx, ny))
  211. 211 }
  212. 212 }
  213. 213 }
  214. 214○ None => ignore(())
  215. 215 }
  216. 216 }
  217. 217 }
  218. 218 }
  219. 219 }
  220. 220 // 计算主要笔画方向(基于梯度方向直方图)
  221. 221 let directions : Array[Double] = []
  222. 222 let mut total_grad = 0.0
  223. 223● ignore(total_grad)
  224. 224 for y in 1..<(h - 1) {
  225. 225● for x in 1..<(w - 1) {
  226. 226● if data[y * w + x].to_int() > 128 {
  227. 227● let gx = data[y * w + x + 1].to_int().to_double() -
  228. 228● data[y * w + x - 1].to_int().to_double()
  229. 229● let gy = data[(y + 1) * w + x].to_int().to_double() -
  230. 230● data[(y - 1) * w + x].to_int().to_double()
  231. 231● let grad = (gx * gx + gy * gy).sqrt()
  232. 232 if grad > 10.0 {
  233. 233● let angle = @math.atan2(gy, gx)
  234. 234● directions.push(angle)
  235. 235 total_grad += grad
  236. 236 }
  237. 237 }
  238. 238 }
  239. 239 }
  240. 240 // 计算连通性(连笔程度)
  241. 241 let mut ink_pixels = 0
  242. 242 for i in 0..<(w * h) {
  243. 243● if data[i].to_int() > 128 {
  244. 244● ink_pixels += 1
  245. 245 }
  246. 246 }
  247. 247 let connectivity = if num_components > 0 {
  248. 248● ink_pixels.to_double() / (num_components.to_double() * 50.0)
  249. 249 } else {
  250. 250● 0.0
  251. 251 }
  252. 252 // 计算曲率(基于方向变化)
  253. 253 let mut curvature = 0.0
  254. 254● if directions.length() > 10 {
  255. 255● let mut prev_angle = directions[0]
  256. 256● for i in 1..<directions.length() {
  257. 257● let diff = (directions[i] - prev_angle).abs()
  258. 258 curvature += if diff > 3.141592653589793 {
  259. 259● 6.283185307179586 - diff
  260. 260 } else {
  261. 261● diff
  262. 262 }
  263. 263 prev_angle = directions[i]
  264. 264 }
  265. 265● curvature = curvature / directions.length().to_double()
  266. 266 }
  267. 267 HandwritingStrokeFeatures::{
  268. 268 num_strokes: num_components,
  269. 269 stroke_directions: directions,
  270. 270 stroke_lengths: [],
  271. 271● connectivity: connectivity.min(1.0),
  272. 272 curvature,
  273. 273 }
  274. 274}
  275. 275
  276. 276///|
  277. 277/// 弹性匹配(允许形状变形的模板匹配)
  278. 278pub fn elastic_match(
  279. 279 features : Array[Double],
  280. 280 template : Array[Double],
  281. 281 elasticity~ : Double = 0.5,
  282. 282 grid_size~ : Int32 = 16,
  283. 283) -> Double {
  284. 284● let n = if features.length() < template.length() {
  285. 285● features.length()
  286. 286 } else {
  287. 287● template.length()
  288. 288 }
  289. 289 // 基础距离
  290. 290 let mut base_dist = 0.0
  291. 291 for i in 0..<n {
  292. 292● let diff = features[i] - template[i]
  293. 293 base_dist += diff * diff
  294. 294 }
  295. 295● base_dist = base_dist.sqrt()
  296. 296 // 弹性变形补偿(计算局部相似度)
  297. 297 let cell = n / grid_size
  298. 298 let mut local_similarity = 0.0
  299. 299 for block in 0..<grid_size {
  300. 300● let start = block * cell
  301. 301● let end = if start + cell < n { start + cell } else { n }
  302. 302 let mut block_dist = 0.0
  303. 303 for i in start..<end {
  304. 304● let diff = features[i] - template[i]
  305. 305 block_dist += diff * diff
  306. 306 }
  307. 307● block_dist = block_dist.sqrt()
  308. 308 local_similarity += 1.0 / (1.0 + block_dist)
  309. 309 }
  310. 310● local_similarity = local_similarity / grid_size.to_double()
  311. 311 // 弹性匹配距离 = 基础距离 * (1 - elasticity * 局部相似度)
  312. 312 let elastic_dist = base_dist * (1.0 - elasticity * local_similarity * 0.3)
  313. 313 elastic_dist
  314. 314}
  315. 315
  316. 316///|
  317. 317/// 连笔字符分割(基于笔画特征的分割点检测)
  318. 318pub fn segment_cursive_chars(
  319. 319 img : @types.Image,
  320. 320 min_char_width~ : Int32 = 8,
  321. 321 max_char_width~ : Int32 = 80,
  322. 322) -> Array[(Int32, Int32, Int32, Int32)] {
  323. 323● let w = img.width
  324. 324 let h = img.height
  325. 325 let data = img.data
  326. 326 // 计算垂直投影
  327. 327● let projection : Array[Int32] = Array::make(w, 0)
  328. 328 for x in 0..<w {
  329. 329● let mut count = 0
  330. 330 for y in 0..<h {
  331. 331● if data[y * w + x].to_int() > 128 {
  332. 332● count += 1
  333. 333 }
  334. 334 }
  335. 335 projection[x] = count
  336. 336 }
  337. 337 // 检测分割点(投影局部最小值)
  338. 338 let split_points : Array[Int32] = []
  339. 339 for x in 2..<(w - 2) {
  340. 340● if projection[x] < projection[x - 1] &&
  341. 341 projection[x] < projection[x + 1] &&
  342. 342 projection[x] < h / 10 {
  343. 343○ split_points.push(x)
  344. 344 }
  345. 345 }
  346. 346 // 基于分割点提取字符区域
  347. 347 let regions : Array[(Int32, Int32, Int32, Int32)] = []
  348. 348 let mut prev_x = 0
  349. 349 for split_x in split_points {
  350. 350○ let char_w = split_x - prev_x
  351. 351 if char_w >= min_char_width && char_w <= max_char_width {
  352. 352 // 找到字符的上下边界
  353. 353○ let mut min_y = h
  354. 354 let mut max_y = 0
  355. 355 for x in prev_x..<split_x {
  356. 356○ for y in 0..<h {
  357. 357○ if data[y * w + x].to_int() > 128 {
  358. 358○ if y < min_y {
  359. 359○ min_y = y
  360. 360 }
  361. 361 if y > max_y {
  362. 362○ max_y = y
  363. 363 }
  364. 364 }
  365. 365 }
  366. 366 }
  367. 367 if max_y > min_y {
  368. 368○ regions.push((prev_x, min_y, char_w, max_y - min_y + 1))
  369. 369 }
  370. 370 }
  371. 371 prev_x = split_x
  372. 372 }
  373. 373 // 处理最后一个字符
  374. 374 let char_w = w - prev_x
  375. 375 if char_w >= min_char_width && char_w <= max_char_width {
  376. 376● let mut min_y = h
  377. 377 let mut max_y = 0
  378. 378 for x in prev_x..<w {
  379. 379● for y in 0..<h {
  380. 380● if data[y * w + x].to_int() > 128 {
  381. 381● if y < min_y {
  382. 382● min_y = y
  383. 383 }
  384. 384 if y > max_y {
  385. 385● max_y = y
  386. 386 }
  387. 387 }
  388. 388 }
  389. 389 }
  390. 390 if max_y > min_y {
  391. 391● regions.push((prev_x, min_y, char_w, max_y - min_y + 1))
  392. 392 }
  393. 393 }
  394. 394 regions
  395. 395}
  396. 396
  397. 397///|
  398. 398/// 手写体后处理(基于常见手写体混淆的纠错)
  399. 399pub fn handwriting_postprocess(
  400. 400 text : String,
  401. 401 confidence : Double,
  402. 402) -> (String, Double) {
  403. 403 // 常见手写体混淆字符纠错
  404. 404● let corrected = text
  405. 405 // 简单替换(基于上下文的简单纠错)
  406. 406 // 注意:这是简化版,实际应该用语言模型
  407. 407 let mut adjusted_confidence = confidence
  408. 408 // 如果置信度低,降低调整后的置信度
  409. 409 if confidence < 0.5 {
  410. 410● adjusted_confidence = confidence * 0.9
  411. 411 }
  412. 412 (corrected, adjusted_confidence)
  413. 413}
  414. 414
  415. 415///|
  416. 416/// 增强手写体识别(完整流水线)
  417. 417pub fn recognize_handwriting_enhanced(
  418. 418 img : @types.Image,
  419. 419 config? : HandwritingOcrEnhancedConfig,
  420. 420) -> OcrResult raise @types.LoadError {
  421. 421 // 输入验证
  422. 422● if img.width <= 0 || img.height <= 0 {
  423. 423● raise @types.LoadError::DecodeFailed(
  424. 424 "recognize_handwriting_enhanced: 图像尺寸必须大于0",
  425. 425 )
  426. 426 }
  427. 427 if img.channels < 1 || img.channels > 4 {
  428. 428● raise @types.LoadError::DecodeFailed(
  429. 429 "recognize_handwriting_enhanced: 通道数必须在1-4之间",
  430. 430 )
  431. 431 }
  432. 432 let expected_size = img.width * img.height * img.channels
  433. 433● if img.data.length() != expected_size {
  434. 434● raise @types.LoadError::DecodeFailed(
  435. 435 "recognize_handwriting_enhanced: 数据大小不匹配,期望 " +
  436. 436● expected_size.to_string() +
  437. 437 ",实际 " +
  438. 438● img.data.length().to_string(),
  439. 439 )
  440. 440 }
  441. 441● let cfg = match config {
  442. 442● Some(c) => c
  443. 443● None => handwriting_ocr_enhanced_default_config()
  444. 444 }
  445. 445 // 1. 预处理
  446. 446● let mut preprocessed = ocr_preprocess(img)
  447. 447 // 2. 倾斜校正(手写体专用)
  448. 448 if cfg.use_slant_correction {
  449. 449● preprocessed = correct_slant(preprocessed)
  450. 450 }
  451. 451 // 3. 连笔字符分割
  452. 452 let char_regions = if cfg.use_elastic_matching {
  453. 453● segment_cursive_chars(
  454. 454 preprocessed,
  455. 455 min_char_width=cfg.min_char_width,
  456. 456 max_char_width=cfg.max_char_width,
  457. 457 )
  458. 458 } else {
  459. 459● segment_handwriting_chars_simple(preprocessed, cfg)
  460. 460 }
  461. 461 // 4. 生成增强手写体模板
  462. 462● let templates = generate_enhanced_handwriting_templates(
  463. 463 char_set="digits+letters",
  464. 464 num_variants=cfg.num_variants,
  465. 465 )
  466. 466 // 5. 对每个字符进行识别
  467. 467 let char_results : Array[OcrCharResult] = []
  468. 468 let mut text = ""
  469. 469 let mut total_confidence = 0.0
  470. 470 for _tup1 in char_regions {
  471. 471● let (x, y, w, h) = _tup1
  472. 472 // 提取字符图像
  473. 473● let char_img = extract_handwriting_char_region_enhanced(
  474. 474 preprocessed,
  475. 475 x,
  476. 476 y,
  477. 477 w,
  478. 478 h,
  479. 479 cfg.target_size,
  480. 480 )
  481. 481 // 提取网格特征
  482. 482● let features = extract_handwriting_grid_features(char_img, 16)
  483. 483 // 提取笔画特征(如果启用)
  484. 484 let stroke_features = if cfg.use_stroke_features {
  485. 485● extract_handwriting_stroke_features(char_img)
  486. 486 } else {
  487. 487● HandwritingStrokeFeatures::{
  488. 488 num_strokes: 0,
  489. 489 stroke_directions: [],
  490. 490 stroke_lengths: [],
  491. 491 connectivity: 0.0,
  492. 492 curvature: 0.0,
  493. 493 }
  494. 494 }
  495. 495 // 模板匹配(多变体投票 + 弹性匹配)
  496. 496● let result = match_handwriting_enhanced(
  497. 497 features, templates, stroke_features, cfg,
  498. 498 )
  499. 499 // 后处理(如果启用)
  500. 500 let (final_char, final_conf) = if cfg.use_postprocessing {
  501. 501● handwriting_postprocess(result.0, result.1)
  502. 502 } else {
  503. 503● result
  504. 504 }
  505. 505 text += final_char
  506. 506 total_confidence += final_conf
  507. 507● char_results.push(OcrCharResult::{
  508. 508 char: final_char,
  509. 509 confidence: final_conf,
  510. 510 x,
  511. 511 y,
  512. 512 width: w,
  513. 513 height: h,
  514. 514 })
  515. 515 }
  516. 516● let avg_confidence = if char_results.length() > 0 {
  517. 517● total_confidence / char_results.length().to_double()
  518. 518 } else {
  519. 519○ 0.0
  520. 520 }
  521. 521 OcrResult::{ text, confidence: avg_confidence, characters: char_results, }
  522. 522}
  523. 523
  524. 524///|
  525. 525/// 简单字符分割(备用)
  526. 526fn segment_handwriting_chars_simple(
  527. 527 img : @types.Image,
  528. 528 cfg : HandwritingOcrEnhancedConfig,
  529. 529) -> Array[(Int32, Int32, Int32, Int32)] {
  530. 530● let w = img.width
  531. 531 let h = img.height
  532. 532 let data = img.data
  533. 533● let labels : Array[Int32] = Array::make(w * h, 0)
  534. 534 let mut next_label = 1
  535. 535 for y in 0..<h {
  536. 536● for x in 0..<w {
  537. 537● if data[y * w + x].to_int() > 128 {
  538. 538● let mut label = 0
  539. 539 if x > 0 && labels[y * w + x - 1] > 0 {
  540. 540● label = labels[y * w + x - 1]
  541. 541 }
  542. 542 if y > 0 && labels[(y - 1) * w + x] > 0 {
  543. 543● if label == 0 {
  544. 544● label = labels[(y - 1) * w + x]
  545. 545 }
  546. 546 }
  547. 547 if label == 0 {
  548. 548● label = next_label
  549. 549 next_label += 1
  550. 550 }
  551. 551 labels[y * w + x] = label
  552. 552 }
  553. 553 }
  554. 554 }
  555. 555● let min_x : Array[Int32] = Array::make(next_label, w)
  556. 556● let max_x : Array[Int32] = Array::make(next_label, 0)
  557. 557● let min_y : Array[Int32] = Array::make(next_label, h)
  558. 558● let max_y : Array[Int32] = Array::make(next_label, 0)
  559. 559● let area : Array[Int32] = Array::make(next_label, 0)
  560. 560 for y in 0..<h {
  561. 561● for x in 0..<w {
  562. 562● let label = labels[y * w + x]
  563. 563 if label > 0 {
  564. 564● area[label] += 1
  565. 565 if x < min_x[label] {
  566. 566● min_x[label] = x
  567. 567 }
  568. 568 if x > max_x[label] {
  569. 569● max_x[label] = x
  570. 570 }
  571. 571 if y < min_y[label] {
  572. 572● min_y[label] = y
  573. 573 }
  574. 574 if y > max_y[label] {
  575. 575● max_y[label] = y
  576. 576 }
  577. 577 }
  578. 578 }
  579. 579 }
  580. 580 let regions : Array[(Int32, Int32, Int32, Int32)] = []
  581. 581 for label in 1..<next_label {
  582. 582● let rw = max_x[label] - min_x[label] + 1
  583. 583 let rh = max_y[label] - min_y[label] + 1
  584. 584 if rw >= cfg.min_char_width &&
  585. 585 rw <= cfg.max_char_width &&
  586. 586 rh >= cfg.min_char_height &&
  587. 587 rh <= cfg.max_char_height &&
  588. 588 area[label] > 15 {
  589. 589● regions.push((min_x[label], min_y[label], rw, rh))
  590. 590 }
  591. 591 }
  592. 592 regions
  593. 593}
  594. 594
  595. 595///|
  596. 596/// 提取手写体字符区域(增强版)
  597. 597fn extract_handwriting_char_region_enhanced(
  598. 598 img : @types.Image,
  599. 599 x : Int32,
  600. 600 y : Int32,
  601. 601 width : Int32,
  602. 602 height : Int32,
  603. 603 target_size : Int32,
  604. 604) -> @types.Image {
  605. 605● let w = img.width
  606. 606 let h = img.height
  607. 607◐ let crop_w = if x + width > w { w - x } else { width }
  608. 608◐ let crop_h = if y + height > h { h - y } else { height }
  609. 609 if crop_w <= 0 || crop_h <= 0 {
  610. 610○ let empty : Array[Byte] = Array::make(target_size * target_size, b'\x00')
  611. 611 return @types.Image::{
  612. 612 width: target_size,
  613. 613 height: target_size,
  614. 614 channels: 1,
  615. 615○ data: Bytes::from_array(empty),
  616. 616 }
  617. 617 }
  618. 618● let out : Array[Byte] = Array::make(target_size * target_size, b'\x00')
  619. 619 let data = img.data
  620. 620 for py in 0..<target_size {
  621. 621● for px in 0..<target_size {
  622. 622● let src_x = x + px * crop_w / target_size
  623. 623 let src_y = y + py * crop_h / target_size
  624. 624 if src_x < w && src_y < h {
  625. 625● out[py * target_size + px] = data[src_y * w + src_x]
  626. 626 }
  627. 627 }
  628. 628 }
  629. 629 @types.Image::{
  630. 630 width: target_size,
  631. 631 height: target_size,
  632. 632 channels: 1,
  633. 633● data: Bytes::from_array(out),
  634. 634 }
  635. 635}
  636. 636
  637. 637///|
  638. 638/// 提取手写体网格特征
  639. 639fn extract_handwriting_grid_features(
  640. 640 char_img : @types.Image,
  641. 641 grid_size : Int32,
  642. 642) -> Array[Double] {
  643. 643● let w = char_img.width
  644. 644 let h = char_img.height
  645. 645 let data = char_img.data
  646. 646 let cell_w = w / grid_size
  647. 647 let cell_h = h / grid_size
  648. 648 let features : Array[Double] = []
  649. 649 for r in 0..<grid_size {
  650. 650● for c in 0..<grid_size {
  651. 651● let mut count = 0
  652. 652 let mut total = 0
  653. 653 for py in 0..<cell_h {
  654. 654● for px in 0..<cell_w {
  655. 655● let sx = c * cell_w + px
  656. 656 let sy = r * cell_h + py
  657. 657 if sx < w && sy < h {
  658. 658● total += 1
  659. 659● if data[sy * w + sx].to_int() > 128 {
  660. 660● count += 1
  661. 661 }
  662. 662 }
  663. 663 }
  664. 664 }
  665. 665 let density = if total > 0 {
  666. 666● count.to_double() / total.to_double()
  667. 667 } else {
  668. 668○ 0.0
  669. 669 }
  670. 670● features.push(density)
  671. 671 }
  672. 672 }
  673. 673 features
  674. 674}
  675. 675
  676. 676///|
  677. 677/// 增强手写体模板匹配(多变体投票 + 弹性匹配 + 笔画特征)
  678. 678fn match_handwriting_enhanced(
  679. 679 features : Array[Double],
  680. 680 templates : Array[(String, Array[Double])],
  681. 681 stroke_features : HandwritingStrokeFeatures,
  682. 682 cfg : HandwritingOcrEnhancedConfig,
  683. 683) -> (String, Double) {
  684. 684● ignore(stroke_features)
  685. 685 // 收集所有变体的预测
  686. 686 let label_votes : Array[(String, Double)] = []
  687. 687 for _tup2 in templates {
  688. 688● let (label_full, template) = _tup2
  689. 689 // 弹性匹配(如果启用)
  690. 690 let dist = if cfg.use_elastic_matching {
  691. 691● elastic_match(features, template, elasticity=cfg.elasticity, grid_size=16)
  692. 692 } else {
  693. 693● let n = if features.length() < template.length() {
  694. 694● features.length()
  695. 695 } else {
  696. 696○ template.length()
  697. 697 }
  698. 698 let mut sum_sq = 0.0
  699. 699 for i in 0..<n {
  700. 700● let diff = features[i] - template[i]
  701. 701 sum_sq += diff * diff
  702. 702 }
  703. 703● sum_sq.sqrt()
  704. 704 }
  705. 705◐ let confidence = if dist > 0.0 { 1.0 / (1.0 + dist) } else { 1.0 }
  706. 706 // 提取基础标签(去掉变体后缀)
  707. 707● let base_label = if label_full.length() > 0 {
  708. 708● label_full[0].to_string()
  709. 709 } else {
  710. 710○ label_full
  711. 711 }
  712. 712 // 投票
  713. 713 let mut found = false
  714. 714● for i in 0..<label_votes.length() {
  715. 715● if label_votes[i].0 == base_label {
  716. 716● label_votes[i] = (base_label, label_votes[i].1 + confidence)
  717. 717 found = true
  718. 718 }
  719. 719 }
  720. 720 if !found {
  721. 721● label_votes.push((base_label, confidence))
  722. 722 }
  723. 723 }
  724. 724 // 找得票最多的标签
  725. 725 let mut best_label = "?"
  726. 726 let mut best_votes = 0.0
  727. 727 let mut total_votes = 0.0
  728. 728 for _tup3 in label_votes {
  729. 729● let (label, votes) = _tup3
  730. 730 total_votes += votes
  731. 731 if votes > best_votes {
  732. 732● best_votes = votes
  733. 733 best_label = label
  734. 734 }
  735. 735 }
  736. 736 let confidence = if total_votes > 0.0 {
  737. 737● best_votes / total_votes
  738. 738 } else {
  739. 739○ 0.0
  740. 740 }
  741. 741 (best_label, confidence)
  742. 742}