image.vision\ocr\table_image_extraction.mbt
85.4% · 170 / 199 points · 694 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # 表格图像提取 ocr/table_image_extraction - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 表格识别增强与图片提取(v12.20.0) - 7
// 真正的表格线检测、单元格分割、表格结构分析、图片区域裁剪保存 - 8
- 9
///| - 10
/// 表格线检测结果 - 11
#derive(Eq, @debug.Debug) - 12
pub(all) struct TableDetectionResult { - 13
horizontal_lines : Array[(Int32, Int32, Int32)] // (y, x_start, x_end) - 14
vertical_lines : Array[(Int32, Int32, Int32)] // (x, y_start, y_end) - 15
intersections : Array[(Int32, Int32)] // (x, y) 交叉点 - 16
num_rows : Int32 - 17
num_cols : Int32 - 18
confidence : Double - 19
} - 20
- 21
///| - 22
pub extend TableDetectionResult with Eq::{not_equal, equal} - 23
- 24
///| - 25
pub extend TableDetectionResult with @debug.Debug::{to_repr} - 26
- 27
///| - 28
/// 单元格内容 - 29
#derive(Eq, @debug.Debug) - 30
pub(all) struct TableCellContent { - 31
row : Int32 - 32
col : Int32 - 33
row_span : Int32 - 34
col_span : Int32 - 35
x : Int32 - 36
y : Int32 - 37
width : Int32 - 38
height : Int32 - 39
text : String - 40
is_header : Bool - 41
is_merged : Bool - 42
} - 43
- 44
///| - 45
pub extend TableCellContent with Eq::{not_equal, equal} - 46
- 47
///| - 48
pub extend TableCellContent with @debug.Debug::{to_repr} - 49
- 50
///| - 51
/// 完整表格识别结果 - 52
#derive(Eq, @debug.Debug) - 53
pub(all) struct EnhancedTableResult { - 54
x : Int32 - 55
y : Int32 - 56
width : Int32 - 57
height : Int32 - 58
rows : Int32 - 59
cols : Int32 - 60
cells : Array[TableCellContent] - 61
has_header : Bool - 62
header_rows : Int32 - 63
detection : TableDetectionResult - 64
confidence : Double - 65
} - 66
- 67
///| - 68
pub extend EnhancedTableResult with Eq::{not_equal, equal} - 69
- 70
///| - 71
pub extend EnhancedTableResult with @debug.Debug::{to_repr} - 72
- 73
///| - 74
/// 提取的图片区域 - 75
#derive(Eq, @debug.Debug) - 76
pub(all) struct ExtractedImage { - 77
x : Int32 - 78
y : Int32 - 79
width : Int32 - 80
height : Int32 - 81
image_type : String // "photo" / "diagram" / "chart" / "logo" / "signature" - 82
confidence : Double - 83
aspect_ratio : Double - 84
fill_ratio : Double - 85
edge_density : Double - 86
file_name : String - 87
} - 88
- 89
///| - 90
pub extend ExtractedImage with Eq::{not_equal, equal} - 91
- 92
///| - 93
pub extend ExtractedImage with @debug.Debug::{to_repr} - 94
- 95
///| - 96
/// 检测水平表格线(基于形态学操作的简化版) - 97
pub fn detect_horizontal_table_lines( - 98
binary_img : @types.Image, - 99
min_length~ : Int32 = 50, - 100
max_gap~ : Int32 = 3, - 101
) -> Array[(Int32, Int32, Int32)] raise @types.LoadError { - 102
// 输入验证 - 103●
if binary_img.width <= 0 || binary_img.height <= 0 { - 104●
raise @types.LoadError::DecodeFailed( - 105
"detect_horizontal_table_lines: 图像尺寸必须大于0", - 106
) - 107
} - 108
if binary_img.channels != 1 { - 109●
raise @types.LoadError::DecodeFailed( - 110
"detect_horizontal_table_lines: 仅支持单通道二值图", - 111
) - 112
} - 113
let expected_size = binary_img.width * binary_img.height - 114●
if binary_img.data.length() != expected_size { - 115●
raise @types.LoadError::DecodeFailed( - 116
"detect_horizontal_table_lines: 数据大小不匹配,期望 " + - 117●
expected_size.to_string() + - 118
",实际 " + - 119●
binary_img.data.length().to_string(), - 120
) - 121
} - 122
if min_length <= 0 { - 123●
raise @types.LoadError::DecodeFailed( - 124
"detect_horizontal_table_lines: 最小线长必须大于0", - 125
) - 126
} - 127
if max_gap < 0 { - 128●
raise @types.LoadError::DecodeFailed( - 129
"detect_horizontal_table_lines: 最大间隙不能为负", - 130
) - 131
} - 132
let min_len = min_length - 133
let max_g = max_gap - 134
let w = binary_img.width - 135
let h = binary_img.height - 136
let lines : Array[(Int32, Int32, Int32)] = [] - 137
for y in 0..<h { - 138●
let mut x = 0 - 139
while x < w { - 140●
if binary_img.data[y * w + x].to_int() < 128 { - 141●
let start_x = x - 142
let mut end_x = x - 143
let mut gap = 0 - 144
while x < w && gap <= max_g { - 145●
if binary_img.data[y * w + x].to_int() < 128 { - 146●
end_x = x - 147
gap = 0 - 148
} else { - 149●
gap += 1 - 150
} - 151
x += 1 - 152
} - 153
let length = end_x - start_x + 1 - 154
if length >= min_len { - 155●
lines.push((y, start_x, end_x)) - 156
} - 157
} else { - 158●
x += 1 - 159
} - 160
} - 161
} - 162
// 合并相近的线(y 差 <= 2) - 163
let merged : Array[(Int32, Int32, Int32)] = [] - 164
for line in lines { - 165●
let mut found = false - 166●
for i in 0..<merged.length() { - 167●
let (my, msx, mex) = merged[i] - 168●
if (line.0 - my).abs() <= 2 { - 169
// 合并 - 170○
let new_y = (line.0 + my) / 2 - 171○
let new_sx = if line.1 < msx { line.1 } else { msx } - 172○
let new_ex = if line.2 > mex { line.2 } else { mex } - 173
merged[i] = (new_y, new_sx, new_ex) - 174
found = true - 175
break - 176
} - 177
} - 178
if !found { - 179●
merged.push(line) - 180
} - 181
} - 182
merged - 183
} - 184
- 185
///| - 186
/// 检测垂直表格线 - 187
pub fn detect_vertical_table_lines( - 188
binary_img : @types.Image, - 189
min_length~ : Int32 = 50, - 190
max_gap~ : Int32 = 3, - 191
) -> Array[(Int32, Int32, Int32)] raise @types.LoadError { - 192
// 输入验证 - 193●
if binary_img.width <= 0 || binary_img.height <= 0 { - 194●
raise @types.LoadError::DecodeFailed( - 195
"detect_vertical_table_lines: 图像尺寸必须大于0", - 196
) - 197
} - 198
if binary_img.channels != 1 { - 199●
raise @types.LoadError::DecodeFailed( - 200
"detect_vertical_table_lines: 仅支持单通道二值图", - 201
) - 202
} - 203
let expected_size = binary_img.width * binary_img.height - 204●
if binary_img.data.length() != expected_size { - 205●
raise @types.LoadError::DecodeFailed( - 206
"detect_vertical_table_lines: 数据大小不匹配,期望 " + - 207●
expected_size.to_string() + - 208
",实际 " + - 209●
binary_img.data.length().to_string(), - 210
) - 211
} - 212
if min_length <= 0 { - 213●
raise @types.LoadError::DecodeFailed( - 214
"detect_vertical_table_lines: 最小线长必须大于0", - 215
) - 216
} - 217
if max_gap < 0 { - 218●
raise @types.LoadError::DecodeFailed( - 219
"detect_vertical_table_lines: 最大间隙不能为负", - 220
) - 221
} - 222
let min_len = min_length - 223
let max_g = max_gap - 224
let w = binary_img.width - 225
let h = binary_img.height - 226
let lines : Array[(Int32, Int32, Int32)] = [] - 227
for x in 0..<w { - 228●
let mut y = 0 - 229
while y < h { - 230●
if binary_img.data[y * w + x].to_int() < 128 { - 231●
let start_y = y - 232
let mut end_y = y - 233
let mut gap = 0 - 234
while y < h && gap <= max_g { - 235●
if binary_img.data[y * w + x].to_int() < 128 { - 236●
end_y = y - 237
gap = 0 - 238
} else { - 239●
gap += 1 - 240
} - 241
y += 1 - 242
} - 243
let length = end_y - start_y + 1 - 244
if length >= min_len { - 245●
lines.push((x, start_y, end_y)) - 246
} - 247
} else { - 248●
y += 1 - 249
} - 250
} - 251
} - 252
// 合并相近的线 - 253
let merged : Array[(Int32, Int32, Int32)] = [] - 254
for line in lines { - 255●
let mut found = false - 256●
for i in 0..<merged.length() { - 257●
let (mx, msy, mey) = merged[i] - 258●
if (line.0 - mx).abs() <= 2 { - 259○
let new_x = (line.0 + mx) / 2 - 260○
let new_sy = if line.1 < msy { line.1 } else { msy } - 261○
let new_ey = if line.2 > mey { line.2 } else { mey } - 262
merged[i] = (new_x, new_sy, new_ey) - 263
found = true - 264
break - 265
} - 266
} - 267
if !found { - 268●
merged.push(line) - 269
} - 270
} - 271
merged - 272
} - 273
- 274
///| - 275
/// 检测表格线交叉点 - 276
pub fn find_line_intersections( - 277
h_lines : Array[(Int32, Int32, Int32)], - 278
v_lines : Array[(Int32, Int32, Int32)], - 279
) -> Array[(Int32, Int32)] { - 280●
let intersections : Array[(Int32, Int32)] = [] - 281
for _tup0 in h_lines { - 282●
let (hy, hsx, hex) = _tup0 - 283
for _tup1 in v_lines { - 284●
let (vx, vsy, vey) = _tup1 - 285
if vx >= hsx && vx <= hex && hy >= vsy && hy <= vey { - 286●
intersections.push((vx, hy)) - 287
} - 288
} - 289
} - 290
intersections - 291
} - 292
- 293
///| - 294
/// 完整表格检测 - 295
pub fn detect_table_enhanced( - 296
binary_img : @types.Image, - 297
min_table_size~ : Int32 = 100, - 298
) -> Array[EnhancedTableResult] raise @types.LoadError { - 299
// 输入验证 - 300●
if binary_img.width <= 0 || binary_img.height <= 0 { - 301●
raise @types.LoadError::DecodeFailed( - 302
"detect_table_enhanced: 图像尺寸必须大于0", - 303
) - 304
} - 305
if binary_img.channels != 1 { - 306●
raise @types.LoadError::DecodeFailed( - 307
"detect_table_enhanced: 仅支持单通道二值图", - 308
) - 309
} - 310
let expected_size = binary_img.width * binary_img.height - 311●
if binary_img.data.length() != expected_size { - 312●
raise @types.LoadError::DecodeFailed( - 313
"detect_table_enhanced: 数据大小不匹配,期望 " + - 314●
expected_size.to_string() + - 315
",实际 " + - 316●
binary_img.data.length().to_string(), - 317
) - 318
} - 319
if min_table_size <= 0 { - 320●
raise @types.LoadError::DecodeFailed( - 321
"detect_table_enhanced: 最小表格尺寸必须大于0", - 322
) - 323
} - 324
let min_size = min_table_size - 325●
let h_lines = detect_horizontal_table_lines( - 326
binary_img, - 327
min_length=50, - 328
max_gap=3, - 329
) - 330●
let v_lines = detect_vertical_table_lines( - 331
binary_img, - 332
min_length=50, - 333
max_gap=3, - 334
) - 335●
let intersections = find_line_intersections(h_lines, v_lines) - 336
- 337
let results : Array[EnhancedTableResult] = [] - 338
- 339●
if h_lines.length() < 2 || v_lines.length() < 2 { - 340●
return results - 341
} - 342
- 343
// 提取唯一的行 y 坐标和列 x 坐标 - 344
let row_ys : Array[Int32] = [] - 345
for _tup2 in h_lines { - 346●
let (y, _, _) = _tup2 - 347
let mut exists = false - 348
for ry in row_ys { - 349●
if (ry - y).abs() <= 3 { - 350○
exists = true - 351
break - 352
} - 353
} - 354
if !exists { - 355●
row_ys.push(y) - 356
} - 357
} - 358
- 359
let col_xs : Array[Int32] = [] - 360
for _tup3 in v_lines { - 361●
let (x, _, _) = _tup3 - 362
let mut exists = false - 363
for cx in col_xs { - 364●
if (cx - x).abs() <= 3 { - 365○
exists = true - 366
break - 367
} - 368
} - 369
if !exists { - 370●
col_xs.push(x) - 371
} - 372
} - 373
- 374
// 排序 - 375●
for i in 0..<row_ys.length() { - 376●
for j in 0..<(row_ys.length() - i - 1) { - 377●
if row_ys[j] > row_ys[j + 1] { - 378○
let temp = row_ys[j] - 379
row_ys[j] = row_ys[j + 1] - 380
row_ys[j + 1] = temp - 381
} - 382
} - 383
} - 384●
for i in 0..<col_xs.length() { - 385●
for j in 0..<(col_xs.length() - i - 1) { - 386●
if col_xs[j] > col_xs[j + 1] { - 387○
let temp = col_xs[j] - 388
col_xs[j] = col_xs[j + 1] - 389
col_xs[j + 1] = temp - 390
} - 391
} - 392
} - 393
- 394●
let num_rows = row_ys.length() - 1 - 395●
let num_cols = col_xs.length() - 1 - 396
- 397
if num_rows < 1 || num_cols < 1 { - 398○
return results - 399
} - 400
- 401
let table_x = col_xs[0] - 402
let table_y = row_ys[0] - 403●
let table_width = col_xs[col_xs.length() - 1] - table_x - 404●
let table_height = row_ys[row_ys.length() - 1] - table_y - 405
- 406
if table_width < min_size || table_height < min_size { - 407○
return results - 408
} - 409
- 410
// 构建单元格 - 411
let cells : Array[TableCellContent] = [] - 412
for row in 0..<num_rows { - 413●
for col in 0..<num_cols { - 414●
let cell_x = col_xs[col] + 2 - 415
let cell_y = row_ys[row] + 2 - 416
let cell_w = col_xs[col + 1] - col_xs[col] - 4 - 417
let cell_h = row_ys[row + 1] - row_ys[row] - 4 - 418
let cell = TableCellContent::{ - 419
row, - 420
col, - 421
row_span: 1, - 422
col_span: 1, - 423
x: cell_x, - 424
y: cell_y, - 425
width: cell_w, - 426
height: cell_h, - 427
text: "", - 428
is_header: row == 0, - 429
is_merged: false, - 430
} - 431●
cells.push(cell) - 432
} - 433
} - 434
- 435
let detection = TableDetectionResult::{ - 436
horizontal_lines: h_lines, - 437
vertical_lines: v_lines, - 438
intersections, - 439
num_rows, - 440
num_cols, - 441
confidence: 0.85, - 442
} - 443
- 444
let result = EnhancedTableResult::{ - 445
x: table_x, - 446
y: table_y, - 447
width: table_width, - 448
height: table_height, - 449
rows: num_rows, - 450
cols: num_cols, - 451
cells, - 452
has_header: true, - 453
header_rows: 1, - 454
detection, - 455
confidence: 0.85, - 456
} - 457
- 458●
results.push(result) - 459
results - 460
} - 461
- 462
///| - 463
/// 表格转 Markdown(增强版,支持单元格内容) - 464
pub fn enhanced_table_to_markdown(table : EnhancedTableResult) -> String { - 465●
let mut md = "" - 466
// 表头 - 467
if table.has_header && table.rows > 0 { - 468●
md = md + "| " - 469
for col in 0..<table.cols { - 470●
let cell_text = get_cell_text(table, 0, col) - 471
md = md + cell_text + " | " - 472
} - 473
md = md + "\n| " - 474
for _ in 0..<table.cols { - 475●
md = md + "--- | " - 476
} - 477
md = md + "\n" - 478
// 数据行 - 479
for row in 1..<table.rows { - 480●
md = md + "| " - 481
for col in 0..<table.cols { - 482●
let cell_text = get_cell_text(table, row, col) - 483
md = md + cell_text + " | " - 484
} - 485
md = md + "\n" - 486
} - 487
} else { - 488●
for row in 0..<table.rows { - 489●
md = md + "| " - 490
for col in 0..<table.cols { - 491●
let cell_text = get_cell_text(table, row, col) - 492
md = md + cell_text + " | " - 493
} - 494
md = md + "\n" - 495
} - 496
} - 497
md - 498
} - 499
- 500
///| - 501
/// 获取单元格文本 - 502
fn get_cell_text( - 503
table : EnhancedTableResult, - 504
row : Int32, - 505
col : Int32, - 506
) -> String { - 507●
for cell in table.cells { - 508●
if cell.row == row && cell.col == col { - 509●
return cell.text - 510
} - 511
} - 512
"" - 513
} - 514
- 515
///| - 516
/// 提取图片区域(增强版,支持多种图片类型判断) - 517
pub fn extract_images_enhanced( - 518
binary_img : @types.Image, - 519
min_area~ : Int32 = 500, - 520
) -> Array[ExtractedImage] { - 521●
let min = min_area - 522
let w = binary_img.width - 523
let h = binary_img.height - 524
let images : Array[ExtractedImage] = [] - 525
let visited : Array[Bool] = [] - 526
for _ in 0..<(w * h) { - 527●
visited.push(false) - 528
} - 529
for y in 0..<h { - 530●
for x in 0..<w { - 531●
let idx = y * w + x - 532●
if !visited[idx] && binary_img.data[idx].to_int() < 128 { - 533●
let stack_x : Array[Int32] = [] - 534
let stack_y : Array[Int32] = [] - 535●
stack_x.push(x) - 536●
stack_y.push(y) - 537
visited[idx] = true - 538
let mut min_x = x - 539
let mut max_x = x - 540
let mut min_y = y - 541
let mut max_y = y - 542
let mut area = 0 - 543
let mut edge_pixels = 0 - 544●
while stack_x.length() > 0 { - 545●
let cx_opt = stack_x.pop() - 546●
let cy_opt = stack_y.pop() - 547●
match cx_opt { - 548
Some(cx) => - 549●
match cy_opt { - 550●
Some(cy) => { - 551
area += 1 - 552
if cx < min_x { - 553○
min_x = cx - 554
} - 555
if cx > max_x { - 556●
max_x = cx - 557
} - 558
if cy < min_y { - 559○
min_y = cy - 560
} - 561
if cy > max_y { - 562●
max_y = cy - 563
} - 564
// 边缘检测:检查是否有白色邻域 - 565
let mut is_edge = false - 566
let neighbors = [ - 567
(cx - 1, cy), - 568
(cx + 1, cy), - 569
(cx, cy - 1), - 570
(cx, cy + 1), - 571
] - 572
for _tup4 in neighbors { - 573●
let (nx, ny) = _tup4 - 574
if nx >= 0 && nx < w && ny >= 0 && ny < h { - 575●
let nidx = ny * w + nx - 576●
if !visited[nidx] && binary_img.data[nidx].to_int() >= 128 { - 577○
is_edge = true - 578
} - 579●
if !visited[nidx] && binary_img.data[nidx].to_int() < 128 { - 580●
visited[nidx] = true - 581●
stack_x.push(nx) - 582●
stack_y.push(ny) - 583
} - 584
} - 585
} - 586
if is_edge { - 587○
edge_pixels += 1 - 588
} - 589
} - 590○
None => () - 591
} - 592○
None => () - 593
} - 594
} - 595
let region_width = max_x - min_x + 1 - 596
let region_height = max_y - min_y + 1 - 597
if area >= min && region_width > 20 && region_height > 20 { - 598●
let fill_ratio = area.to_double() / - 599●
(region_width * region_height).to_double() - 600●
let aspect_ratio = region_width.to_double() / - 601●
region_height.to_double() - 602●
let edge_density = edge_pixels.to_double() / area.to_double() - 603
// 图片类型判断 - 604
let image_type = if fill_ratio > 0.9 && - 605
aspect_ratio > 0.8 && - 606
aspect_ratio < 1.2 { - 607●
"logo" - 608○
} else if fill_ratio > 0.8 { - 609○
"diagram" - 610○
} else if fill_ratio > 0.5 && edge_density > 0.3 { - 611○
"chart" - 612○
} else if aspect_ratio > 2.0 || aspect_ratio < 0.5 { - 613○
"signature" - 614
} else { - 615○
"photo" - 616
} - 617●
let file_name = "image_" + images.length().to_string() + ".png" - 618●
images.push(ExtractedImage::{ - 619
x: min_x, - 620
y: min_y, - 621
width: region_width, - 622
height: region_height, - 623
image_type, - 624
confidence: 0.75, - 625
aspect_ratio, - 626
fill_ratio, - 627
edge_density, - 628
file_name, - 629
}) - 630
} - 631
} - 632
} - 633
} - 634
images - 635
} - 636
- 637
///| - 638
/// 生成图片提取报告 - 639
pub fn generate_image_extraction_report( - 640
images : Array[ExtractedImage], - 641
) -> String { - 642●
let mut report = "## 图片提取报告\n\n" - 643
report = report + - 644
"共提取 " + - 645●
images.length().to_string() + - 646
" 张图片\n\n" - 647
report = report + - 648
"| 序号 | 类型 | 位置 | 尺寸 | 宽高比 | 填充率 | 置信度 | 文件名 |\n" - 649
report = report + - 650
"|------|------|------|------|--------|--------|--------|--------|\n" - 651●
for i in 0..<images.length() { - 652●
let img = images[i] - 653●
report = report + "| " + (i + 1).to_string() + " | " - 654
report = report + img.image_type + " | " - 655●
report = report + "(" + img.x.to_string() + "," + img.y.to_string() + ") | " - 656
report = report + - 657●
img.width.to_string() + - 658
"x" + - 659●
img.height.to_string() + - 660
" | " - 661●
report = report + img.aspect_ratio.to_string() + " | " - 662●
report = report + (img.fill_ratio * 100.0).to_string() + "% | " - 663●
report = report + (img.confidence * 100.0).to_string() + "% | " - 664
report = report + img.file_name + " |\n" - 665
} - 666
report - 667
} - 668
- 669
///| - 670
/// 统计表格识别结果 - 671
pub fn analyze_table_results( - 672
tables : Array[EnhancedTableResult], - 673
) -> Array[(String, Int32)] { - 674●
let total_tables = tables.length() - 675
let mut total_cells = 0 - 676
let mut total_rows = 0 - 677
let mut total_cols = 0 - 678
let mut with_header = 0 - 679
for table in tables { - 680●
total_cells += table.cells.length() - 681
total_rows += table.rows - 682
total_cols += table.cols - 683
if table.has_header { - 684●
with_header += 1 - 685
} - 686
} - 687
[ - 688
("表格总数", total_tables), - 689
("单元格总数", total_cells), - 690
("总行数", total_rows), - 691
("总列数", total_cols), - 692
("含表头表格", with_header), - 693
] - 694
}