image.vision\ocr\handwriting_recognition.mbt

93.2% · 179 / 192 points · 766 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/handwriting_recognition
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 手写体识别支持(v13.2.0)
  7. 7// 手写字符预处理、连笔分割、笔画特征提取、手写字体模板、手写识别引擎
  8. 8
  9. 9///|
  10. 10/// 手写体类型
  11. 11/// `#non_exhaustive` 表示未来可能添加新构造器
  12. 12#derive(Eq, @debug.Debug)
  13. 13#non_exhaustive
  14. 14pub(all) enum HandwritingStyle {
  15. 15 Print // 印刷体
  16. 16 Cursive // 草书/连笔
  17. 17 SemiCursive // 半连笔
  18. 18 Block // 方块字
  19. 19 Unknown
  20. 20}
  21. 21
  22. 22///|
  23. 23pub extend HandwritingStyle with @debug.Debug::{to_repr}
  24. 24
  25. 25///|
  26. 26pub extend HandwritingStyle with Eq::{not_equal, equal}
  27. 27
  28. 28///|
  29. 29/// 笔画类型
  30. 30/// `#non_exhaustive` 表示未来可能添加新构造器
  31. 31#derive(Eq, @debug.Debug)
  32. 32#non_exhaustive
  33. 33pub(all) enum StrokeType {
  34. 34 Horizontal // 横
  35. 35 Vertical // 竖
  36. 36 LeftFalling // 撇
  37. 37 RightFalling // 捺
  38. 38 Dot // 点
  39. 39 Hook // 钩
  40. 40 Turning // 折
  41. 41 Rising // 提
  42. 42 Unknown
  43. 43}
  44. 44
  45. 45///|
  46. 46pub extend StrokeType with @debug.Debug::{to_repr}
  47. 47
  48. 48///|
  49. 49pub extend StrokeType with Eq::{not_equal, equal}
  50. 50
  51. 51///|
  52. 52/// 笔画特征
  53. 53#derive(Eq, @debug.Debug)
  54. 54pub(all) struct StrokeFeature {
  55. 55 stroke_type : StrokeType
  56. 56 start_x : Double
  57. 57 start_y : Double
  58. 58 end_x : Double
  59. 59 end_y : Double
  60. 60 length : Double
  61. 61 angle : Double
  62. 62 curvature : Double
  63. 63 pressure : Double
  64. 64}
  65. 65
  66. 66///|
  67. 67pub extend StrokeFeature with Eq::{not_equal, equal}
  68. 68
  69. 69///|
  70. 70pub extend StrokeFeature with @debug.Debug::{to_repr}
  71. 71
  72. 72///|
  73. 73/// 连笔分割结果
  74. 74#derive(Eq, @debug.Debug)
  75. 75pub(all) struct StrokeSegmentationResult {
  76. 76 num_strokes : Int32
  77. 77 strokes : Array[StrokeFeature]
  78. 78 segmentation_points : Array[(Int32, Int32)]
  79. 79 confidence : Double
  80. 80}
  81. 81
  82. 82///|
  83. 83pub extend StrokeSegmentationResult with Eq::{not_equal, equal}
  84. 84
  85. 85///|
  86. 86pub extend StrokeSegmentationResult with @debug.Debug::{to_repr}
  87. 87
  88. 88///|
  89. 89/// 手写字符特征
  90. 90#derive(Eq, @debug.Debug)
  91. 91pub(all) struct HandwritingCharFeature {
  92. 92 char : String
  93. 93 num_strokes : Int32
  94. 94 stroke_types : Array[StrokeType]
  95. 95 aspect_ratio : Double
  96. 96 density : Double
  97. 97 center_of_mass_x : Double
  98. 98 center_of_mass_y : Double
  99. 99 horizontal_projection : Array[Double]
  100. 100 vertical_projection : Array[Double]
  101. 101 contour_complexity : Double
  102. 102 slant_angle : Double
  103. 103 size_normalized : Bool
  104. 104}
  105. 105
  106. 106///|
  107. 107pub extend HandwritingCharFeature with Eq::{not_equal, equal}
  108. 108
  109. 109///|
  110. 110pub extend HandwritingCharFeature with @debug.Debug::{to_repr}
  111. 111
  112. 112///|
  113. 113/// 手写字体模板
  114. 114#derive(Eq, @debug.Debug)
  115. 115pub(all) struct HandwritingTemplate {
  116. 116 char : String
  117. 117 style : HandwritingStyle
  118. 118 features : HandwritingCharFeature
  119. 119 sample_count : Int32
  120. 120 avg_accuracy : Double
  121. 121}
  122. 122
  123. 123///|
  124. 124pub extend HandwritingTemplate with Eq::{not_equal, equal}
  125. 125
  126. 126///|
  127. 127pub extend HandwritingTemplate with @debug.Debug::{to_repr}
  128. 128
  129. 129///|
  130. 130/// 手写识别配置
  131. 131#derive(Eq, @debug.Debug)
  132. 132pub(all) struct HandwritingRecognitionConfig {
  133. 133 min_stroke_length : Double
  134. 134 max_stroke_angle : Double
  135. 135 segmentation_threshold : Double
  136. 136 similarity_threshold : Double
  137. 137 enable_slant_correction : Bool
  138. 138 enable_size_normalization : Bool
  139. 139 enable_stroke_order : Bool
  140. 140 max_candidates : Int32
  141. 141 style_priority : HandwritingStyle
  142. 142}
  143. 143
  144. 144///|
  145. 145pub extend HandwritingRecognitionConfig with Eq::{not_equal, equal}
  146. 146
  147. 147///|
  148. 148pub extend HandwritingRecognitionConfig with @debug.Debug::{to_repr}
  149. 149
  150. 150///|
  151. 151/// 手写识别结果
  152. 152#derive(Eq, @debug.Debug)
  153. 153pub(all) struct HandwritingRecognitionResult {
  154. 154 predicted_char : String
  155. 155 confidence : Double
  156. 156 top_candidates : Array[(String, Double)]
  157. 157 detected_style : HandwritingStyle
  158. 158 num_strokes_detected : Int32
  159. 159 slant_angle : Double
  160. 160 preprocessing_time_ms : Double
  161. 161 feature_extraction_time_ms : Double
  162. 162 matching_time_ms : Double
  163. 163 total_time_ms : Double
  164. 164}
  165. 165
  166. 166///|
  167. 167pub extend HandwritingRecognitionResult with Eq::{not_equal, equal}
  168. 168
  169. 169///|
  170. 170pub extend HandwritingRecognitionResult with @debug.Debug::{to_repr}
  171. 171
  172. 172///|
  173. 173/// 创建默认手写识别配置
  174. 174pub fn create_default_handwriting_config() -> HandwritingRecognitionConfig {
  175. 175● HandwritingRecognitionConfig::{
  176. 176 min_stroke_length: 5.0,
  177. 177 max_stroke_angle: 45.0,
  178. 178 segmentation_threshold: 0.3,
  179. 179 similarity_threshold: 0.6,
  180. 180 enable_slant_correction: true,
  181. 181 enable_size_normalization: true,
  182. 182 enable_stroke_order: true,
  183. 183 max_candidates: 5,
  184. 184 style_priority: HandwritingStyle::SemiCursive,
  185. 185 }
  186. 186}
  187. 187
  188. 188///|
  189. 189/// 检测手写体倾斜角度
  190. 190pub fn detect_handwriting_slant(
  191. 191 img : @types.Image,
  192. 192) -> Double raise @types.LoadError {
  193. 193 // 输入验证
  194. 194● if img.width <= 0 || img.height <= 0 {
  195. 195● raise @types.LoadError::DecodeFailed(
  196. 196 "detect_handwriting_slant: 图像尺寸必须大于0",
  197. 197 )
  198. 198 }
  199. 199 if img.channels < 1 || img.channels > 4 {
  200. 200● raise @types.LoadError::DecodeFailed(
  201. 201 "detect_handwriting_slant: 通道数必须在1-4之间",
  202. 202 )
  203. 203 }
  204. 204 let expected_size = img.width * img.height * img.channels
  205. 205● if img.data.length() != expected_size {
  206. 206● raise @types.LoadError::DecodeFailed(
  207. 207 "detect_handwriting_slant: 数据大小不匹配,期望 " +
  208. 208● expected_size.to_string() +
  209. 209 ",实际 " +
  210. 210● img.data.length().to_string(),
  211. 211 )
  212. 212 }
  213. 213 let w = img.width
  214. 214 let h = img.height
  215. 215 // 基于文本行的倾斜检测
  216. 216 let mut total_angle = 0.0
  217. 217 let mut line_count = 0
  218. 218
  219. 219 for y in 0..<(h - 1) {
  220. 220● let mut start_x = -1
  221. 221 let mut end_x = -1
  222. 222 for x in 0..<w {
  223. 223● if img.data[y * w + x].to_int() < 128 {
  224. 224● if start_x == -1 {
  225. 225● start_x = x
  226. 226 }
  227. 227 end_x = x
  228. 228 }
  229. 229 }
  230. 230 if start_x != -1 && end_x != -1 && end_x - start_x > w / 4 {
  231. 231● let center_x = (start_x + end_x) / 2
  232. 232 // 简化:用行中心的变化计算倾斜
  233. 233 if y > 0 {
  234. 234● let prev_center = center_x
  235. 235● let angle = (prev_center - center_x).to_double() /
  236. 236● h.to_double() *
  237. 237 57.2958
  238. 238 total_angle += angle
  239. 239 line_count += 1
  240. 240 }
  241. 241 }
  242. 242 }
  243. 243
  244. 244 if line_count > 0 {
  245. 245● total_angle / line_count.to_double()
  246. 246 } else {
  247. 247● 0.0
  248. 248 }
  249. 249}
  250. 250
  251. 251///|
  252. 252/// 手写字符大小归一化(简化版,返回尺寸信息)
  253. 253pub fn normalize_handwriting_size(
  254. 254 img : @types.Image,
  255. 255 target_size : Int32,
  256. 256) -> @types.Image raise @types.LoadError {
  257. 257 // 输入验证
  258. 258● if img.width <= 0 || img.height <= 0 {
  259. 259● raise @types.LoadError::DecodeFailed(
  260. 260 "normalize_handwriting_size: 图像尺寸必须大于0",
  261. 261 )
  262. 262 }
  263. 263 if img.channels < 1 || img.channels > 4 {
  264. 264○ raise @types.LoadError::DecodeFailed(
  265. 265 "normalize_handwriting_size: 通道数必须在1-4之间",
  266. 266 )
  267. 267 }
  268. 268 let expected_size = img.width * img.height * img.channels
  269. 269● if img.data.length() != expected_size {
  270. 270● raise @types.LoadError::DecodeFailed(
  271. 271 "normalize_handwriting_size: 数据大小不匹配,期望 " +
  272. 272● expected_size.to_string() +
  273. 273 ",实际 " +
  274. 274● img.data.length().to_string(),
  275. 275 )
  276. 276 }
  277. 277 if target_size <= 0 {
  278. 278● raise @types.LoadError::DecodeFailed(
  279. 279 "normalize_handwriting_size: 目标尺寸必须大于0",
  280. 280 )
  281. 281 }
  282. 282 // 简化版:返回原图像,实际应进行缩放
  283. 283 img
  284. 284}
  285. 285
  286. 286///|
  287. 287/// 提取笔画特征
  288. 288pub fn extract_hw_stroke_features(img : @types.Image) -> Array[StrokeFeature] {
  289. 289● let w = img.width
  290. 290 let h = img.height
  291. 291 let strokes : Array[StrokeFeature] = []
  292. 292
  293. 293 // 简化版:基于连通域的笔画提取
  294. 294 let visited : Array[Bool] = []
  295. 295 for _ in 0..<(w * h) {
  296. 296● visited.push(false)
  297. 297 }
  298. 298
  299. 299 for y in 0..<h {
  300. 300● for x in 0..<w {
  301. 301● let idx = y * w + x
  302. 302● if !visited[idx] && img.data[idx].to_int() < 128 {
  303. 303 // 找到一个连通域(简化为单点)
  304. 304● visited[idx] = true
  305. 305 let stroke = StrokeFeature::{
  306. 306 stroke_type: StrokeType::Unknown,
  307. 307● start_x: x.to_double(),
  308. 308● start_y: y.to_double(),
  309. 309● end_x: x.to_double(),
  310. 310● end_y: y.to_double(),
  311. 311 length: 1.0,
  312. 312 angle: 0.0,
  313. 313 curvature: 0.0,
  314. 314 pressure: 0.5,
  315. 315 }
  316. 316● strokes.push(stroke)
  317. 317 }
  318. 318 }
  319. 319 }
  320. 320
  321. 321 strokes
  322. 322}
  323. 323
  324. 324///|
  325. 325/// 连笔分割
  326. 326pub fn segment_connected_strokes(
  327. 327 img : @types.Image,
  328. 328 config : HandwritingRecognitionConfig,
  329. 329) -> StrokeSegmentationResult {
  330. 330● let strokes = extract_hw_stroke_features(img)
  331. 331 let segmentation_points : Array[(Int32, Int32)] = []
  332. 332
  333. 333 // 简化版:基于笔画长度的分割
  334. 334● for i in 0..<strokes.length() {
  335. 335● if strokes[i].length < config.min_stroke_length {
  336. 336● segmentation_points.push(
  337. 337● (strokes[i].start_x.to_int(), strokes[i].start_y.to_int()),
  338. 338 )
  339. 339 }
  340. 340 }
  341. 341
  342. 342 StrokeSegmentationResult::{
  343. 343● num_strokes: strokes.length(),
  344. 344 strokes,
  345. 345 segmentation_points,
  346. 346 confidence: 0.7,
  347. 347 }
  348. 348}
  349. 349
  350. 350///|
  351. 351/// 提取手写字符特征
  352. 352pub fn extract_handwriting_features(
  353. 353 img : @types.Image,
  354. 354 char : String,
  355. 355) -> HandwritingCharFeature raise @types.LoadError {
  356. 356 // 输入验证
  357. 357● if img.width <= 0 || img.height <= 0 {
  358. 358● raise @types.LoadError::DecodeFailed(
  359. 359 "extract_handwriting_features: 图像尺寸必须大于0",
  360. 360 )
  361. 361 }
  362. 362 if img.channels < 1 || img.channels > 4 {
  363. 363● raise @types.LoadError::DecodeFailed(
  364. 364 "extract_handwriting_features: 通道数必须在1-4之间",
  365. 365 )
  366. 366 }
  367. 367 let expected_size = img.width * img.height * img.channels
  368. 368● if img.data.length() != expected_size {
  369. 369● raise @types.LoadError::DecodeFailed(
  370. 370 "extract_handwriting_features: 数据大小不匹配,期望 " +
  371. 371● expected_size.to_string() +
  372. 372 ",实际 " +
  373. 373● img.data.length().to_string(),
  374. 374 )
  375. 375 }
  376. 376 let w = img.width
  377. 377 let h = img.height
  378. 378
  379. 379 // 计算水平投影
  380. 380 let horizontal : Array[Double] = []
  381. 381 for y in 0..<h {
  382. 382● let mut count = 0.0
  383. 383 for x in 0..<w {
  384. 384● if img.data[y * w + x].to_int() < 128 {
  385. 385● count += 1.0
  386. 386 }
  387. 387 }
  388. 388● horizontal.push(count / w.to_double())
  389. 389 }
  390. 390
  391. 391 // 计算垂直投影
  392. 392 let vertical : Array[Double] = []
  393. 393 for x in 0..<w {
  394. 394● let mut count = 0.0
  395. 395 for y in 0..<h {
  396. 396● if img.data[y * w + x].to_int() < 128 {
  397. 397● count += 1.0
  398. 398 }
  399. 399 }
  400. 400● vertical.push(count / h.to_double())
  401. 401 }
  402. 402
  403. 403 // 计算重心
  404. 404 let mut total_mass = 0.0
  405. 405 let mut sum_x = 0.0
  406. 406 let mut sum_y = 0.0
  407. 407 for y in 0..<h {
  408. 408● for x in 0..<w {
  409. 409● if img.data[y * w + x].to_int() < 128 {
  410. 410● total_mass += 1.0
  411. 411● sum_x += x.to_double()
  412. 412● sum_y += y.to_double()
  413. 413 }
  414. 414 }
  415. 415 }
  416. 416
  417. 417 let center_x = if total_mass > 0 {
  418. 418● sum_x / total_mass
  419. 419 } else {
  420. 420● w.to_double() / 2.0
  421. 421 }
  422. 422 let center_y = if total_mass > 0 {
  423. 423● sum_y / total_mass
  424. 424 } else {
  425. 425● h.to_double() / 2.0
  426. 426 }
  427. 427
  428. 428 // 计算密度
  429. 429● let density = total_mass / (w * h).to_double()
  430. 430
  431. 431 // 提取笔画
  432. 432● let strokes = extract_hw_stroke_features(img)
  433. 433 let stroke_types : Array[StrokeType] = []
  434. 434 for s in strokes {
  435. 435● stroke_types.push(s.stroke_type)
  436. 436 }
  437. 437
  438. 438 HandwritingCharFeature::{
  439. 439 char,
  440. 440● num_strokes: strokes.length(),
  441. 441 stroke_types,
  442. 442● aspect_ratio: w.to_double() / h.to_double(),
  443. 443 density,
  444. 444● center_of_mass_x: center_x / w.to_double(),
  445. 445● center_of_mass_y: center_y / h.to_double(),
  446. 446 horizontal_projection: horizontal,
  447. 447 vertical_projection: vertical,
  448. 448● contour_complexity: strokes.length().to_double() / 10.0,
  449. 449● slant_angle: detect_handwriting_slant(img),
  450. 450 size_normalized: true,
  451. 451 }
  452. 452}
  453. 453
  454. 454///|
  455. 455/// 计算手写特征相似度
  456. 456pub fn handwriting_feature_similarity(
  457. 457 feat1 : HandwritingCharFeature,
  458. 458 feat2 : HandwritingCharFeature,
  459. 459) -> Double {
  460. 460● let mut score = 0.0
  461. 461
  462. 462 // 笔画数相似度(20%)
  463. 463● let stroke_diff = (feat1.num_strokes - feat2.num_strokes).abs().to_double()
  464. 464 let stroke_sim = if stroke_diff < 1 {
  465. 465● 1.0
  466. 466● } else if stroke_diff < 3 {
  467. 467● 0.7
  468. 468 } else {
  469. 469● 0.4
  470. 470 }
  471. 471 score += stroke_sim * 0.2
  472. 472
  473. 473 // 宽高比相似度(15%)
  474. 474● let aspect_diff = (feat1.aspect_ratio - feat2.aspect_ratio).abs()
  475. 475 let aspect_sim = if aspect_diff < 0.1 {
  476. 476● 1.0
  477. 477● } else if aspect_diff < 0.3 {
  478. 478○ 0.7
  479. 479 } else {
  480. 480● 0.4
  481. 481 }
  482. 482 score += aspect_sim * 0.15
  483. 483
  484. 484 // 密度相似度(15%)
  485. 485● let density_diff = (feat1.density - feat2.density).abs()
  486. 486 let density_sim = if density_diff < 0.05 {
  487. 487● 1.0
  488. 488● } else if density_diff < 0.15 {
  489. 489○ 0.7
  490. 490 } else {
  491. 491● 0.4
  492. 492 }
  493. 493 score += density_sim * 0.15
  494. 494
  495. 495 // 重心相似度(20%)
  496. 496● let center_dist = (@math.pow(
  497. 497 feat1.center_of_mass_x - feat2.center_of_mass_x,
  498. 498 2.0,
  499. 499 ) +
  500. 500● @math.pow(feat1.center_of_mass_y - feat2.center_of_mass_y, 2.0)).sqrt()
  501. 501 let center_sim = if center_dist < 0.05 {
  502. 502● 1.0
  503. 503● } else if center_dist < 0.15 {
  504. 504○ 0.7
  505. 505 } else {
  506. 506● 0.4
  507. 507 }
  508. 508 score += center_sim * 0.2
  509. 509
  510. 510 // 倾斜角度相似度(10%)
  511. 511● let slant_diff = (feat1.slant_angle - feat2.slant_angle).abs()
  512. 512 let slant_sim = if slant_diff < 5.0 {
  513. 513● 1.0
  514. 514● } else if slant_diff < 15.0 {
  515. 515○ 0.7
  516. 516 } else {
  517. 517● 0.4
  518. 518 }
  519. 519 score += slant_sim * 0.1
  520. 520
  521. 521 // 轮廓复杂度相似度(10%)
  522. 522● let contour_diff = (feat1.contour_complexity - feat2.contour_complexity).abs()
  523. 523 let contour_sim = if contour_diff < 0.5 {
  524. 524● 1.0
  525. 525● } else if contour_diff < 1.5 {
  526. 526● 0.7
  527. 527 } else {
  528. 528● 0.4
  529. 529 }
  530. 530 score += contour_sim * 0.1
  531. 531
  532. 532 score
  533. 533}
  534. 534
  535. 535///|
  536. 536/// 创建手写字体模板
  537. 537pub fn create_handwriting_template(
  538. 538 char : String,
  539. 539 style : HandwritingStyle,
  540. 540 samples : Array[@types.Image],
  541. 541) -> HandwritingTemplate raise @types.LoadError {
  542. 542 // 输入验证
  543. 543● if char.length() == 0 {
  544. 544● raise @types.LoadError::DecodeFailed(
  545. 545 "create_handwriting_template: 字符不能为空",
  546. 546 )
  547. 547 }
  548. 548● if samples.length() == 0 {
  549. 549● return HandwritingTemplate::{
  550. 550 char,
  551. 551 style,
  552. 552 features: HandwritingCharFeature::{
  553. 553 char,
  554. 554 num_strokes: 0,
  555. 555 stroke_types: [],
  556. 556 aspect_ratio: 1.0,
  557. 557 density: 0.0,
  558. 558 center_of_mass_x: 0.5,
  559. 559 center_of_mass_y: 0.5,
  560. 560 horizontal_projection: [],
  561. 561 vertical_projection: [],
  562. 562 contour_complexity: 0.0,
  563. 563 slant_angle: 0.0,
  564. 564 size_normalized: false,
  565. 565 },
  566. 566 sample_count: 0,
  567. 567 avg_accuracy: 0.0,
  568. 568 }
  569. 569 }
  570. 570
  571. 571 // 计算平均特征
  572. 572 let mut avg_strokes = 0.0
  573. 573 let mut avg_aspect = 0.0
  574. 574 let mut avg_density = 0.0
  575. 575 let mut avg_center_x = 0.0
  576. 576 let mut avg_center_y = 0.0
  577. 577 let mut avg_slant = 0.0
  578. 578 let mut avg_contour = 0.0
  579. 579
  580. 580 for sample in samples {
  581. 581● let feat = extract_handwriting_features(sample, char)
  582. 582● avg_strokes += feat.num_strokes.to_double()
  583. 583 avg_aspect += feat.aspect_ratio
  584. 584 avg_density += feat.density
  585. 585 avg_center_x += feat.center_of_mass_x
  586. 586 avg_center_y += feat.center_of_mass_y
  587. 587 avg_slant += feat.slant_angle
  588. 588 avg_contour += feat.contour_complexity
  589. 589 }
  590. 590
  591. 591● let n = samples.length().to_double()
  592. 592 let avg_features = HandwritingCharFeature::{
  593. 593 char,
  594. 594● num_strokes: (avg_strokes / n).to_int(),
  595. 595 stroke_types: [],
  596. 596 aspect_ratio: avg_aspect / n,
  597. 597 density: avg_density / n,
  598. 598 center_of_mass_x: avg_center_x / n,
  599. 599 center_of_mass_y: avg_center_y / n,
  600. 600 horizontal_projection: [],
  601. 601 vertical_projection: [],
  602. 602 contour_complexity: avg_contour / n,
  603. 603 slant_angle: avg_slant / n,
  604. 604 size_normalized: true,
  605. 605 }
  606. 606
  607. 607 HandwritingTemplate::{
  608. 608 char,
  609. 609 style,
  610. 610 features: avg_features,
  611. 611● sample_count: samples.length(),
  612. 612 avg_accuracy: 0.85,
  613. 613 }
  614. 614}
  615. 615
  616. 616///|
  617. 617/// 手写字符识别
  618. 618pub fn recognize_handwriting_char(
  619. 619 img : @types.Image,
  620. 620 templates : Array[HandwritingTemplate],
  621. 621 config : HandwritingRecognitionConfig,
  622. 622) -> HandwritingRecognitionResult raise @types.LoadError {
  623. 623 // 输入验证
  624. 624● if img.width <= 0 || img.height <= 0 {
  625. 625● raise @types.LoadError::DecodeFailed(
  626. 626 "recognize_handwriting_char: 图像尺寸必须大于0",
  627. 627 )
  628. 628 }
  629. 629 if img.channels < 1 || img.channels > 4 {
  630. 630○ raise @types.LoadError::DecodeFailed(
  631. 631 "recognize_handwriting_char: 通道数必须在1-4之间",
  632. 632 )
  633. 633 }
  634. 634 let expected_size = img.width * img.height * img.channels
  635. 635● if img.data.length() != expected_size {
  636. 636● raise @types.LoadError::DecodeFailed(
  637. 637 "recognize_handwriting_char: 数据大小不匹配,期望 " +
  638. 638● expected_size.to_string() +
  639. 639 ",实际 " +
  640. 640● img.data.length().to_string(),
  641. 641 )
  642. 642 }
  643. 643● if templates.length() == 0 {
  644. 644● raise @types.LoadError::DecodeFailed(
  645. 645 "recognize_handwriting_char: 模板列表不能为空",
  646. 646 )
  647. 647 }
  648. 648 if config.similarity_threshold < 0.0 || config.similarity_threshold > 1.0 {
  649. 649○ raise @types.LoadError::DecodeFailed(
  650. 650 "recognize_handwriting_char: 相似度阈值必须在0-1之间",
  651. 651 )
  652. 652 }
  653. 653 let _ = 0.0
  654. 654
  655. 655 // 1. 预处理
  656. 656 let preprocessed = if config.enable_size_normalization {
  657. 657● normalize_handwriting_size(img, 64)
  658. 658 } else {
  659. 659○ img
  660. 660 }
  661. 661 let preprocess_time = 0.0
  662. 662
  663. 663 // 2. 特征提取
  664. 664● let features = extract_handwriting_features(preprocessed, "?")
  665. 665 let feature_time = 0.0
  666. 666
  667. 667 // 3. 模板匹配
  668. 668 let candidates : Array[(String, Double)] = []
  669. 669 for template in templates {
  670. 670● let sim = handwriting_feature_similarity(features, template.features)
  671. 671 if sim > config.similarity_threshold {
  672. 672● candidates.push((template.char, sim))
  673. 673 }
  674. 674 }
  675. 675
  676. 676 // 排序
  677. 677● for i in 0..<candidates.length() {
  678. 678● for j in 0..<(candidates.length() - i - 1) {
  679. 679● if candidates[j].1 < candidates[j + 1].1 {
  680. 680○ let temp = candidates[j]
  681. 681 candidates[j] = candidates[j + 1]
  682. 682 candidates[j + 1] = temp
  683. 683 }
  684. 684 }
  685. 685 }
  686. 686
  687. 687 let match_time = 0.0
  688. 688
  689. 689● let predicted = if candidates.length() > 0 { candidates[0].0 } else { "?" }
  690. 690● let confidence = if candidates.length() > 0 { candidates[0].1 } else { 0.0 }
  691. 691
  692. 692 let top_candidates : Array[(String, Double)] = []
  693. 693 for
  694. 694● i in 0..<(if config.max_candidates < candidates.length() {
  695. 695○ config.max_candidates
  696. 696 } else {
  697. 697● candidates.length()
  698. 698 }) {
  699. 699● top_candidates.push(candidates[i])
  700. 700 }
  701. 701
  702. 702 HandwritingRecognitionResult::{
  703. 703 predicted_char: predicted,
  704. 704 confidence,
  705. 705 top_candidates,
  706. 706 detected_style: config.style_priority,
  707. 707 num_strokes_detected: features.num_strokes,
  708. 708 slant_angle: features.slant_angle,
  709. 709 preprocessing_time_ms: preprocess_time,
  710. 710 feature_extraction_time_ms: feature_time,
  711. 711 matching_time_ms: match_time,
  712. 712 total_time_ms: 0.0,
  713. 713 }
  714. 714}
  715. 715
  716. 716///|
  717. 717/// 生成手写识别报告
  718. 718pub fn handwriting_report_to_string(
  719. 719 result : HandwritingRecognitionResult,
  720. 720) -> String {
  721. 721● let mut report = "## 手写体识别报告\n\n"
  722. 722 report = report + "### 识别结果\n\n"
  723. 723 report = report + "| 指标 | 值 |\n"
  724. 724 report = report + "|------|------|\n"
  725. 725 report = report + "| 预测字符 | **" + result.predicted_char + "** |\n"
  726. 726 report = report +
  727. 727 "| 置信度 | " +
  728. 728● (result.confidence * 100.0).to_string() +
  729. 729 "% |\n"
  730. 730 report = report +
  731. 731 "| 检测字体 | " +
  732. 732● (match result.detected_style {
  733. 733● HandwritingStyle::Print => "印刷体"
  734. 734○ HandwritingStyle::Cursive => "草书/连笔"
  735. 735● HandwritingStyle::SemiCursive => "半连笔"
  736. 736○ HandwritingStyle::Block => "方块字"
  737. 737○ _ => "未知"
  738. 738 }) +
  739. 739 " |\n"
  740. 740 report = report +
  741. 741 "| 检测笔画数 | " +
  742. 742● result.num_strokes_detected.to_string() +
  743. 743 " |\n"
  744. 744 report = report +
  745. 745 "| 倾斜角度 | " +
  746. 746● result.slant_angle.to_string() +
  747. 747 "° |\n\n"
  748. 748
  749. 749● if result.top_candidates.length() > 0 {
  750. 750● report = report + "### Top-K 候选\n\n"
  751. 751 report = report + "| 排名 | 字符 | 置信度 |\n"
  752. 752 report = report + "|------|------|--------|\n"
  753. 753● for i in 0..<result.top_candidates.length() {
  754. 754● report = report +
  755. 755 "| " +
  756. 756● (i + 1).to_string() +
  757. 757 " | " +
  758. 758 result.top_candidates[i].0 +
  759. 759 " | " +
  760. 760● (result.top_candidates[i].1 * 100.0).to_string() +
  761. 761 "% |\n"
  762. 762 }
  763. 763 }
  764. 764
  765. 765 report
  766. 766}