image.vision\ocr\table_recognition.mbt

86.2% · 137 / 159 points · 574 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/table_recognition
  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 TableLine {
  13. 13 x1 : Int32
  14. 14 y1 : Int32
  15. 15 x2 : Int32
  16. 16 y2 : Int32
  17. 17 line_type : TableLineType
  18. 18 thickness : Int32
  19. 19}
  20. 20
  21. 21///|
  22. 22pub extend TableLine with Eq::{not_equal, equal}
  23. 23
  24. 24///|
  25. 25pub extend TableLine with @debug.Debug::{to_repr}
  26. 26
  27. 27///|
  28. 28/// 表格线类型
  29. 29/// `#non_exhaustive` 表示未来可能添加新构造器
  30. 30#derive(Eq, @debug.Debug)
  31. 31#non_exhaustive
  32. 32pub(all) enum TableLineType {
  33. 33 Horizontal
  34. 34 Vertical
  35. 35}
  36. 36
  37. 37///|
  38. 38pub extend TableLineType with @debug.Debug::{to_repr}
  39. 39
  40. 40///|
  41. 41pub extend TableLineType with Eq::{not_equal, equal}
  42. 42
  43. 43///|
  44. 44/// 单元格结构体
  45. 45#derive(Eq, @debug.Debug)
  46. 46pub(all) struct TableCell {
  47. 47 x : Int32
  48. 48 y : Int32
  49. 49 width : Int32
  50. 50 height : Int32
  51. 51 row : Int32
  52. 52 col : Int32
  53. 53 row_span : Int32
  54. 54 col_span : Int32
  55. 55}
  56. 56
  57. 57///|
  58. 58pub extend TableCell with Eq::{not_equal, equal}
  59. 59
  60. 60///|
  61. 61pub extend TableCell with @debug.Debug::{to_repr}
  62. 62
  63. 63///|
  64. 64/// 表格结构结构体
  65. 65#derive(Eq, @debug.Debug)
  66. 66pub(all) struct TableStructure {
  67. 67 rows : Int32
  68. 68 cols : Int32
  69. 69 cells : Array[TableCell]
  70. 70 horizontal_lines : Array[TableLine]
  71. 71 vertical_lines : Array[TableLine]
  72. 72 bounding_box : (Int32, Int32, Int32, Int32)
  73. 73}
  74. 74
  75. 75///|
  76. 76pub extend TableStructure with Eq::{not_equal, equal}
  77. 77
  78. 78///|
  79. 79pub extend TableStructure with @debug.Debug::{to_repr}
  80. 80
  81. 81///|
  82. 82/// 检测水平表格线
  83. 83pub fn detect_horizontal_lines(
  84. 84 img : @types.Image,
  85. 85 min_length~ : Int32 = 20,
  86. 86 max_gap~ : Int32 = 2,
  87. 87) -> Array[TableLine] raise @types.LoadError {
  88. 88 // 输入验证
  89. 89● if img.width <= 0 || img.height <= 0 {
  90. 90● raise @types.LoadError::DecodeFailed(
  91. 91 "detect_horizontal_lines: 图像尺寸必须大于0",
  92. 92 )
  93. 93 }
  94. 94 if img.channels != 1 {
  95. 95● raise @types.LoadError::DecodeFailed(
  96. 96 "detect_horizontal_lines: 仅支持单通道二值图",
  97. 97 )
  98. 98 }
  99. 99 let expected_size = img.width * img.height
  100. 100● if img.data.length() != expected_size {
  101. 101● raise @types.LoadError::DecodeFailed(
  102. 102 "detect_horizontal_lines: 数据大小不匹配,期望 " +
  103. 103● expected_size.to_string() +
  104. 104 ",实际 " +
  105. 105● img.data.length().to_string(),
  106. 106 )
  107. 107 }
  108. 108 if min_length <= 0 {
  109. 109● raise @types.LoadError::DecodeFailed(
  110. 110 "detect_horizontal_lines: min_length必须大于0",
  111. 111 )
  112. 112 }
  113. 113 if max_gap < 0 {
  114. 114● raise @types.LoadError::DecodeFailed(
  115. 115 "detect_horizontal_lines: max_gap不能为负数",
  116. 116 )
  117. 117 }
  118. 118 let w = img.width
  119. 119 let h = img.height
  120. 120 let data = img.data
  121. 121 let lines : Array[TableLine] = []
  122. 122 // 逐行检测水平线
  123. 123 for y in 0..<h {
  124. 124● let mut x = 0
  125. 125 while x < w {
  126. 126 // 找连续的黑色像素
  127. 127● if data[y * w + x].to_int() < 128 {
  128. 128● let start_x = x
  129. 129 let mut end_x = x
  130. 130 let mut gap = 0
  131. 131 while x < w && gap <= max_gap {
  132. 132● if data[y * w + x].to_int() < 128 {
  133. 133● end_x = x
  134. 134 gap = 0
  135. 135 } else {
  136. 136● gap += 1
  137. 137 }
  138. 138 x += 1
  139. 139 }
  140. 140 let length = end_x - start_x + 1
  141. 141 if length >= min_length {
  142. 142● lines.push(TableLine::{
  143. 143 x1: start_x,
  144. 144 y1: y,
  145. 145 x2: end_x,
  146. 146 y2: y,
  147. 147 line_type: TableLineType::Horizontal,
  148. 148 thickness: 1,
  149. 149 })
  150. 150 }
  151. 151 } else {
  152. 152● x += 1
  153. 153 }
  154. 154 }
  155. 155 }
  156. 156 // 合并相邻的水平线(同一表格线可能有多行像素)
  157. 157● merge_horizontal_lines(lines, 3)
  158. 158}
  159. 159
  160. 160///|
  161. 161/// 检测垂直表格线
  162. 162pub fn detect_vertical_lines(
  163. 163 img : @types.Image,
  164. 164 min_length~ : Int32 = 20,
  165. 165 max_gap~ : Int32 = 2,
  166. 166) -> Array[TableLine] raise @types.LoadError {
  167. 167 // 输入验证
  168. 168● if img.width <= 0 || img.height <= 0 {
  169. 169● raise @types.LoadError::DecodeFailed(
  170. 170 "detect_vertical_lines: 图像尺寸必须大于0",
  171. 171 )
  172. 172 }
  173. 173 if img.channels != 1 {
  174. 174● raise @types.LoadError::DecodeFailed(
  175. 175 "detect_vertical_lines: 仅支持单通道二值图",
  176. 176 )
  177. 177 }
  178. 178 let expected_size = img.width * img.height
  179. 179● if img.data.length() != expected_size {
  180. 180○ raise @types.LoadError::DecodeFailed(
  181. 181 "detect_vertical_lines: 数据大小不匹配,期望 " +
  182. 182○ expected_size.to_string() +
  183. 183 ",实际 " +
  184. 184○ img.data.length().to_string(),
  185. 185 )
  186. 186 }
  187. 187 if min_length <= 0 {
  188. 188● raise @types.LoadError::DecodeFailed(
  189. 189 "detect_vertical_lines: min_length必须大于0",
  190. 190 )
  191. 191 }
  192. 192 if max_gap < 0 {
  193. 193○ raise @types.LoadError::DecodeFailed(
  194. 194 "detect_vertical_lines: max_gap不能为负数",
  195. 195 )
  196. 196 }
  197. 197 let w = img.width
  198. 198 let h = img.height
  199. 199 let data = img.data
  200. 200 let lines : Array[TableLine] = []
  201. 201 // 逐列检测垂直线
  202. 202 for x in 0..<w {
  203. 203● let mut y = 0
  204. 204 while y < h {
  205. 205● if data[y * w + x].to_int() < 128 {
  206. 206● let start_y = y
  207. 207 let mut end_y = y
  208. 208 let mut gap = 0
  209. 209 while y < h && gap <= max_gap {
  210. 210● if data[y * w + x].to_int() < 128 {
  211. 211● end_y = y
  212. 212 gap = 0
  213. 213 } else {
  214. 214● gap += 1
  215. 215 }
  216. 216 y += 1
  217. 217 }
  218. 218 let length = end_y - start_y + 1
  219. 219 if length >= min_length {
  220. 220● lines.push(TableLine::{
  221. 221 x1: x,
  222. 222 y1: start_y,
  223. 223 x2: x,
  224. 224 y2: end_y,
  225. 225 line_type: TableLineType::Vertical,
  226. 226 thickness: 1,
  227. 227 })
  228. 228 }
  229. 229 } else {
  230. 230● y += 1
  231. 231 }
  232. 232 }
  233. 233 }
  234. 234 // 合并相邻的垂直线
  235. 235● merge_vertical_lines(lines, 3)
  236. 236}
  237. 237
  238. 238///|
  239. 239/// 合并相邻的水平线
  240. 240fn merge_horizontal_lines(
  241. 241 lines : Array[TableLine],
  242. 242 max_y_diff : Int32,
  243. 243) -> Array[TableLine] {
  244. 244● if lines.length() == 0 {
  245. 245● return lines
  246. 246 }
  247. 247 let merged : Array[TableLine] = []
  248. 248 let mut current = lines[0]
  249. 249● for i in 1..<lines.length() {
  250. 250● let next = lines[i]
  251. 251 // 检查是否是同一条线(y坐标接近,x范围重叠)
  252. 252● let y_diff = (next.y1 - current.y1).abs()
  253. 253● let x_overlap = @types.int_min(current.x2, next.x2) -
  254. 254● @types.int_max(current.x1, next.x1)
  255. 255 if y_diff <= max_y_diff && x_overlap > 0 {
  256. 256 // 合并
  257. 257● current = TableLine::{
  258. 258● x1: @types.int_min(current.x1, next.x1),
  259. 259 y1: (current.y1 + next.y1) / 2,
  260. 260● x2: @types.int_max(current.x2, next.x2),
  261. 261 y2: (current.y2 + next.y2) / 2,
  262. 262 line_type: TableLineType::Horizontal,
  263. 263 thickness: current.thickness + 1,
  264. 264 }
  265. 265 } else {
  266. 266● merged.push(current)
  267. 267 current = next
  268. 268 }
  269. 269 }
  270. 270● merged.push(current)
  271. 271 merged
  272. 272}
  273. 273
  274. 274///|
  275. 275/// 合并相邻的垂直线
  276. 276fn merge_vertical_lines(
  277. 277 lines : Array[TableLine],
  278. 278 max_x_diff : Int32,
  279. 279) -> Array[TableLine] {
  280. 280● if lines.length() == 0 {
  281. 281● return lines
  282. 282 }
  283. 283 let merged : Array[TableLine] = []
  284. 284 let mut current = lines[0]
  285. 285● for i in 1..<lines.length() {
  286. 286● let next = lines[i]
  287. 287● let x_diff = (next.x1 - current.x1).abs()
  288. 288● let y_overlap = @types.int_min(current.y2, next.y2) -
  289. 289● @types.int_max(current.y1, next.y1)
  290. 290 if x_diff <= max_x_diff && y_overlap > 0 {
  291. 291● current = TableLine::{
  292. 292 x1: (current.x1 + next.x1) / 2,
  293. 293● y1: @types.int_min(current.y1, next.y1),
  294. 294 x2: (current.x2 + next.x2) / 2,
  295. 295● y2: @types.int_max(current.y2, next.y2),
  296. 296 line_type: TableLineType::Vertical,
  297. 297 thickness: current.thickness + 1,
  298. 298 }
  299. 299 } else {
  300. 300● merged.push(current)
  301. 301 current = next
  302. 302 }
  303. 303 }
  304. 304● merged.push(current)
  305. 305 merged
  306. 306}
  307. 307
  308. 308///|
  309. 309/// 分析表格结构(基于水平线和垂直线)
  310. 310pub fn analyze_table_structure(
  311. 311 horizontal_lines : Array[TableLine],
  312. 312 vertical_lines : Array[TableLine],
  313. 313) -> TableStructure raise @types.LoadError {
  314. 314 // 输入验证
  315. 315● if horizontal_lines.length() == 0 {
  316. 316● raise @types.LoadError::DecodeFailed(
  317. 317 "analyze_table_structure: 水平线列表不能为空",
  318. 318 )
  319. 319 }
  320. 320● if vertical_lines.length() == 0 {
  321. 321● raise @types.LoadError::DecodeFailed(
  322. 322 "analyze_table_structure: 垂直线列表不能为空",
  323. 323 )
  324. 324 }
  325. 325● if horizontal_lines.length() < 2 || vertical_lines.length() < 2 {
  326. 326● return TableStructure::{
  327. 327 rows: 0,
  328. 328 cols: 0,
  329. 329 cells: [],
  330. 330 horizontal_lines,
  331. 331 vertical_lines,
  332. 332 bounding_box: (0, 0, 0, 0),
  333. 333 }
  334. 334 }
  335. 335 // 提取水平线的y坐标(按y排序)
  336. 336 let h_ys : Array[Int32] = []
  337. 337 for line in horizontal_lines {
  338. 338● h_ys.push(line.y1)
  339. 339 }
  340. 340 // 排序
  341. 341● for _ in 0..<h_ys.length() {
  342. 342● for j in 0..<(h_ys.length() - 1) {
  343. 343● if h_ys[j] > h_ys[j + 1] {
  344. 344○ let temp = h_ys[j]
  345. 345 h_ys[j] = h_ys[j + 1]
  346. 346 h_ys[j + 1] = temp
  347. 347 }
  348. 348 }
  349. 349 }
  350. 350 // 提取垂直线的x坐标(按x排序)
  351. 351 let v_xs : Array[Int32] = []
  352. 352 for line in vertical_lines {
  353. 353● v_xs.push(line.x1)
  354. 354 }
  355. 355● for _ in 0..<v_xs.length() {
  356. 356● for j in 0..<(v_xs.length() - 1) {
  357. 357● if v_xs[j] > v_xs[j + 1] {
  358. 358○ let temp = v_xs[j]
  359. 359 v_xs[j] = v_xs[j + 1]
  360. 360 v_xs[j + 1] = temp
  361. 361 }
  362. 362 }
  363. 363 }
  364. 364 // 计算边界框
  365. 365 let min_x = v_xs[0]
  366. 366● let max_x = v_xs[v_xs.length() - 1]
  367. 367 let min_y = h_ys[0]
  368. 368● let max_y = h_ys[h_ys.length() - 1]
  369. 369 // 生成单元格
  370. 370 let cells : Array[TableCell] = []
  371. 371● let rows = h_ys.length() - 1
  372. 372● let cols = v_xs.length() - 1
  373. 373 for row in 0..<rows {
  374. 374● for col in 0..<cols {
  375. 375● let cell_x = v_xs[col]
  376. 376 let cell_y = h_ys[row]
  377. 377 let cell_w = v_xs[col + 1] - v_xs[col]
  378. 378 let cell_h = h_ys[row + 1] - h_ys[row]
  379. 379 if cell_w > 0 && cell_h > 0 {
  380. 380● cells.push(TableCell::{
  381. 381 x: cell_x,
  382. 382 y: cell_y,
  383. 383 width: cell_w,
  384. 384 height: cell_h,
  385. 385 row,
  386. 386 col,
  387. 387 row_span: 1,
  388. 388 col_span: 1,
  389. 389 })
  390. 390 }
  391. 391 }
  392. 392 }
  393. 393 TableStructure::{
  394. 394 rows,
  395. 395 cols,
  396. 396 cells,
  397. 397 horizontal_lines,
  398. 398 vertical_lines,
  399. 399 bounding_box: (min_x, min_y, max_x - min_x, max_y - min_y),
  400. 400 }
  401. 401}
  402. 402
  403. 403///|
  404. 404/// 完整表格识别流水线
  405. 405pub fn recognize_table(
  406. 406 img : @types.Image,
  407. 407 min_line_length~ : Int32 = 20,
  408. 408) -> TableStructure raise @types.LoadError {
  409. 409 // 输入验证
  410. 410● if img.width <= 0 || img.height <= 0 {
  411. 411● raise @types.LoadError::DecodeFailed(
  412. 412 "recognize_table: 图像尺寸必须大于0",
  413. 413 )
  414. 414 }
  415. 415 if img.channels < 1 || img.channels > 4 {
  416. 416● raise @types.LoadError::DecodeFailed(
  417. 417 "recognize_table: 通道数必须在1-4之间",
  418. 418 )
  419. 419 }
  420. 420 let expected_size = img.width * img.height * img.channels
  421. 421● if img.data.length() != expected_size {
  422. 422● raise @types.LoadError::DecodeFailed(
  423. 423 "recognize_table: 数据大小不匹配,期望 " +
  424. 424● expected_size.to_string() +
  425. 425 ",实际 " +
  426. 426● img.data.length().to_string(),
  427. 427 )
  428. 428 }
  429. 429 if min_line_length <= 0 {
  430. 430○ raise @types.LoadError::DecodeFailed(
  431. 431 "recognize_table: min_line_length必须大于0",
  432. 432 )
  433. 433 }
  434. 434 // 1. 预处理(二值化)
  435. 435◐ let binary = if img.channels == 1 { img } else { to_grayscale_table(img) }
  436. 436 // 2. 检测水平线
  437. 437● let h_lines = detect_horizontal_lines(binary, min_length=min_line_length)
  438. 438 // 3. 检测垂直线
  439. 439● let v_lines = detect_vertical_lines(binary, min_length=min_line_length)
  440. 440 // 4. 分析表格结构
  441. 441● analyze_table_structure(h_lines, v_lines)
  442. 442}
  443. 443
  444. 444///|
  445. 445/// 提取单元格图像
  446. 446pub fn extract_cell_image(
  447. 447 img : @types.Image,
  448. 448 cell : TableCell,
  449. 449 padding~ : Int32 = 1,
  450. 450) -> @types.Image raise @types.LoadError {
  451. 451 // 输入验证
  452. 452● if img.width <= 0 || img.height <= 0 {
  453. 453● raise @types.LoadError::DecodeFailed(
  454. 454 "extract_cell_image: 图像尺寸必须大于0",
  455. 455 )
  456. 456 }
  457. 457 if img.channels < 1 || img.channels > 4 {
  458. 458○ raise @types.LoadError::DecodeFailed(
  459. 459 "extract_cell_image: 通道数必须在1-4之间",
  460. 460 )
  461. 461 }
  462. 462 let expected_size = img.width * img.height * img.channels
  463. 463● if img.data.length() != expected_size {
  464. 464○ raise @types.LoadError::DecodeFailed(
  465. 465 "extract_cell_image: 数据大小不匹配,期望 " +
  466. 466○ expected_size.to_string() +
  467. 467 ",实际 " +
  468. 468○ img.data.length().to_string(),
  469. 469 )
  470. 470 }
  471. 471 if cell.width <= 0 || cell.height <= 0 {
  472. 472● raise @types.LoadError::DecodeFailed(
  473. 473 "extract_cell_image: 单元格尺寸必须大于0",
  474. 474 )
  475. 475 }
  476. 476 if padding < 0 {
  477. 477● raise @types.LoadError::DecodeFailed(
  478. 478 "extract_cell_image: padding不能为负数",
  479. 479 )
  480. 480 }
  481. 481 let w = img.width
  482. 482 let h = img.height
  483. 483 let ch = img.channels
  484. 484● let x = @types.int_max(0, cell.x - padding)
  485. 485● let y = @types.int_max(0, cell.y - padding)
  486. 486● let width = @types.int_min(w - x, cell.width + padding * 2)
  487. 487● let height = @types.int_min(h - y, cell.height + padding * 2)
  488. 488 if width <= 0 || height <= 0 {
  489. 489○ let empty : Array[Byte] = Array::make(1 * 1 * ch, b'\x00')
  490. 490 return @types.Image::{
  491. 491 width: 1,
  492. 492 height: 1,
  493. 493 channels: ch,
  494. 494○ data: Bytes::from_array(empty),
  495. 495 }
  496. 496 }
  497. 497● let out : Array[Byte] = Array::make(width * height * ch, b'\x00')
  498. 498 let data = img.data
  499. 499 for yy in 0..<height {
  500. 500● for xx in 0..<width {
  501. 501● for c in 0..<ch {
  502. 502● out[(yy * width + xx) * ch + c] = data[((y + yy) * w + (x + xx)) * ch +
  503. 503 c]
  504. 504 }
  505. 505 }
  506. 506 }
  507. 507● @types.Image::{ width, height, channels: ch, data: Bytes::from_array(out), }
  508. 508}
  509. 509
  510. 510///|
  511. 511/// 提取所有单元格图像
  512. 512pub fn extract_all_cells(
  513. 513 img : @types.Image,
  514. 514 structure : TableStructure,
  515. 515 padding~ : Int32 = 1,
  516. 516) -> Array[@types.Image] raise @types.LoadError {
  517. 517 // 输入验证
  518. 518● if img.width <= 0 || img.height <= 0 {
  519. 519● raise @types.LoadError::DecodeFailed(
  520. 520 "extract_all_cells: 图像尺寸必须大于0",
  521. 521 )
  522. 522 }
  523. 523 if img.channels < 1 || img.channels > 4 {
  524. 524○ raise @types.LoadError::DecodeFailed(
  525. 525 "extract_all_cells: 通道数必须在1-4之间",
  526. 526 )
  527. 527 }
  528. 528 let expected_size = img.width * img.height * img.channels
  529. 529● if img.data.length() != expected_size {
  530. 530○ raise @types.LoadError::DecodeFailed(
  531. 531 "extract_all_cells: 数据大小不匹配,期望 " +
  532. 532○ expected_size.to_string() +
  533. 533 ",实际 " +
  534. 534○ img.data.length().to_string(),
  535. 535 )
  536. 536 }
  537. 537 if padding < 0 {
  538. 538● raise @types.LoadError::DecodeFailed(
  539. 539 "extract_all_cells: padding不能为负数",
  540. 540 )
  541. 541 }
  542. 542 let images : Array[@types.Image] = []
  543. 543 for cell in structure.cells {
  544. 544● let cell_img = extract_cell_image(img, cell, padding~)
  545. 545● images.push(cell_img)
  546. 546 }
  547. 547 images
  548. 548}
  549. 549
  550. 550///|
  551. 551/// 转灰度(表格识别专用)
  552. 552fn to_grayscale_table(img : @types.Image) -> @types.Image {
  553. 553● if img.channels == 1 {
  554. 554● return img
  555. 555 }
  556. 556 let n = img.width * img.height
  557. 557 let ch = img.channels
  558. 558● let out : Array[Byte] = Array::make(n, b'\x00')
  559. 559 let data = img.data
  560. 560 for i in 0..<n {
  561. 561● let base = i * ch
  562. 562● let r = data[base].to_int()
  563. 563● let g = data[base + 1].to_int()
  564. 564● let b = data[base + 2].to_int()
  565. 565 let gray = (r * 299 + g * 587 + b * 114) / 1000
  566. 566● out[i] = gray.to_byte()
  567. 567 }
  568. 568 @types.Image::{
  569. 569 width: img.width,
  570. 570 height: img.height,
  571. 571 channels: 1,
  572. 572● data: Bytes::from_array(out),
  573. 573 }
  574. 574}