image.vision\ocr\layout_analysis.mbt

93.1% · 121 / 130 points · 466 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/layout_analysis
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 版面分析
  7. 7// 文本区域检测、页面分割、多栏检测
  8. 8
  9. 9///|
  10. 10/// 文本区域结构体
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct TextRegion {
  13. 13 x : Int32
  14. 14 y : Int32
  15. 15 width : Int32
  16. 16 height : Int32
  17. 17 region_type : TextRegionType
  18. 18}
  19. 19
  20. 20///|
  21. 21pub extend TextRegion with Eq::{not_equal, equal}
  22. 22
  23. 23///|
  24. 24pub extend TextRegion with @debug.Debug::{to_repr}
  25. 25
  26. 26///|
  27. 27/// 文本区域类型
  28. 28/// `#non_exhaustive` 表示未来可能添加新构造器
  29. 29#derive(Eq, @debug.Debug)
  30. 30#non_exhaustive
  31. 31pub(all) enum TextRegionType {
  32. 32 Text
  33. 33 Image
  34. 34 Table
  35. 35 Unknown
  36. 36}
  37. 37
  38. 38///|
  39. 39pub extend TextRegionType with @debug.Debug::{to_repr}
  40. 40
  41. 41///|
  42. 42pub extend TextRegionType with Eq::{not_equal, equal}
  43. 43
  44. 44///|
  45. 45/// 文本行结构体
  46. 46#derive(Eq, @debug.Debug)
  47. 47pub(all) struct TextLine {
  48. 48 x : Int32
  49. 49 y : Int32
  50. 50 width : Int32
  51. 51 height : Int32
  52. 52}
  53. 53
  54. 54///|
  55. 55pub extend TextLine with Eq::{not_equal, equal}
  56. 56
  57. 57///|
  58. 58pub extend TextLine with @debug.Debug::{to_repr}
  59. 59
  60. 60///|
  61. 61/// 检测文本区域(基于投影分析)
  62. 62/// 返回文本区域列表
  63. 63pub fn detect_text_regions(
  64. 64 img : @types.Image,
  65. 65) -> Array[TextRegion] raise @types.LoadError {
  66. 66 // 输入验证
  67. 67● if img.width <= 0 || img.height <= 0 {
  68. 68● raise @types.LoadError::DecodeFailed(
  69. 69 "detect_text_regions: 图像尺寸必须大于0",
  70. 70 )
  71. 71 }
  72. 72 if img.channels != 1 {
  73. 73● raise @types.LoadError::DecodeFailed(
  74. 74 "detect_text_regions: 仅支持单通道灰度图",
  75. 75 )
  76. 76 }
  77. 77 let expected_size = img.width * img.height
  78. 78● if img.data.length() != expected_size {
  79. 79● raise @types.LoadError::DecodeFailed(
  80. 80 "detect_text_regions: 数据大小不匹配,期望 " +
  81. 81● expected_size.to_string() +
  82. 82 ",实际 " +
  83. 83● img.data.length().to_string(),
  84. 84 )
  85. 85 }
  86. 86 let w = img.width
  87. 87 let h = img.height
  88. 88 let data = img.data
  89. 89 // 二值化(简单阈值)
  90. 90● let binary : Array[Bool] = Array::make(w * h, false)
  91. 91 for i in 0..<(w * h) {
  92. 92● binary[i] = data[i].to_int() < 128
  93. 93 }
  94. 94 // 水平投影(检测文本行)
  95. 95● let horizontal_proj : Array[Int32] = Array::make(h, 0)
  96. 96 for y in 0..<h {
  97. 97● for x in 0..<w {
  98. 98● if binary[y * w + x] {
  99. 99● horizontal_proj[y] += 1
  100. 100 }
  101. 101 }
  102. 102 }
  103. 103 // 检测文本行区域
  104. 104 let regions : Array[TextRegion] = []
  105. 105 let mut in_text = false
  106. 106 let mut start_y = 0
  107. 107 let threshold = w / 20 // 文本行阈值
  108. 108 for y in 0..<h {
  109. 109● if horizontal_proj[y] > threshold && !in_text {
  110. 110● in_text = true
  111. 111 start_y = y
  112. 112● } else if horizontal_proj[y] <= threshold && in_text {
  113. 113● in_text = false
  114. 114 // 计算这一行的水平范围
  115. 115 let mut min_x = w
  116. 116 let mut max_x = 0
  117. 117 for yy in start_y..<y {
  118. 118● for x in 0..<w {
  119. 119● if binary[yy * w + x] {
  120. 120● if x < min_x {
  121. 121● min_x = x
  122. 122 }
  123. 123 if x > max_x {
  124. 124● max_x = x
  125. 125 }
  126. 126 }
  127. 127 }
  128. 128 }
  129. 129 if max_x > min_x {
  130. 130● regions.push(TextRegion::{
  131. 131 x: min_x,
  132. 132 y: start_y,
  133. 133 width: max_x - min_x + 1,
  134. 134 height: y - start_y,
  135. 135 region_type: TextRegionType::Text,
  136. 136 })
  137. 137 }
  138. 138 }
  139. 139 }
  140. 140 regions
  141. 141}
  142. 142
  143. 143///|
  144. 144/// 页面分割(文本/图像/表格区域)
  145. 145/// 返回区域列表
  146. 146pub fn segment_page(
  147. 147 img : @types.Image,
  148. 148) -> Array[TextRegion] raise @types.LoadError {
  149. 149 // 输入验证
  150. 150● if img.width <= 0 || img.height <= 0 {
  151. 151● raise @types.LoadError::DecodeFailed(
  152. 152 "segment_page: 图像尺寸必须大于0",
  153. 153 )
  154. 154 }
  155. 155 if img.channels != 1 {
  156. 156○ raise @types.LoadError::DecodeFailed(
  157. 157 "segment_page: 仅支持单通道灰度图",
  158. 158 )
  159. 159 }
  160. 160 let expected_size = img.width * img.height
  161. 161● if img.data.length() != expected_size {
  162. 162● raise @types.LoadError::DecodeFailed(
  163. 163 "segment_page: 数据大小不匹配,期望 " +
  164. 164● expected_size.to_string() +
  165. 165 ",实际 " +
  166. 166● img.data.length().to_string(),
  167. 167 )
  168. 168 }
  169. 169 let w = img.width
  170. 170 let h = img.height
  171. 171 let data = img.data
  172. 172 // 二值化
  173. 173● let binary : Array[Bool] = Array::make(w * h, false)
  174. 174 for i in 0..<(w * h) {
  175. 175● binary[i] = data[i].to_int() < 128
  176. 176 }
  177. 177 // 连通域分析(简化版)
  178. 178● let visited : Array[Bool] = Array::make(w * h, false)
  179. 179 let regions : Array[TextRegion] = []
  180. 180 for y in 0..<h {
  181. 181● for x in 0..<w {
  182. 182● if binary[y * w + x] && !visited[y * w + x] {
  183. 183 // BFS 找连通域
  184. 184● let mut min_x = x
  185. 185 let mut max_x = x
  186. 186 let mut min_y = y
  187. 187 let mut max_y = y
  188. 188 let mut count = 0
  189. 189 let queue : Array[(Int32, Int32)] = [(x, y)]
  190. 190 visited[y * w + x] = true
  191. 191 let mut queue_idx = 0
  192. 192● while queue_idx < queue.length() {
  193. 193● let (cx, cy) = queue[queue_idx]
  194. 194 queue_idx += 1
  195. 195 count += 1
  196. 196 if cx < min_x {
  197. 197○ min_x = cx
  198. 198 }
  199. 199 if cx > max_x {
  200. 200● max_x = cx
  201. 201 }
  202. 202 if cy < min_y {
  203. 203○ min_y = cy
  204. 204 }
  205. 205 if cy > max_y {
  206. 206● max_y = cy
  207. 207 }
  208. 208 // 8 邻域
  209. 209 for dy in -1..<2 {
  210. 210● for dx in -1..<2 {
  211. 211● let nx = cx + dx
  212. 212 let ny = cy + dy
  213. 213 if nx >= 0 &&
  214. 214 nx < w &&
  215. 215 ny >= 0 &&
  216. 216 ny < h &&
  217. 217 binary[ny * w + nx] &&
  218. 218 !visited[ny * w + nx] {
  219. 219● visited[ny * w + nx] = true
  220. 220● queue.push((nx, ny))
  221. 221 }
  222. 222 }
  223. 223 }
  224. 224 }
  225. 225 // 根据区域大小和宽高比判断类型
  226. 226 let region_w = max_x - min_x + 1
  227. 227 let region_h = max_y - min_y + 1
  228. 228 let region_type = if count < 50 {
  229. 229○ TextRegionType::Unknown // 噪声
  230. 230● } else if region_w > 50 && region_h > 50 {
  231. 231○ TextRegionType::Image // 大区域可能是图像
  232. 232 } else {
  233. 233● TextRegionType::Text // 小区域可能是文字
  234. 234 }
  235. 235● regions.push(TextRegion::{
  236. 236 x: min_x,
  237. 237 y: min_y,
  238. 238 width: region_w,
  239. 239 height: region_h,
  240. 240 region_type,
  241. 241 })
  242. 242 }
  243. 243 }
  244. 244 }
  245. 245 regions
  246. 246}
  247. 247
  248. 248///|
  249. 249/// 检测多栏布局
  250. 250/// 返回栏数和每栏的 x 范围
  251. 251pub fn detect_columns(
  252. 252 img : @types.Image,
  253. 253) -> (Int32, Array[(Int32, Int32)]) raise @types.LoadError {
  254. 254 // 输入验证
  255. 255● if img.width <= 0 || img.height <= 0 {
  256. 256● raise @types.LoadError::DecodeFailed(
  257. 257 "detect_columns: 图像尺寸必须大于0",
  258. 258 )
  259. 259 }
  260. 260 if img.channels != 1 {
  261. 261○ raise @types.LoadError::DecodeFailed(
  262. 262 "detect_columns: 仅支持单通道灰度图",
  263. 263 )
  264. 264 }
  265. 265 let expected_size = img.width * img.height
  266. 266● if img.data.length() != expected_size {
  267. 267● raise @types.LoadError::DecodeFailed(
  268. 268 "detect_columns: 数据大小不匹配,期望 " +
  269. 269● expected_size.to_string() +
  270. 270 ",实际 " +
  271. 271● img.data.length().to_string(),
  272. 272 )
  273. 273 }
  274. 274 let w = img.width
  275. 275 let h = img.height
  276. 276 let data = img.data
  277. 277 // 垂直投影
  278. 278● let vertical_proj : Array[Int32] = Array::make(w, 0)
  279. 279 for y in 0..<h {
  280. 280● for x in 0..<w {
  281. 281● if data[y * w + x].to_int() < 128 {
  282. 282● vertical_proj[x] += 1
  283. 283 }
  284. 284 }
  285. 285 }
  286. 286 // 找空白列(栏间距)
  287. 287 let threshold = h / 50 // 空白列阈值
  288. 288 let gaps : Array[(Int32, Int32)] = []
  289. 289 let mut in_gap = false
  290. 290 let mut gap_start = 0
  291. 291 for x in 0..<w {
  292. 292● if vertical_proj[x] < threshold && !in_gap {
  293. 293● in_gap = true
  294. 294 gap_start = x
  295. 295● } else if vertical_proj[x] >= threshold && in_gap {
  296. 296● in_gap = false
  297. 297 let gap_width = x - gap_start
  298. 298 if gap_width > w / 20 { // 足够宽的间隙才算栏间距
  299. 299● gaps.push((gap_start, x))
  300. 300 }
  301. 301 }
  302. 302 }
  303. 303 // 根据间隙计算栏数和范围
  304. 304● let num_columns = gaps.length() + 1
  305. 305 let columns : Array[(Int32, Int32)] = []
  306. 306 let mut prev_end = 0
  307. 307● for i in 0..<gaps.length() {
  308. 308● let (start, end) = gaps[i]
  309. 309● columns.push((prev_end, start))
  310. 310 prev_end = end
  311. 311 }
  312. 312● columns.push((prev_end, w))
  313. 313 (num_columns, columns)
  314. 314}
  315. 315
  316. 316///|
  317. 317/// 提取文本行图像
  318. 318/// 返回文本行图像列表
  319. 319pub fn extract_text_lines(
  320. 320 img : @types.Image,
  321. 321) -> Array[@types.Image] raise @types.LoadError {
  322. 322 // 输入验证
  323. 323● if img.width <= 0 || img.height <= 0 {
  324. 324● raise @types.LoadError::DecodeFailed(
  325. 325 "extract_text_lines: 图像尺寸必须大于0",
  326. 326 )
  327. 327 }
  328. 328 if img.channels != 1 {
  329. 329● raise @types.LoadError::DecodeFailed(
  330. 330 "extract_text_lines: 仅支持单通道灰度图",
  331. 331 )
  332. 332 }
  333. 333 let expected_size = img.width * img.height
  334. 334● if img.data.length() != expected_size {
  335. 335● raise @types.LoadError::DecodeFailed(
  336. 336 "extract_text_lines: 数据大小不匹配,期望 " +
  337. 337● expected_size.to_string() +
  338. 338 ",实际 " +
  339. 339● img.data.length().to_string(),
  340. 340 )
  341. 341 }
  342. 342● let regions = detect_text_regions(img)
  343. 343 let lines : Array[@types.Image] = []
  344. 344 for region in regions {
  345. 345● if region.region_type == TextRegionType::Text {
  346. 346● let line = crop_region(
  347. 347 img,
  348. 348 region.x,
  349. 349 region.y,
  350. 350 region.width,
  351. 351 region.height,
  352. 352 )
  353. 353● match line {
  354. 354● Some(l) => lines.push(l)
  355. 355○ None => ignore(())
  356. 356 }
  357. 357 }
  358. 358 }
  359. 359 lines
  360. 360}
  361. 361
  362. 362///|
  363. 363/// 裁剪图像区域
  364. 364fn crop_region(
  365. 365 img : @types.Image,
  366. 366 x : Int32,
  367. 367 y : Int32,
  368. 368 width : Int32,
  369. 369 height : Int32,
  370. 370) -> @types.Image? {
  371. 371● let w = img.width
  372. 372 let h = img.height
  373. 373 let ch = img.channels
  374. 374 if x < 0 || y < 0 || x + width > w || y + height > h {
  375. 375○ return None
  376. 376 }
  377. 377● let out : Array[Byte] = Array::make(width * height * ch, b'\x00')
  378. 378 let data = img.data
  379. 379 for yy in 0..<height {
  380. 380● for xx in 0..<width {
  381. 381● for c in 0..<ch {
  382. 382● out[(yy * width + xx) * ch + c] = data[((y + yy) * w + (x + xx)) * ch +
  383. 383 c]
  384. 384 }
  385. 385 }
  386. 386 }
  387. 387 Some(@types.Image::{
  388. 388 width,
  389. 389 height,
  390. 390 channels: ch,
  391. 391● data: Bytes::from_array(out),
  392. 392 })
  393. 393}
  394. 394
  395. 395///|
  396. 396/// OCR 完整预处理流水线
  397. 397/// 灰度化 -> 去噪 -> 倾斜校正 -> 二值化 -> 输出
  398. 398pub fn ocr_preprocess(
  399. 399 img : @types.Image,
  400. 400 binarization_method~ : String = "sauvola",
  401. 401) -> @types.Image raise @types.LoadError {
  402. 402 // 输入验证
  403. 403● if img.width <= 0 || img.height <= 0 {
  404. 404● raise @types.LoadError::DecodeFailed(
  405. 405 "ocr_preprocess: 图像尺寸必须大于0",
  406. 406 )
  407. 407 }
  408. 408 if img.channels < 1 || img.channels > 4 {
  409. 409● raise @types.LoadError::DecodeFailed(
  410. 410 "ocr_preprocess: 通道数必须在1-4之间",
  411. 411 )
  412. 412 }
  413. 413 let expected_size = img.width * img.height * img.channels
  414. 414● if img.data.length() != expected_size {
  415. 415● raise @types.LoadError::DecodeFailed(
  416. 416 "ocr_preprocess: 数据大小不匹配,期望 " +
  417. 417● expected_size.to_string() +
  418. 418 ",实际 " +
  419. 419● img.data.length().to_string(),
  420. 420 )
  421. 421 }
  422. 422 let mut result = img
  423. 423 // 1. 转灰度
  424. 424 if result.channels != 1 {
  425. 425● result = to_grayscale_ocr(result)
  426. 426 }
  427. 427 // 2. 文档增强(去噪+对比度+锐化)
  428. 428● result = document_enhance(result)
  429. 429 // 3. 倾斜校正
  430. 430● result = deskew(result)
  431. 431 // 4. 二值化
  432. 432● result = match binarization_method {
  433. 433● "sauvola" => sauvola_threshold(result)
  434. 434● "niblack" => niblack_threshold(result)
  435. 435● "otsu" => otsu_threshold(result)
  436. 436● "adaptive" => adaptive_threshold_ocr(result)
  437. 437● _ => sauvola_threshold(result)
  438. 438 }
  439. 439 result
  440. 440}
  441. 441
  442. 442///|
  443. 443/// 转灰度(OCR 专用)
  444. 444fn to_grayscale_ocr(img : @types.Image) -> @types.Image {
  445. 445● if img.channels == 1 {
  446. 446○ return img
  447. 447 }
  448. 448 let n = img.width * img.height
  449. 449 let ch = img.channels
  450. 450● let out : Array[Byte] = Array::make(n, b'\x00')
  451. 451 let data = img.data
  452. 452 for i in 0..<n {
  453. 453● let base = i * ch
  454. 454● let r = data[base].to_int()
  455. 455● let g = data[base + 1].to_int()
  456. 456● let b = data[base + 2].to_int()
  457. 457 let gray = (r * 299 + g * 587 + b * 114) / 1000
  458. 458● out[i] = gray.to_byte()
  459. 459 }
  460. 460 @types.Image::{
  461. 461 width: img.width,
  462. 462 height: img.height,
  463. 463 channels: 1,
  464. 464● data: Bytes::from_array(out),
  465. 465 }
  466. 466}