image.vision\ocr\scan_document_ocr.mbt

93% · 305 / 328 points · 920 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/scan_document_ocr
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 扫描版文档 OCR 增强(v12.16.0)
  7. 7// 扫描文档预处理、版面分析、质量评估、批量处理、多格式输出
  8. 8
  9. 9///|
  10. 10/// 扫描文档配置
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct ScanOCRConfig {
  13. 13 language : String // "digit" / "english" / "chinese" / "multilingual"
  14. 14 dpi : Int32 // 扫描 DPI(通常 300)
  15. 15 deskew : Bool // 是否自动倾斜校正
  16. 16 denoise : Bool // 是否去噪
  17. 17 binarization_method : String // "otsu" / "adaptive" / "sauvola"
  18. 18 layout_analysis : Bool // 是否进行版面分析
  19. 19 confidence_threshold : Double // 置信度阈值
  20. 20}
  21. 21
  22. 22///|
  23. 23pub extend ScanOCRConfig with Eq::{not_equal, equal}
  24. 24
  25. 25///|
  26. 26pub extend ScanOCRConfig with @debug.Debug::{to_repr}
  27. 27
  28. 28///|
  29. 29/// 创建默认扫描 OCR 配置
  30. 30pub fn scan_ocr_default_config() -> ScanOCRConfig {
  31. 31● ScanOCRConfig::{
  32. 32 language: "english",
  33. 33 dpi: 300,
  34. 34 deskew: true,
  35. 35 denoise: true,
  36. 36 binarization_method: "otsu",
  37. 37 layout_analysis: true,
  38. 38 confidence_threshold: 0.6,
  39. 39 }
  40. 40}
  41. 41
  42. 42///|
  43. 43/// 扫描质量评估结果
  44. 44#derive(Eq, @debug.Debug)
  45. 45pub(all) struct ScanQuality {
  46. 46 brightness : Double // 平均亮度(0-255)
  47. 47 contrast : Double // 对比度(标准差)
  48. 48 sharpness : Double // 锐度(拉普拉斯方差)
  49. 49 noise_level : Double // 噪声水平
  50. 50 skew_angle : Double // 倾斜角度(度)
  51. 51 overall_score : Double // 综合质量评分(0-100)
  52. 52 issues : Array[String] // 检测到的问题
  53. 53}
  54. 54
  55. 55///|
  56. 56pub extend ScanQuality with Eq::{not_equal, equal}
  57. 57
  58. 58///|
  59. 59pub extend ScanQuality with @debug.Debug::{to_repr}
  60. 60
  61. 61///|
  62. 62/// 文本块(版面分析结果)
  63. 63#derive(Eq, @debug.Debug)
  64. 64pub(all) struct TextBlock {
  65. 65 x : Int32
  66. 66 y : Int32
  67. 67 width : Int32
  68. 68 height : Int32
  69. 69 block_type : String // "text" / "title" / "table" / "image" / "list"
  70. 70 text : String
  71. 71 confidence : Double
  72. 72 reading_order : Int32
  73. 73}
  74. 74
  75. 75///|
  76. 76pub extend TextBlock with Eq::{not_equal, equal}
  77. 77
  78. 78///|
  79. 79pub extend TextBlock with @debug.Debug::{to_repr}
  80. 80
  81. 81///|
  82. 82/// OCR 页面结果
  83. 83#derive(Eq, @debug.Debug)
  84. 84pub(all) struct OCRPageResult {
  85. 85 page_number : Int32
  86. 86 width : Int32
  87. 87 height : Int32
  88. 88 blocks : Array[TextBlock]
  89. 89 full_text : String
  90. 90 average_confidence : Double
  91. 91 processing_time_ms : Double
  92. 92}
  93. 93
  94. 94///|
  95. 95pub extend OCRPageResult with Eq::{not_equal, equal}
  96. 96
  97. 97///|
  98. 98pub extend OCRPageResult with @debug.Debug::{to_repr}
  99. 99
  100. 100///|
  101. 101/// 评估扫描图像质量
  102. 102pub fn evaluate_scan_quality(
  103. 103 img : @types.Image,
  104. 104) -> ScanQuality raise @types.LoadError {
  105. 105 // 输入验证
  106. 106● if img.width <= 0 || img.height <= 0 {
  107. 107● raise @types.LoadError::DecodeFailed(
  108. 108 "evaluate_scan_quality: 图像尺寸必须大于0",
  109. 109 )
  110. 110 }
  111. 111 if img.channels < 1 || img.channels > 4 {
  112. 112● raise @types.LoadError::DecodeFailed(
  113. 113 "evaluate_scan_quality: 通道数必须在1-4之间",
  114. 114 )
  115. 115 }
  116. 116 let expected_size = img.width * img.height * img.channels
  117. 117● if img.data.length() != expected_size {
  118. 118● raise @types.LoadError::DecodeFailed(
  119. 119 "evaluate_scan_quality: 数据大小不匹配,期望 " +
  120. 120● expected_size.to_string() +
  121. 121 ",实际 " +
  122. 122● img.data.length().to_string(),
  123. 123 )
  124. 124 }
  125. 125 let w = img.width
  126. 126 let h = img.height
  127. 127 let channels = img.channels
  128. 128 // 计算亮度和对比度
  129. 129 let mut sum = 0.0
  130. 130 let mut sum_sq = 0.0
  131. 131● let total = (w * h).to_double()
  132. 132 for y in 0..<h {
  133. 133● for x in 0..<w {
  134. 134● let idx = (y * w + x) * channels
  135. 135 let gray = if channels >= 3 {
  136. 136● 0.299 * img.data[idx].to_double() +
  137. 137● 0.587 * img.data[idx + 1].to_double() +
  138. 138● 0.114 * img.data[idx + 2].to_double()
  139. 139 } else {
  140. 140● img.data[idx].to_double()
  141. 141 }
  142. 142 sum += gray
  143. 143 sum_sq += gray * gray
  144. 144 }
  145. 145 }
  146. 146 let brightness = sum / total
  147. 147 let variance = sum_sq / total - brightness * brightness
  148. 148● let contrast = if variance > 0.0 { variance.sqrt() } else { 0.0 }
  149. 149 // 计算锐度(拉普拉斯算子简化版)
  150. 150 let mut sharpness_sum = 0.0
  151. 151 let mut sharpness_count = 0
  152. 152 for y in 1..<(h - 1) {
  153. 153● for x in 1..<(w - 1) {
  154. 154● let idx = (y * w + x) * channels
  155. 155 let center = if channels >= 3 {
  156. 156● 0.299 * img.data[idx].to_double() +
  157. 157● 0.587 * img.data[idx + 1].to_double() +
  158. 158● 0.114 * img.data[idx + 2].to_double()
  159. 159 } else {
  160. 160● img.data[idx].to_double()
  161. 161 }
  162. 162 let up = if channels >= 3 {
  163. 163● 0.299 * img.data[((y - 1) * w + x) * channels].to_double() +
  164. 164● 0.587 * img.data[((y - 1) * w + x) * channels + 1].to_double() +
  165. 165● 0.114 * img.data[((y - 1) * w + x) * channels + 2].to_double()
  166. 166 } else {
  167. 167● img.data[((y - 1) * w + x) * channels].to_double()
  168. 168 }
  169. 169 let down = if channels >= 3 {
  170. 170● 0.299 * img.data[((y + 1) * w + x) * channels].to_double() +
  171. 171● 0.587 * img.data[((y + 1) * w + x) * channels + 1].to_double() +
  172. 172● 0.114 * img.data[((y + 1) * w + x) * channels + 2].to_double()
  173. 173 } else {
  174. 174● img.data[((y + 1) * w + x) * channels].to_double()
  175. 175 }
  176. 176 let left = if channels >= 3 {
  177. 177● 0.299 * img.data[(y * w + x - 1) * channels].to_double() +
  178. 178● 0.587 * img.data[(y * w + x - 1) * channels + 1].to_double() +
  179. 179● 0.114 * img.data[(y * w + x - 1) * channels + 2].to_double()
  180. 180 } else {
  181. 181● img.data[(y * w + x - 1) * channels].to_double()
  182. 182 }
  183. 183 let right = if channels >= 3 {
  184. 184● 0.299 * img.data[(y * w + x + 1) * channels].to_double() +
  185. 185● 0.587 * img.data[(y * w + x + 1) * channels + 1].to_double() +
  186. 186● 0.114 * img.data[(y * w + x + 1) * channels + 2].to_double()
  187. 187 } else {
  188. 188● img.data[(y * w + x + 1) * channels].to_double()
  189. 189 }
  190. 190 let laplacian = 4.0 * center - up - down - left - right
  191. 191 sharpness_sum += laplacian * laplacian
  192. 192 sharpness_count += 1
  193. 193 }
  194. 194 }
  195. 195 let sharpness = if sharpness_count > 0 {
  196. 196● sharpness_sum / sharpness_count.to_double()
  197. 197 } else {
  198. 198● 0.0
  199. 199 }
  200. 200 // 估计噪声水平(基于平坦区域的方差)
  201. 201● let noise_level = if contrast > 0 { (contrast * 0.1).min(50.0) } else { 10.0 }
  202. 202 // 估计倾斜角度(简化版:基于水平投影的方差)
  203. 203 let skew_angle = 0.0 // 简化,实际需要霍夫变换
  204. 204 // 综合质量评分
  205. 205 let mut score = 50.0
  206. 206 // 亮度评分(理想 128)
  207. 207● let brightness_score = 100.0 - (brightness - 128.0).abs() * 0.5
  208. 208 score += brightness_score * 0.2
  209. 209 // 对比度评分(理想 > 50)
  210. 210● let contrast_score = if contrast > 50.0 { 100.0 } else { contrast * 2.0 }
  211. 211 score += contrast_score * 0.3
  212. 212 // 锐度评分
  213. 213● let sharpness_score = if sharpness > 100.0 { 100.0 } else { sharpness }
  214. 214 score += sharpness_score * 0.3
  215. 215 // 噪声评分
  216. 216 let noise_score = if noise_level < 10.0 {
  217. 217● 100.0
  218. 218 } else {
  219. 219● (100.0 - noise_level).max(0.0)
  220. 220 }
  221. 221 score += noise_score * 0.2
  222. 222 // 检测问题
  223. 223 let issues : Array[String] = []
  224. 224 if brightness < 50.0 {
  225. 225● issues.push("图像过暗")
  226. 226 }
  227. 227 if brightness > 200.0 {
  228. 228● issues.push("图像过亮")
  229. 229 }
  230. 230 if contrast < 30.0 {
  231. 231● issues.push("对比度不足")
  232. 232 }
  233. 233 if sharpness < 20.0 {
  234. 234● issues.push("图像模糊")
  235. 235 }
  236. 236 if noise_level > 30.0 {
  237. 237○ issues.push("噪声较高")
  238. 238 }
  239. 239 ScanQuality::{
  240. 240 brightness,
  241. 241 contrast,
  242. 242 sharpness,
  243. 243 noise_level,
  244. 244 skew_angle,
  245. 245● overall_score: score.min(100.0).max(0.0),
  246. 246 issues,
  247. 247 }
  248. 248}
  249. 249
  250. 250///|
  251. 251/// 扫描文档预处理流水线
  252. 252pub fn scan_document_preprocess(
  253. 253 img : @types.Image,
  254. 254 config : ScanOCRConfig,
  255. 255) -> @types.Image raise @types.LoadError {
  256. 256 // 输入验证
  257. 257● if img.width <= 0 || img.height <= 0 {
  258. 258● raise @types.LoadError::DecodeFailed(
  259. 259 "scan_document_preprocess: 图像尺寸必须大于0",
  260. 260 )
  261. 261 }
  262. 262 if img.channels < 1 || img.channels > 4 {
  263. 263● raise @types.LoadError::DecodeFailed(
  264. 264 "scan_document_preprocess: 通道数必须在1-4之间",
  265. 265 )
  266. 266 }
  267. 267 let expected_size = img.width * img.height * img.channels
  268. 268● if img.data.length() != expected_size {
  269. 269● raise @types.LoadError::DecodeFailed(
  270. 270 "scan_document_preprocess: 数据大小不匹配,期望 " +
  271. 271● expected_size.to_string() +
  272. 272 ",实际 " +
  273. 273● img.data.length().to_string(),
  274. 274 )
  275. 275 }
  276. 276 let mut result = img
  277. 277 // 1. 去噪(中值滤波简化版)
  278. 278 if config.denoise {
  279. 279● result = denoise_scan(result)
  280. 280 }
  281. 281 // 2. 对比度增强
  282. 282● result = enhance_contrast_scan(result)
  283. 283 // 3. 二值化
  284. 284● result = match config.binarization_method {
  285. 285● "otsu" => binarize_otsu_scan(result)
  286. 286● "adaptive" => binarize_adaptive_scan(result)
  287. 287● "sauvola" => binarize_sauvola_scan(result)
  288. 288● _ => binarize_otsu_scan(result)
  289. 289 }
  290. 290 result
  291. 291}
  292. 292
  293. 293///|
  294. 294/// 扫描文档去噪(简化版中值滤波)
  295. 295fn denoise_scan(img : @types.Image) -> @types.Image {
  296. 296● let w = img.width
  297. 297 let h = img.height
  298. 298 let channels = img.channels
  299. 299● let out_data : Array[Byte] = Array::make(w * h * channels, b'\x00')
  300. 300 for y in 0..<h {
  301. 301● for x in 0..<w {
  302. 302● let idx = (y * w + x) * channels
  303. 303 for c in 0..<channels {
  304. 304 // 3x3 中值滤波(简化版:取 5 个点的中值)
  305. 305● let values : Array[Int32] = []
  306. 306 // 中心
  307. 307● values.push(img.data[idx + c].to_int())
  308. 308 // 上
  309. 309 if y > 0 {
  310. 310● values.push(img.data[((y - 1) * w + x) * channels + c].to_int())
  311. 311 }
  312. 312 // 下
  313. 313 if y < h - 1 {
  314. 314● values.push(img.data[((y + 1) * w + x) * channels + c].to_int())
  315. 315 }
  316. 316 // 左
  317. 317 if x > 0 {
  318. 318● values.push(img.data[(y * w + x - 1) * channels + c].to_int())
  319. 319 }
  320. 320 // 右
  321. 321 if x < w - 1 {
  322. 322● values.push(img.data[(y * w + x + 1) * channels + c].to_int())
  323. 323 }
  324. 324 // 排序取中值
  325. 325● for i in 0..<values.length() {
  326. 326● for j in 0..<(values.length() - i - 1) {
  327. 327● if values[j] > values[j + 1] {
  328. 328● let temp = values[j]
  329. 329 values[j] = values[j + 1]
  330. 330 values[j + 1] = temp
  331. 331 }
  332. 332 }
  333. 333 }
  334. 334● let median = values[values.length() / 2]
  335. 335● out_data[idx + c] = median.to_byte()
  336. 336 }
  337. 337 }
  338. 338 }
  339. 339 @types.Image::{
  340. 340 width: w,
  341. 341 height: h,
  342. 342 channels,
  343. 343● data: Bytes::from_array(out_data),
  344. 344 }
  345. 345}
  346. 346
  347. 347///|
  348. 348/// 扫描文档对比度增强(直方图拉伸)
  349. 349fn enhance_contrast_scan(img : @types.Image) -> @types.Image {
  350. 350● let w = img.width
  351. 351 let h = img.height
  352. 352 let channels = img.channels
  353. 353 // 计算最小值和最大值(忽略 1% 极值)
  354. 354 let histogram : Array[Int32] = []
  355. 355 for _ in 0..<256 {
  356. 356● histogram.push(0)
  357. 357 }
  358. 358 for y in 0..<h {
  359. 359● for x in 0..<w {
  360. 360● let idx = (y * w + x) * channels
  361. 361 let gray = if channels >= 3 {
  362. 362● (0.299 * img.data[idx].to_double() +
  363. 363● 0.587 * img.data[idx + 1].to_double() +
  364. 364● 0.114 * img.data[idx + 2].to_double()).to_int()
  365. 365 } else {
  366. 366● img.data[idx].to_int()
  367. 367 }
  368. 368 histogram[gray] += 1
  369. 369 }
  370. 370 }
  371. 371 let total = w * h
  372. 372 let lower_count = total / 100
  373. 373 let upper_count = total - lower_count
  374. 374 let mut min_val = 0
  375. 375 let mut max_val = 255
  376. 376 let mut cum = 0
  377. 377 for i in 0..<256 {
  378. 378● cum += histogram[i]
  379. 379 if cum >= lower_count && min_val == 0 {
  380. 380● min_val = i
  381. 381 }
  382. 382 if cum >= upper_count {
  383. 383● max_val = i
  384. 384 break
  385. 385 }
  386. 386 }
  387. 387 // 应用拉伸
  388. 388● let out_data : Array[Byte] = Array::make(w * h * channels, b'\x00')
  389. 389● let range = (max_val - min_val).max(1)
  390. 390 for y in 0..<h {
  391. 391● for x in 0..<w {
  392. 392● let idx = (y * w + x) * channels
  393. 393 for c in 0..<channels {
  394. 394● let val = img.data[idx + c].to_int()
  395. 395● let stretched = ((val - min_val) * 255 / range).min(255).max(0)
  396. 396● out_data[idx + c] = stretched.to_byte()
  397. 397 }
  398. 398 }
  399. 399 }
  400. 400 @types.Image::{
  401. 401 width: w,
  402. 402 height: h,
  403. 403 channels,
  404. 404● data: Bytes::from_array(out_data),
  405. 405 }
  406. 406}
  407. 407
  408. 408///|
  409. 409/// Otsu 二值化
  410. 410fn binarize_otsu_scan(img : @types.Image) -> @types.Image {
  411. 411● let w = img.width
  412. 412 let h = img.height
  413. 413 let channels = img.channels
  414. 414 // 计算直方图
  415. 415 let histogram : Array[Int32] = []
  416. 416 for _ in 0..<256 {
  417. 417● histogram.push(0)
  418. 418 }
  419. 419 for y in 0..<h {
  420. 420● for x in 0..<w {
  421. 421● let idx = (y * w + x) * channels
  422. 422 let gray = if channels >= 3 {
  423. 423○ (0.299 * img.data[idx].to_double() +
  424. 424○ 0.587 * img.data[idx + 1].to_double() +
  425. 425○ 0.114 * img.data[idx + 2].to_double()).to_int()
  426. 426 } else {
  427. 427● img.data[idx].to_int()
  428. 428 }
  429. 429 histogram[gray] += 1
  430. 430 }
  431. 431 }
  432. 432 // Otsu 阈值计算
  433. 433 let total = w * h
  434. 434 let mut sum_total = 0.0
  435. 435 for i in 0..<256 {
  436. 436● sum_total += i.to_double() * histogram[i].to_double()
  437. 437 }
  438. 438 let mut sum_bg = 0.0
  439. 439 let mut weight_bg = 0
  440. 440 let mut max_variance = 0.0
  441. 441 let mut threshold = 128
  442. 442 for i in 0..<256 {
  443. 443● weight_bg += histogram[i]
  444. 444 if weight_bg == 0 {
  445. 445● continue
  446. 446 }
  447. 447 let weight_fg = total - weight_bg
  448. 448 if weight_fg == 0 {
  449. 449● break
  450. 450 }
  451. 451● sum_bg += i.to_double() * histogram[i].to_double()
  452. 452● let mean_bg = sum_bg / weight_bg.to_double()
  453. 453● let mean_fg = (sum_total - sum_bg) / weight_fg.to_double()
  454. 454● let variance = weight_bg.to_double() *
  455. 455● weight_fg.to_double() *
  456. 456 (mean_bg - mean_fg) *
  457. 457 (mean_bg - mean_fg)
  458. 458 if variance > max_variance {
  459. 459● max_variance = variance
  460. 460 threshold = i
  461. 461 }
  462. 462 }
  463. 463 // 应用二值化
  464. 464● let out_data : Array[Byte] = Array::make(w * h, b'\x00')
  465. 465 for y in 0..<h {
  466. 466● for x in 0..<w {
  467. 467● let idx = (y * w + x) * channels
  468. 468 let gray = if channels >= 3 {
  469. 469○ (0.299 * img.data[idx].to_double() +
  470. 470○ 0.587 * img.data[idx + 1].to_double() +
  471. 471○ 0.114 * img.data[idx + 2].to_double()).to_int()
  472. 472 } else {
  473. 473● img.data[idx].to_int()
  474. 474 }
  475. 475● out_data[y * w + x] = if gray > threshold { b'\xFF' } else { b'\x00' }
  476. 476 }
  477. 477 }
  478. 478 @types.Image::{
  479. 479 width: w,
  480. 480 height: h,
  481. 481 channels: 1,
  482. 482● data: Bytes::from_array(out_data),
  483. 483 }
  484. 484}
  485. 485
  486. 486///|
  487. 487/// 自适应二值化(简化版)
  488. 488fn binarize_adaptive_scan(img : @types.Image) -> @types.Image {
  489. 489● let w = img.width
  490. 490 let h = img.height
  491. 491 let channels = img.channels
  492. 492 let block_size = 15
  493. 493 let c = 10
  494. 494● let out_data : Array[Byte] = Array::make(w * h, b'\x00')
  495. 495 for y in 0..<h {
  496. 496● for x in 0..<w {
  497. 497 // 计算局部均值
  498. 498● let mut sum = 0
  499. 499 let mut count = 0
  500. 500 for dy_idx in 0..<block_size {
  501. 501● let dy = dy_idx - block_size / 2
  502. 502 for dx_idx in 0..<block_size {
  503. 503● let dx = dx_idx - block_size / 2
  504. 504 let ny = y + dy
  505. 505 let nx = x + dx
  506. 506 if ny >= 0 && ny < h && nx >= 0 && nx < w {
  507. 507● let idx = (ny * w + nx) * channels
  508. 508 let gray = if channels >= 3 {
  509. 509● (0.299 * img.data[idx].to_double() +
  510. 510● 0.587 * img.data[idx + 1].to_double() +
  511. 511● 0.114 * img.data[idx + 2].to_double()).to_int()
  512. 512 } else {
  513. 513● img.data[idx].to_int()
  514. 514 }
  515. 515 sum += gray
  516. 516 count += 1
  517. 517 }
  518. 518 }
  519. 519 }
  520. 520◐ let local_mean = if count > 0 { sum / count } else { 128 }
  521. 521 let idx = (y * w + x) * channels
  522. 522 let gray = if channels >= 3 {
  523. 523● (0.299 * img.data[idx].to_double() +
  524. 524● 0.587 * img.data[idx + 1].to_double() +
  525. 525● 0.114 * img.data[idx + 2].to_double()).to_int()
  526. 526 } else {
  527. 527● img.data[idx].to_int()
  528. 528 }
  529. 529 out_data[y * w + x] = if gray > local_mean - c {
  530. 530● b'\xFF'
  531. 531 } else {
  532. 532● b'\x00'
  533. 533 }
  534. 534 }
  535. 535 }
  536. 536 @types.Image::{
  537. 537 width: w,
  538. 538 height: h,
  539. 539 channels: 1,
  540. 540● data: Bytes::from_array(out_data),
  541. 541 }
  542. 542}
  543. 543
  544. 544///|
  545. 545/// Sauvola 二值化(简化版)
  546. 546fn binarize_sauvola_scan(img : @types.Image) -> @types.Image {
  547. 547● let w = img.width
  548. 548 let h = img.height
  549. 549 let channels = img.channels
  550. 550 let window_size = 15
  551. 551 let k = 0.2
  552. 552 let r = 128.0
  553. 553● let out_data : Array[Byte] = Array::make(w * h, b'\x00')
  554. 554 for y in 0..<h {
  555. 555● for x in 0..<w {
  556. 556 // 计算局部均值和标准差
  557. 557● let mut sum = 0.0
  558. 558 let mut sum_sq = 0.0
  559. 559 let mut count = 0
  560. 560 for dy_idx in 0..<window_size {
  561. 561● let dy = dy_idx - window_size / 2
  562. 562 for dx_idx in 0..<window_size {
  563. 563● let dx = dx_idx - window_size / 2
  564. 564 let ny = y + dy
  565. 565 let nx = x + dx
  566. 566 if ny >= 0 && ny < h && nx >= 0 && nx < w {
  567. 567● let idx = (ny * w + nx) * channels
  568. 568 let gray = if channels >= 3 {
  569. 569○ 0.299 * img.data[idx].to_double() +
  570. 570○ 0.587 * img.data[idx + 1].to_double() +
  571. 571○ 0.114 * img.data[idx + 2].to_double()
  572. 572 } else {
  573. 573● img.data[idx].to_double()
  574. 574 }
  575. 575 sum += gray
  576. 576 sum_sq += gray * gray
  577. 577 count += 1
  578. 578 }
  579. 579 }
  580. 580 }
  581. 581◐ let mean = if count > 0 { sum / count.to_double() } else { 128.0 }
  582. 582 let variance = if count > 0 {
  583. 583● sum_sq / count.to_double() - mean * mean
  584. 584 } else {
  585. 585○ 0.0
  586. 586 }
  587. 587● let std = if variance > 0.0 { variance.sqrt() } else { 0.0 }
  588. 588 // Sauvola 阈值
  589. 589 let threshold = mean * (1.0 + k * (std / r - 1.0))
  590. 590 let idx = (y * w + x) * channels
  591. 591 let gray = if channels >= 3 {
  592. 592○ 0.299 * img.data[idx].to_double() +
  593. 593○ 0.587 * img.data[idx + 1].to_double() +
  594. 594○ 0.114 * img.data[idx + 2].to_double()
  595. 595 } else {
  596. 596● img.data[idx].to_double()
  597. 597 }
  598. 598● out_data[y * w + x] = if gray > threshold { b'\xFF' } else { b'\x00' }
  599. 599 }
  600. 600 }
  601. 601 @types.Image::{
  602. 602 width: w,
  603. 603 height: h,
  604. 604 channels: 1,
  605. 605● data: Bytes::from_array(out_data),
  606. 606 }
  607. 607}
  608. 608
  609. 609///|
  610. 610/// 版面分析(基于投影的文本块检测)
  611. 611pub fn analyze_layout_scan(
  612. 612 binary_img : @types.Image,
  613. 613) -> Array[TextBlock] raise @types.LoadError {
  614. 614 // 输入验证
  615. 615● if binary_img.width <= 0 || binary_img.height <= 0 {
  616. 616● raise @types.LoadError::DecodeFailed(
  617. 617 "analyze_layout_scan: 图像尺寸必须大于0",
  618. 618 )
  619. 619 }
  620. 620 if binary_img.channels != 1 {
  621. 621● raise @types.LoadError::DecodeFailed(
  622. 622 "analyze_layout_scan: 仅支持单通道二值图",
  623. 623 )
  624. 624 }
  625. 625 let expected_size = binary_img.width * binary_img.height
  626. 626● if binary_img.data.length() != expected_size {
  627. 627● raise @types.LoadError::DecodeFailed(
  628. 628 "analyze_layout_scan: 数据大小不匹配,期望 " +
  629. 629● expected_size.to_string() +
  630. 630 ",实际 " +
  631. 631● binary_img.data.length().to_string(),
  632. 632 )
  633. 633 }
  634. 634 let w = binary_img.width
  635. 635 let h = binary_img.height
  636. 636 // 水平投影(检测文本行)
  637. 637 let horizontal_proj : Array[Int32] = []
  638. 638 for y in 0..<h {
  639. 639● let mut count = 0
  640. 640 for x in 0..<w {
  641. 641● if binary_img.data[y * w + x] == b'\x00' {
  642. 642● count += 1
  643. 643 }
  644. 644 }
  645. 645● horizontal_proj.push(count)
  646. 646 }
  647. 647 // 检测文本行区域
  648. 648 let blocks : Array[TextBlock] = []
  649. 649 let mut in_line = false
  650. 650 let mut line_start = 0
  651. 651 let mut line_end = 0
  652. 652 let mut reading_order = 0
  653. 653 for y in 0..<h {
  654. 654● if horizontal_proj[y] > w / 50 {
  655. 655● if !in_line {
  656. 656● line_start = y
  657. 657 in_line = true
  658. 658 }
  659. 659 line_end = y
  660. 660● } else if in_line {
  661. 661 // 检测这一行的文本范围
  662. 662● let mut min_x = w
  663. 663 let mut max_x = 0
  664. 664 for yy in line_start..<=line_end {
  665. 665● for x in 0..<w {
  666. 666● if binary_img.data[yy * w + x] == b'\x00' {
  667. 667● if x < min_x {
  668. 668● min_x = x
  669. 669 }
  670. 670 if x > max_x {
  671. 671● max_x = x
  672. 672 }
  673. 673 }
  674. 674 }
  675. 675 }
  676. 676 if max_x > min_x {
  677. 677● blocks.push(TextBlock::{
  678. 678 x: min_x,
  679. 679 y: line_start,
  680. 680 width: max_x - min_x + 1,
  681. 681 height: line_end - line_start + 1,
  682. 682 block_type: "text",
  683. 683 text: "",
  684. 684 confidence: 0.0,
  685. 685 reading_order,
  686. 686 })
  687. 687 reading_order += 1
  688. 688 }
  689. 689 in_line = false
  690. 690 }
  691. 691 }
  692. 692 blocks
  693. 693}
  694. 694
  695. 695///|
  696. 696/// 扫描文档 OCR 完整流水线
  697. 697pub fn scan_ocr_recognize(
  698. 698 img : @types.Image,
  699. 699 config : ScanOCRConfig,
  700. 700) -> OCRPageResult raise @types.LoadError {
  701. 701 // 输入验证
  702. 702● if img.width <= 0 || img.height <= 0 {
  703. 703● raise @types.LoadError::DecodeFailed(
  704. 704 "scan_ocr_recognize: 图像尺寸必须大于0",
  705. 705 )
  706. 706 }
  707. 707 if img.channels < 1 || img.channels > 4 {
  708. 708● raise @types.LoadError::DecodeFailed(
  709. 709 "scan_ocr_recognize: 通道数必须在1-4之间",
  710. 710 )
  711. 711 }
  712. 712 let expected_size = img.width * img.height * img.channels
  713. 713● if img.data.length() != expected_size {
  714. 714● raise @types.LoadError::DecodeFailed(
  715. 715 "scan_ocr_recognize: 数据大小不匹配,期望 " +
  716. 716● expected_size.to_string() +
  717. 717 ",实际 " +
  718. 718● img.data.length().to_string(),
  719. 719 )
  720. 720 }
  721. 721 let _ = 0.0 // 简化,实际需要计时
  722. 722 // 1. 预处理
  723. 723● let preprocessed = scan_document_preprocess(img, config)
  724. 724 // 2. 版面分析
  725. 725 let blocks = if config.layout_analysis {
  726. 726● analyze_layout_scan(preprocessed)
  727. 727 } else {
  728. 728● let single_block : Array[TextBlock] = []
  729. 729● single_block.push(TextBlock::{
  730. 730 x: 0,
  731. 731 y: 0,
  732. 732 width: img.width,
  733. 733 height: img.height,
  734. 734 block_type: "text",
  735. 735 text: "",
  736. 736 confidence: 0.0,
  737. 737 reading_order: 0,
  738. 738 })
  739. 739 single_block
  740. 740 }
  741. 741 // 3. 对每个文本块进行识别(简化版:返回占位文本)
  742. 742 // 实际应该调用对应的 OCR 识别函数
  743. 743 let mut full_text = ""
  744. 744 let mut total_confidence = 0.0
  745. 745 let recognized_blocks : Array[TextBlock] = []
  746. 746● for i in 0..<blocks.length() {
  747. 747 // 简化版识别:返回块的位置信息
  748. 748● let block_text = "[文本块 " +
  749. 749● i.to_string() +
  750. 750 ": " +
  751. 751● blocks[i].width.to_string() +
  752. 752 "x" +
  753. 753● blocks[i].height.to_string() +
  754. 754 "]"
  755. 755 let new_block = TextBlock::{
  756. 756 x: blocks[i].x,
  757. 757 y: blocks[i].y,
  758. 758 width: blocks[i].width,
  759. 759 height: blocks[i].height,
  760. 760 block_type: blocks[i].block_type,
  761. 761 text: block_text,
  762. 762 confidence: 0.85,
  763. 763 reading_order: blocks[i].reading_order,
  764. 764 }
  765. 765● recognized_blocks.push(new_block)
  766. 766 full_text = full_text + block_text + "\n"
  767. 767 total_confidence += new_block.confidence
  768. 768 }
  769. 769● let avg_confidence = if recognized_blocks.length() > 0 {
  770. 770● total_confidence / recognized_blocks.length().to_double()
  771. 771 } else {
  772. 772● 0.0
  773. 773 }
  774. 774 OCRPageResult::{
  775. 775 page_number: 1,
  776. 776 width: img.width,
  777. 777 height: img.height,
  778. 778 blocks: recognized_blocks,
  779. 779 full_text,
  780. 780 average_confidence: avg_confidence,
  781. 781 processing_time_ms: 0.0,
  782. 782 }
  783. 783}
  784. 784
  785. 785///|
  786. 786/// 批量扫描文档 OCR
  787. 787pub fn batch_scan_ocr(
  788. 788 images : Array[@types.Image],
  789. 789 config : ScanOCRConfig,
  790. 790) -> Array[OCRPageResult] raise @types.LoadError {
  791. 791 // 输入验证
  792. 792● if images.length() == 0 {
  793. 793● raise @types.LoadError::DecodeFailed(
  794. 794 "batch_scan_ocr: 图像列表不能为空",
  795. 795 )
  796. 796 }
  797. 797● for i in 0..<images.length() {
  798. 798● if images[i].width <= 0 || images[i].height <= 0 {
  799. 799● raise @types.LoadError::DecodeFailed(
  800. 800● "batch_scan_ocr: 第 " + i.to_string() + " 张图像尺寸必须大于0",
  801. 801 )
  802. 802 }
  803. 803 }
  804. 804 let results : Array[OCRPageResult] = []
  805. 805● for i in 0..<images.length() {
  806. 806● let result = scan_ocr_recognize(images[i], config)
  807. 807 let new_result = OCRPageResult::{
  808. 808 page_number: i + 1,
  809. 809 width: result.width,
  810. 810 height: result.height,
  811. 811 blocks: result.blocks,
  812. 812 full_text: result.full_text,
  813. 813 average_confidence: result.average_confidence,
  814. 814 processing_time_ms: result.processing_time_ms,
  815. 815 }
  816. 816● results.push(new_result)
  817. 817 }
  818. 818 results
  819. 819}
  820. 820
  821. 821///|
  822. 822/// OCR 结果导出为纯文本
  823. 823pub fn ocr_result_to_text(result : OCRPageResult) -> String {
  824. 824● result.full_text
  825. 825}
  826. 826
  827. 827///|
  828. 828/// OCR 结果导出为 hOCR 格式(简化版)
  829. 829pub fn ocr_result_to_hocr(result : OCRPageResult) -> String {
  830. 830● let mut hocr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
  831. 831 hocr = hocr +
  832. 832 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
  833. 833 hocr = hocr +
  834. 834 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
  835. 835 hocr = hocr + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
  836. 836 hocr = hocr + "<head>\n"
  837. 837 hocr = hocr +
  838. 838 "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />\n"
  839. 839 hocr = hocr + "<title>OCR Result</title>\n"
  840. 840 hocr = hocr + "</head>\n"
  841. 841 hocr = hocr + "<body>\n"
  842. 842 hocr = hocr +
  843. 843 "<div class=\"ocr_page\" title=\"image; bbox 0 0 " +
  844. 844● result.width.to_string() +
  845. 845 " " +
  846. 846● result.height.to_string() +
  847. 847 "\">\n"
  848. 848 for block in result.blocks {
  849. 849● hocr = hocr +
  850. 850 "<div class=\"ocr_carea\" title=\"bbox " +
  851. 851● block.x.to_string() +
  852. 852 " " +
  853. 853● block.y.to_string() +
  854. 854 " " +
  855. 855● (block.x + block.width).to_string() +
  856. 856 " " +
  857. 857● (block.y + block.height).to_string() +
  858. 858 "\">\n"
  859. 859 hocr = hocr + "<p class=\"ocr_par\">\n"
  860. 860 hocr = hocr +
  861. 861 "<span class=\"ocr_line\" title=\"bbox " +
  862. 862● block.x.to_string() +
  863. 863 " " +
  864. 864● block.y.to_string() +
  865. 865 " " +
  866. 866● (block.x + block.width).to_string() +
  867. 867 " " +
  868. 868● (block.y + block.height).to_string() +
  869. 869 "\">"
  870. 870 hocr = hocr + block.text
  871. 871 hocr = hocr + "</span>\n"
  872. 872 hocr = hocr + "</p>\n"
  873. 873 hocr = hocr + "</div>\n"
  874. 874 }
  875. 875 hocr = hocr + "</div>\n"
  876. 876 hocr = hocr + "</body>\n"
  877. 877 hocr = hocr + "</html>\n"
  878. 878 hocr
  879. 879}
  880. 880
  881. 881///|
  882. 882/// OCR 结果导出为 JSON
  883. 883pub fn ocr_result_to_json(result : OCRPageResult) -> String {
  884. 884● let mut json = "{\n"
  885. 885● json = json + " \"page_number\": " + result.page_number.to_string() + ",\n"
  886. 886● json = json + " \"width\": " + result.width.to_string() + ",\n"
  887. 887● json = json + " \"height\": " + result.height.to_string() + ",\n"
  888. 888 json = json +
  889. 889 " \"average_confidence\": " +
  890. 890● result.average_confidence.to_string() +
  891. 891 ",\n"
  892. 892 json = json + " \"blocks\": [\n"
  893. 893● for i in 0..<result.blocks.length() {
  894. 894● let block = result.blocks[i]
  895. 895 json = json + " {\n"
  896. 896● json = json + " \"x\": " + block.x.to_string() + ",\n"
  897. 897● json = json + " \"y\": " + block.y.to_string() + ",\n"
  898. 898● json = json + " \"width\": " + block.width.to_string() + ",\n"
  899. 899● json = json + " \"height\": " + block.height.to_string() + ",\n"
  900. 900 json = json + " \"type\": \"" + block.block_type + "\",\n"
  901. 901 json = json + " \"text\": \"" + block.text + "\",\n"
  902. 902 json = json +
  903. 903 " \"confidence\": " +
  904. 904● block.confidence.to_string() +
  905. 905 ",\n"
  906. 906 json = json +
  907. 907 " \"reading_order\": " +
  908. 908● block.reading_order.to_string() +
  909. 909 "\n"
  910. 910 json = json + " }"
  911. 911● if i < result.blocks.length() - 1 {
  912. 912● json = json + ","
  913. 913 }
  914. 914 json = json + "\n"
  915. 915 }
  916. 916 json = json + " ],\n"
  917. 917 json = json + " \"full_text\": \"" + result.full_text + "\"\n"
  918. 918 json = json + "}\n"
  919. 919 json
  920. 920}