image.vision\ocr\robustness_enhancement.mbt

86.5% · 166 / 192 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/robustness_enhancement
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 扫描质量自适应与鲁棒性增强(v12.24.0 P3 鲁棒性)
  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 ScanQualityLevel {
  15. 15 Excellent // 优秀:可直接识别
  16. 16 Good // 良好:轻微预处理即可
  17. 17 Fair // 一般:需要增强处理
  18. 18 Poor // 较差:需要重度预处理
  19. 19 VeryPoor // 很差:可能无法识别
  20. 20}
  21. 21
  22. 22///|
  23. 23pub extend ScanQualityLevel with @debug.Debug::{to_repr}
  24. 24
  25. 25///|
  26. 26pub extend ScanQualityLevel with Eq::{not_equal, equal}
  27. 27
  28. 28///|
  29. 29/// 自适应预处理配置
  30. 30#derive(Eq, @debug.Debug)
  31. 31pub(all) struct AdaptivePreprocessConfig {
  32. 32 quality_level : ScanQualityLevel
  33. 33 denoise_strength : Int32 // 去噪强度 0-5
  34. 34 contrast_enhance : Double // 对比度增强倍数 1.0-3.0
  35. 35 binarization_method : String // "otsu" / "adaptive" / "sauvola"
  36. 36 deskew_enabled : Bool // 是否启用倾斜校正
  37. 37 sharpen_enabled : Bool // 是否启用锐化
  38. 38 morph_open_enabled : Bool // 是否启用形态学开运算
  39. 39 morph_close_enabled : Bool // 是否启用形态学闭运算
  40. 40 recommended_dpi : Int32 // 推荐 DPI
  41. 41}
  42. 42
  43. 43///|
  44. 44pub extend AdaptivePreprocessConfig with Eq::{not_equal, equal}
  45. 45
  46. 46///|
  47. 47pub extend AdaptivePreprocessConfig with @debug.Debug::{to_repr}
  48. 48
  49. 49///|
  50. 50/// 畸变类型
  51. 51/// `#non_exhaustive` 表示未来可能添加新构造器
  52. 52#derive(Eq, @debug.Debug)
  53. 53#non_exhaustive
  54. 54pub(all) enum DistortionType {
  55. 55 Skew // 倾斜
  56. 56 Perspective // 透视畸变
  57. 57 Barrel // 桶形畸变
  58. 58 Pincushion // 枕形畸变
  59. 59 UnevenLighting // 光照不均
  60. 60 Blur // 模糊
  61. 61 Noise // 噪声
  62. 62 Unknown
  63. 63}
  64. 64
  65. 65///|
  66. 66pub extend DistortionType with @debug.Debug::{to_repr}
  67. 67
  68. 68///|
  69. 69pub extend DistortionType with Eq::{not_equal, equal}
  70. 70
  71. 71///|
  72. 72/// 畸变检测结果
  73. 73#derive(Eq, @debug.Debug)
  74. 74pub(all) struct DistortionDetectionResult {
  75. 75 distortion_type : DistortionType
  76. 76 severity : Double // 0.0-1.0
  77. 77 angle : Double // 倾斜角度(度)
  78. 78 confidence : Double
  79. 79 correction_params : Array[(String, Double)]
  80. 80}
  81. 81
  82. 82///|
  83. 83pub extend DistortionDetectionResult with Eq::{not_equal, equal}
  84. 84
  85. 85///|
  86. 86pub extend DistortionDetectionResult with @debug.Debug::{to_repr}
  87. 87
  88. 88///|
  89. 89/// 复杂版面类型
  90. 90/// `#non_exhaustive` 表示未来可能添加新构造器
  91. 91#derive(Eq, @debug.Debug)
  92. 92#non_exhaustive
  93. 93pub(all) enum ComplexLayoutType {
  94. 94 SingleColumn
  95. 95 DoubleColumn
  96. 96 TripleColumn
  97. 97 MultiColumnWithFloats
  98. 98 MixedLayout
  99. 99 TableHeavy
  100. 100 ImageHeavy
  101. 101 Unknown
  102. 102}
  103. 103
  104. 104///|
  105. 105pub extend ComplexLayoutType with @debug.Debug::{to_repr}
  106. 106
  107. 107///|
  108. 108pub extend ComplexLayoutType with Eq::{not_equal, equal}
  109. 109
  110. 110///|
  111. 111/// 复杂版面分析结果
  112. 112#derive(Eq, @debug.Debug)
  113. 113pub(all) struct ComplexLayoutAnalysis {
  114. 114 layout_type : ComplexLayoutType
  115. 115 num_columns : Int32
  116. 116 has_floating_elements : Bool
  117. 117 has_cross_page_elements : Bool
  118. 118 column_boundaries : Array[Int32]
  119. 119 reading_order_strategy : String
  120. 120 confidence : Double
  121. 121}
  122. 122
  123. 123///|
  124. 124pub extend ComplexLayoutAnalysis with Eq::{not_equal, equal}
  125. 125
  126. 126///|
  127. 127pub extend ComplexLayoutAnalysis with @debug.Debug::{to_repr}
  128. 128
  129. 129///|
  130. 130/// 鲁棒性评估报告
  131. 131#derive(Eq, @debug.Debug)
  132. 132pub(all) struct RobustnessReport {
  133. 133 overall_score : Double
  134. 134 quality_score : Double
  135. 135 distortion_score : Double
  136. 136 layout_complexity_score : Double
  137. 137 noise_resistance_score : Double
  138. 138 recommendations : Array[String]
  139. 139 estimated_accuracy : Double
  140. 140 processing_recommendation : String
  141. 141}
  142. 142
  143. 143///|
  144. 144pub extend RobustnessReport with Eq::{not_equal, equal}
  145. 145
  146. 146///|
  147. 147pub extend RobustnessReport with @debug.Debug::{to_repr}
  148. 148
  149. 149///|
  150. 150/// 根据扫描质量自动选择预处理配置
  151. 151pub fn select_adaptive_config(
  152. 152 quality : ScanQuality,
  153. 153) -> AdaptivePreprocessConfig raise @types.LoadError {
  154. 154 // 输入验证
  155. 155● if quality.overall_score < 0.0 || quality.overall_score > 100.0 {
  156. 156● raise @types.LoadError::DecodeFailed(
  157. 157 "select_adaptive_config: 质量评分必须在0-100之间",
  158. 158 )
  159. 159 }
  160. 160 let score = quality.overall_score
  161. 161 if score >= 90.0 {
  162. 162● AdaptivePreprocessConfig::{
  163. 163 quality_level: ScanQualityLevel::Excellent,
  164. 164 denoise_strength: 1,
  165. 165 contrast_enhance: 1.0,
  166. 166 binarization_method: "otsu",
  167. 167 deskew_enabled: false,
  168. 168 sharpen_enabled: false,
  169. 169 morph_open_enabled: false,
  170. 170 morph_close_enabled: false,
  171. 171 recommended_dpi: 200,
  172. 172 }
  173. 173● } else if score >= 75.0 {
  174. 174● AdaptivePreprocessConfig::{
  175. 175 quality_level: ScanQualityLevel::Good,
  176. 176 denoise_strength: 2,
  177. 177 contrast_enhance: 1.2,
  178. 178 binarization_method: "otsu",
  179. 179 deskew_enabled: true,
  180. 180 sharpen_enabled: false,
  181. 181 morph_open_enabled: false,
  182. 182 morph_close_enabled: true,
  183. 183 recommended_dpi: 250,
  184. 184 }
  185. 185● } else if score >= 60.0 {
  186. 186● AdaptivePreprocessConfig::{
  187. 187 quality_level: ScanQualityLevel::Fair,
  188. 188 denoise_strength: 3,
  189. 189 contrast_enhance: 1.5,
  190. 190 binarization_method: "adaptive",
  191. 191 deskew_enabled: true,
  192. 192 sharpen_enabled: true,
  193. 193 morph_open_enabled: true,
  194. 194 morph_close_enabled: true,
  195. 195 recommended_dpi: 300,
  196. 196 }
  197. 197● } else if score >= 40.0 {
  198. 198● AdaptivePreprocessConfig::{
  199. 199 quality_level: ScanQualityLevel::Poor,
  200. 200 denoise_strength: 4,
  201. 201 contrast_enhance: 2.0,
  202. 202 binarization_method: "sauvola",
  203. 203 deskew_enabled: true,
  204. 204 sharpen_enabled: true,
  205. 205 morph_open_enabled: true,
  206. 206 morph_close_enabled: true,
  207. 207 recommended_dpi: 400,
  208. 208 }
  209. 209 } else {
  210. 210● AdaptivePreprocessConfig::{
  211. 211 quality_level: ScanQualityLevel::VeryPoor,
  212. 212 denoise_strength: 5,
  213. 213 contrast_enhance: 2.5,
  214. 214 binarization_method: "sauvola",
  215. 215 deskew_enabled: true,
  216. 216 sharpen_enabled: true,
  217. 217 morph_open_enabled: true,
  218. 218 morph_close_enabled: true,
  219. 219 recommended_dpi: 600,
  220. 220 }
  221. 221 }
  222. 222}
  223. 223
  224. 224///|
  225. 225/// 检测倾斜角度(基于霍夫变换的简化版)
  226. 226pub fn detect_skew_angle_robust(
  227. 227 binary_img : @types.Image,
  228. 228) -> Double raise @types.LoadError {
  229. 229 // 输入验证
  230. 230● if binary_img.width <= 0 || binary_img.height <= 0 {
  231. 231● raise @types.LoadError::DecodeFailed(
  232. 232 "detect_skew_angle_robust: 图像尺寸必须大于0",
  233. 233 )
  234. 234 }
  235. 235 if binary_img.channels != 1 {
  236. 236● raise @types.LoadError::DecodeFailed(
  237. 237 "detect_skew_angle_robust: 仅支持单通道二值图",
  238. 238 )
  239. 239 }
  240. 240 let expected_size = binary_img.width * binary_img.height
  241. 241● if binary_img.data.length() != expected_size {
  242. 242● raise @types.LoadError::DecodeFailed(
  243. 243 "detect_skew_angle_robust: 数据大小不匹配,期望 " +
  244. 244● expected_size.to_string() +
  245. 245 ",实际 " +
  246. 246● binary_img.data.length().to_string(),
  247. 247 )
  248. 248 }
  249. 249 let w = binary_img.width
  250. 250 let h = binary_img.height
  251. 251 // 简化版:基于文本行的倾斜检测
  252. 252 // 计算每行的黑色像素重心
  253. 253 let mut total_x = 0
  254. 254 let mut total_y = 0
  255. 255 let mut count = 0
  256. 256 for y in 0..<h {
  257. 257● let mut row_black = 0
  258. 258 let mut row_x_sum = 0
  259. 259 for x in 0..<w {
  260. 260● if binary_img.data[y * w + x].to_int() < 128 {
  261. 261● row_black += 1
  262. 262 row_x_sum += x
  263. 263 }
  264. 264 }
  265. 265 if row_black > w / 10 {
  266. 266● let center_x = row_x_sum / row_black
  267. 267 total_x += center_x
  268. 268 total_y += y
  269. 269 count += 1
  270. 270 }
  271. 271 }
  272. 272 if count < 2 {
  273. 273● return 0.0
  274. 274 }
  275. 275 // 线性回归计算倾斜角度
  276. 276● let _ = total_x.to_double() / count.to_double()
  277. 277● let _ = total_y.to_double() / count.to_double()
  278. 278 let numerator = 0.0
  279. 279● ignore(numerator)
  280. 280 let denominator = 0.0
  281. 281● ignore(denominator)
  282. 282 // 简化:用首尾两行的重心差计算角度
  283. 283 let mut first_y = h
  284. 284 let mut first_x = 0
  285. 285 let mut last_y = 0
  286. 286 let mut last_x = 0
  287. 287 for y in 0..<h {
  288. 288● let mut row_black = 0
  289. 289 let mut row_x_sum = 0
  290. 290 for x in 0..<w {
  291. 291● if binary_img.data[y * w + x].to_int() < 128 {
  292. 292● row_black += 1
  293. 293 row_x_sum += x
  294. 294 }
  295. 295 }
  296. 296 if row_black > w / 10 {
  297. 297● let center_x = row_x_sum / row_black
  298. 298 if y < first_y {
  299. 299● first_y = y
  300. 300 first_x = center_x
  301. 301 }
  302. 302 if y > last_y {
  303. 303● last_y = y
  304. 304 last_x = center_x
  305. 305 }
  306. 306 }
  307. 307 }
  308. 308 if last_y - first_y > 0 {
  309. 309● let angle_rad = (last_x - first_x).to_double() /
  310. 310● (last_y - first_y).to_double()
  311. 311 let angle_deg = angle_rad * 57.2958 // rad to deg
  312. 312 if angle_deg > 45.0 {
  313. 313● 90.0 - angle_deg
  314. 314● } else if angle_deg < -45.0 {
  315. 315● -90.0 - angle_deg
  316. 316 } else {
  317. 317● angle_deg
  318. 318 }
  319. 319 } else {
  320. 320○ 0.0
  321. 321 }
  322. 322}
  323. 323
  324. 324///|
  325. 325/// 检测畸变类型和严重程度
  326. 326pub fn detect_distortions(
  327. 327 img : @types.Image,
  328. 328) -> Array[DistortionDetectionResult] raise @types.LoadError {
  329. 329 // 输入验证
  330. 330● if img.width <= 0 || img.height <= 0 {
  331. 331● raise @types.LoadError::DecodeFailed(
  332. 332 "detect_distortions: 图像尺寸必须大于0",
  333. 333 )
  334. 334 }
  335. 335 if img.channels < 1 || img.channels > 4 {
  336. 336● raise @types.LoadError::DecodeFailed(
  337. 337 "detect_distortions: 通道数必须在1-4之间",
  338. 338 )
  339. 339 }
  340. 340 let expected_size = img.width * img.height * img.channels
  341. 341● if img.data.length() != expected_size {
  342. 342● raise @types.LoadError::DecodeFailed(
  343. 343 "detect_distortions: 数据大小不匹配,期望 " +
  344. 344● expected_size.to_string() +
  345. 345 ",实际 " +
  346. 346● img.data.length().to_string(),
  347. 347 )
  348. 348 }
  349. 349 let results : Array[DistortionDetectionResult] = []
  350. 350 let w = img.width
  351. 351 let h = img.height
  352. 352
  353. 353 // 1. 检测噪声
  354. 354 let mut noise_count = 0
  355. 355 let mut total_pixels = 0
  356. 356 for y in 1..<(h - 1) {
  357. 357● for x in 1..<(w - 1) {
  358. 358● let idx = y * w + x
  359. 359● let center = img.data[idx].to_int()
  360. 360 let neighbors = [
  361. 361● img.data[idx - 1].to_int(),
  362. 362● img.data[idx + 1].to_int(),
  363. 363● img.data[idx - w].to_int(),
  364. 364● img.data[idx + w].to_int(),
  365. 365 ]
  366. 366 let mut neighbor_sum = 0
  367. 367 for n in neighbors {
  368. 368● neighbor_sum += n
  369. 369 }
  370. 370 let neighbor_avg = neighbor_sum / 4
  371. 371● if (center - neighbor_avg).abs() > 50 {
  372. 372● noise_count += 1
  373. 373 }
  374. 374 total_pixels += 1
  375. 375 }
  376. 376 }
  377. 377 let noise_ratio = if total_pixels > 0 {
  378. 378● noise_count.to_double() / total_pixels.to_double()
  379. 379 } else {
  380. 380○ 0.0
  381. 381 }
  382. 382 if noise_ratio > 0.01 {
  383. 383● results.push(DistortionDetectionResult::{
  384. 384 distortion_type: DistortionType::Noise,
  385. 385 severity: if noise_ratio > 0.1 {
  386. 386● 0.8
  387. 387● } else if noise_ratio > 0.05 {
  388. 388● 0.5
  389. 389 } else {
  390. 390○ 0.2
  391. 391 },
  392. 392 angle: 0.0,
  393. 393 confidence: 0.8,
  394. 394 correction_params: [
  395. 395 (
  396. 396 "denoise_strength",
  397. 397 if noise_ratio > 0.1 {
  398. 398● 5.0
  399. 399● } else if noise_ratio > 0.05 {
  400. 400● 3.0
  401. 401 } else {
  402. 402○ 2.0
  403. 403 },
  404. 404 ),
  405. 405 ],
  406. 406 })
  407. 407 }
  408. 408
  409. 409 // 2. 检测模糊(拉普拉斯方差)
  410. 410 let mut laplacian_sum = 0.0
  411. 411 let mut laplacian_count = 0
  412. 412 for y in 1..<(h - 1) {
  413. 413● for x in 1..<(w - 1) {
  414. 414● let idx = y * w + x
  415. 415● let center = img.data[idx].to_double()
  416. 416 let lap = 4.0 * center -
  417. 417● img.data[idx - 1].to_double() -
  418. 418● img.data[idx + 1].to_double() -
  419. 419● img.data[idx - w].to_double() -
  420. 420● img.data[idx + w].to_double()
  421. 421 laplacian_sum += lap * lap
  422. 422 laplacian_count += 1
  423. 423 }
  424. 424 }
  425. 425 let laplacian_var = if laplacian_count > 0 {
  426. 426● laplacian_sum / laplacian_count.to_double()
  427. 427 } else {
  428. 428○ 0.0
  429. 429 }
  430. 430 if laplacian_var < 100.0 {
  431. 431● results.push(DistortionDetectionResult::{
  432. 432 distortion_type: DistortionType::Blur,
  433. 433 severity: if laplacian_var < 20.0 {
  434. 434● 0.9
  435. 435○ } else if laplacian_var < 50.0 {
  436. 436○ 0.6
  437. 437 } else {
  438. 438○ 0.3
  439. 439 },
  440. 440 angle: 0.0,
  441. 441 confidence: 0.75,
  442. 442 correction_params: [
  443. 443 (
  444. 444 "sharpen_strength",
  445. 445 if laplacian_var < 20.0 {
  446. 446● 3.0
  447. 447○ } else if laplacian_var < 50.0 {
  448. 448○ 2.0
  449. 449 } else {
  450. 450○ 1.0
  451. 451 },
  452. 452 ),
  453. 453 ],
  454. 454 })
  455. 455 }
  456. 456
  457. 457 // 3. 检测光照不均(四角亮度差)
  458. 458 if w > 20 && h > 20 {
  459. 459● let regions = [
  460. 460 (10, 10),
  461. 461 (w - 10, 10),
  462. 462 (10, h - 10),
  463. 463 (w - 10, h - 10),
  464. 464 (w / 2, h / 2),
  465. 465 ]
  466. 466 let brightnesses : Array[Double] = []
  467. 467 for _tup0 in regions {
  468. 468● let (rx, ry) = _tup0
  469. 469 let mut sum = 0.0
  470. 470 let mut count = 0
  471. 471 for dy in 0..<10 {
  472. 472● for dx in 0..<10 {
  473. 473● if rx + dx < w && ry + dy < h {
  474. 474● sum += img.data[(ry + dy) * w + (rx + dx)].to_double()
  475. 475 count += 1
  476. 476 }
  477. 477 }
  478. 478 }
  479. 479 if count > 0 {
  480. 480● brightnesses.push(sum / count.to_double())
  481. 481 }
  482. 482 }
  483. 483● if brightnesses.length() >= 4 {
  484. 484● let mut max_b = brightnesses[0]
  485. 485 let mut min_b = brightnesses[0]
  486. 486 for b in brightnesses {
  487. 487● if b > max_b {
  488. 488● max_b = b
  489. 489 }
  490. 490 if b < min_b {
  491. 491○ min_b = b
  492. 492 }
  493. 493 }
  494. 494 let brightness_diff = max_b - min_b
  495. 495 if brightness_diff > 50.0 {
  496. 496● results.push(DistortionDetectionResult::{
  497. 497 distortion_type: DistortionType::UnevenLighting,
  498. 498 severity: if brightness_diff > 100.0 {
  499. 499● 0.8
  500. 500○ } else if brightness_diff > 75.0 {
  501. 501○ 0.5
  502. 502 } else {
  503. 503○ 0.3
  504. 504 },
  505. 505 angle: 0.0,
  506. 506 confidence: 0.7,
  507. 507 correction_params: [
  508. 508 ("adaptive_threshold", 1.0),
  509. 509 ("contrast_enhance", 1.5),
  510. 510 ],
  511. 511 })
  512. 512 }
  513. 513 }
  514. 514 }
  515. 515
  516. 516 results
  517. 517}
  518. 518
  519. 519///|
  520. 520/// 分析复杂版面
  521. 521pub fn analyze_complex_layout(
  522. 522 text_blocks : Array[TextBlock],
  523. 523 page_width : Int32,
  524. 524 page_height : Int32,
  525. 525) -> ComplexLayoutAnalysis {
  526. 526● ignore(page_height)
  527. 527● if text_blocks.length() == 0 {
  528. 528● return ComplexLayoutAnalysis::{
  529. 529 layout_type: ComplexLayoutType::Unknown,
  530. 530 num_columns: 1,
  531. 531 has_floating_elements: false,
  532. 532 has_cross_page_elements: false,
  533. 533 column_boundaries: [],
  534. 534 reading_order_strategy: "default",
  535. 535 confidence: 0.0,
  536. 536 }
  537. 537 }
  538. 538
  539. 539 // 统计水平覆盖范围
  540. 540 let mut full_width_count = 0
  541. 541 let mut left_count = 0
  542. 542 let mut right_count = 0
  543. 543 let mid_x = page_width / 2
  544. 544
  545. 545 for block in text_blocks {
  546. 546● let center = block.x + block.width / 2
  547. 547● if block.width.to_double() > page_width.to_double() * 0.7 {
  548. 548● full_width_count += 1
  549. 549● } else if center < mid_x {
  550. 550● left_count += 1
  551. 551 } else {
  552. 552● right_count += 1
  553. 553 }
  554. 554 }
  555. 555
  556. 556● let total = text_blocks.length().to_double()
  557. 557● let full_ratio = full_width_count.to_double() / total
  558. 558● let left_ratio = left_count.to_double() / total
  559. 559● let right_ratio = right_count.to_double() / total
  560. 560
  561. 561 let layout_type = if full_ratio > 0.8 {
  562. 562● ComplexLayoutType::SingleColumn
  563. 563● } else if left_ratio > 0.3 && right_ratio > 0.3 && full_ratio < 0.2 {
  564. 564● ComplexLayoutType::DoubleColumn
  565. 565● } else if full_ratio > 0.2 && (left_ratio > 0.2 || right_ratio > 0.2) {
  566. 566● ComplexLayoutType::MixedLayout
  567. 567 } else {
  568. 568● ComplexLayoutType::SingleColumn
  569. 569 }
  570. 570
  571. 571● let num_columns = match layout_type {
  572. 572● ComplexLayoutType::DoubleColumn => 2
  573. 573○ ComplexLayoutType::TripleColumn => 3
  574. 574○ ComplexLayoutType::MultiColumnWithFloats => 3
  575. 575● _ => 1
  576. 576 }
  577. 577
  578. 578 let has_floats = full_ratio > 0.1 && full_ratio < 0.5
  579. 579
  580. 580● let reading_order_strategy = match layout_type {
  581. 581● ComplexLayoutType::SingleColumn => "top_to_bottom"
  582. 582● ComplexLayoutType::DoubleColumn => "left_column_first"
  583. 583○ ComplexLayoutType::TripleColumn => "column_by_column"
  584. 584● ComplexLayoutType::MixedLayout => "adaptive"
  585. 585○ _ => "default"
  586. 586 }
  587. 587
  588. 588 let boundaries : Array[Int32] = []
  589. 589● boundaries.push(0)
  590. 590 if num_columns >= 2 {
  591. 591● boundaries.push(page_width / 2 - 20)
  592. 592● boundaries.push(page_width / 2 + 20)
  593. 593 }
  594. 594● boundaries.push(page_width)
  595. 595
  596. 596 ComplexLayoutAnalysis::{
  597. 597 layout_type,
  598. 598 num_columns,
  599. 599 has_floating_elements: has_floats,
  600. 600 has_cross_page_elements: false,
  601. 601 column_boundaries: boundaries,
  602. 602 reading_order_strategy,
  603. 603 confidence: 0.75,
  604. 604 }
  605. 605}
  606. 606
  607. 607///|
  608. 608/// 生成鲁棒性评估报告
  609. 609pub fn generate_robustness_report(
  610. 610 quality : ScanQuality,
  611. 611 distortions : Array[DistortionDetectionResult],
  612. 612 layout : ComplexLayoutAnalysis,
  613. 613) -> RobustnessReport {
  614. 614 // 质量分数
  615. 615● let quality_score = quality.overall_score / 100.0
  616. 616
  617. 617 // 畸变分数(畸变越少分数越高)
  618. 618 let mut distortion_penalty = 0.0
  619. 619 for d in distortions {
  620. 620● distortion_penalty += d.severity * 0.2
  621. 621 }
  622. 622 let distortion_score = if 1.0 - distortion_penalty > 0 {
  623. 623● 1.0 - distortion_penalty
  624. 624 } else {
  625. 625○ 0.0
  626. 626 }
  627. 627
  628. 628 // 版面复杂度分数(越简单分数越高)
  629. 629● let layout_score = match layout.layout_type {
  630. 630● ComplexLayoutType::SingleColumn => 1.0
  631. 631● ComplexLayoutType::DoubleColumn => 0.8
  632. 632○ ComplexLayoutType::TripleColumn => 0.6
  633. 633○ ComplexLayoutType::MixedLayout => 0.5
  634. 634○ ComplexLayoutType::MultiColumnWithFloats => 0.4
  635. 635● _ => 0.7
  636. 636 }
  637. 637
  638. 638 // 噪声抵抗分数
  639. 639 let mut noise_severity = 0.0
  640. 640 for d in distortions {
  641. 641● if d.distortion_type == DistortionType::Noise {
  642. 642● noise_severity = d.severity
  643. 643 }
  644. 644 }
  645. 645 let noise_score = 1.0 - noise_severity
  646. 646
  647. 647 // 综合分数
  648. 648 let overall = quality_score * 0.3 +
  649. 649 distortion_score * 0.3 +
  650. 650 layout_score * 0.2 +
  651. 651 noise_score * 0.2
  652. 652
  653. 653 // 建议
  654. 654 let recommendations : Array[String] = []
  655. 655 if quality_score < 0.6 {
  656. 656● recommendations.push("建议提高扫描分辨率至 300 DPI 以上")
  657. 657 }
  658. 658 if noise_severity > 0.3 {
  659. 659● recommendations.push("建议启用强去噪处理(中值滤波+NLM)")
  660. 660 }
  661. 661 if layout.num_columns > 1 {
  662. 662● recommendations.push(
  663. 663 "检测到多栏布局,建议使用分栏阅读顺序",
  664. 664 )
  665. 665 }
  666. 666 if distortion_penalty > 0.3 {
  667. 667○ recommendations.push(
  668. 668 "检测到严重畸变,建议启用完整预处理流水线",
  669. 669 )
  670. 670 }
  671. 671● if recommendations.length() == 0 {
  672. 672● recommendations.push("文档质量良好,可使用标准预处理流程")
  673. 673 }
  674. 674
  675. 675 // 预估准确率
  676. 676 let estimated_accuracy = overall * 0.95 + 0.05
  677. 677
  678. 678 let processing_recommendation = if overall > 0.8 {
  679. 679● "标准处理流程"
  680. 680● } else if overall > 0.6 {
  681. 681● "增强处理流程"
  682. 682 } else {
  683. 683○ "重度预处理+人工复核"
  684. 684 }
  685. 685
  686. 686 RobustnessReport::{
  687. 687 overall_score: overall,
  688. 688 quality_score,
  689. 689 distortion_score,
  690. 690 layout_complexity_score: layout_score,
  691. 691 noise_resistance_score: noise_score,
  692. 692 recommendations,
  693. 693 estimated_accuracy,
  694. 694 processing_recommendation,
  695. 695 }
  696. 696}
  697. 697
  698. 698///|
  699. 699/// 生成鲁棒性报告文本
  700. 700pub fn robustness_report_to_string(report : RobustnessReport) -> String {
  701. 701● let mut output = "## OCR 鲁棒性评估报告\n\n"
  702. 702 output = output + "### 综合评分\n\n"
  703. 703 output = output + "| 指标 | 分数 |\n"
  704. 704 output = output + "|------|------|\n"
  705. 705 output = output +
  706. 706 "| **综合评分** | **" +
  707. 707● (report.overall_score * 100.0).to_string() +
  708. 708 "/100** |\n"
  709. 709 output = output +
  710. 710 "| 扫描质量 | " +
  711. 711● (report.quality_score * 100.0).to_string() +
  712. 712 "/100 |\n"
  713. 713 output = output +
  714. 714 "| 畸变控制 | " +
  715. 715● (report.distortion_score * 100.0).to_string() +
  716. 716 "/100 |\n"
  717. 717 output = output +
  718. 718 "| 版面复杂度 | " +
  719. 719● (report.layout_complexity_score * 100.0).to_string() +
  720. 720 "/100 |\n"
  721. 721 output = output +
  722. 722 "| 噪声抵抗 | " +
  723. 723● (report.noise_resistance_score * 100.0).to_string() +
  724. 724 "/100 |\n\n"
  725. 725 output = output +
  726. 726 "### 预估识别准确率: " +
  727. 727● (report.estimated_accuracy * 100.0).to_string() +
  728. 728 "%\n\n"
  729. 729 output = output +
  730. 730 "### 推荐处理方式: " +
  731. 731 report.processing_recommendation +
  732. 732 "\n\n"
  733. 733 output = output + "### 改进建议\n\n"
  734. 734● for i in 0..<report.recommendations.length() {
  735. 735● output = output +
  736. 736● (i + 1).to_string() +
  737. 737 ". " +
  738. 738 report.recommendations[i] +
  739. 739 "\n"
  740. 740 }
  741. 741 output
  742. 742}