Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

perf: optimize connected-component and box matching in UNet table recovery

myhloli3cb9d1d847a2
diff --git a/mineru/model/table/rec/unet_table/table_structure_unet.py b/mineru/model/table/rec/unet_table/table_structure_unet.py
index cd5a177e..c7b2bd9f 100644
--- a/mineru/model/table/rec/unet_table/table_structure_unet.py
+++ b/mineru/model/table/rec/unet_table/table_structure_unet.py
@@ -5,16 +5,16 @@ from typing import Optional, Dict, Any, Tuple
import cv2
import numpy as np
-from skimage import measure
from mineru.utils.os_env_config import get_op_num_threads
from .utils import OrtInferSession, resize_img
from .utils_table_line_rec import (
get_table_line,
final_adjust_lines,
- min_area_rect_box,
draw_lines,
adjust_lines,
+ _iter_connected_component_coords,
+ min_area_rect_box_from_components,
)
from.utils_table_recover import (
sorted_ocr_boxes,
@@ -150,10 +150,9 @@ class TSRUnet:
return polygons, rotated_polygons
def cal_region_boxes(self, tmp):
- labels = measure.label(tmp < 255, connectivity=2) # 8连通区域标记
- regions = measure.regionprops(labels)
- ceilboxes = min_area_rect_box(
- regions,
+ components = _iter_connected_component_coords(tmp < 255) # 8连通区域标记
+ ceilboxes = min_area_rect_box_from_components(
+ components,
False,
tmp.shape[1],
tmp.shape[0],
diff --git a/mineru/model/table/rec/unet_table/utils_table_line_rec.py b/mineru/model/table/rec/unet_table/utils_table_line_rec.py
index 5b4e7447..077b3c6c 100644
--- a/mineru/model/table/rec/unet_table/utils_table_line_rec.py
+++ b/mineru/model/table/rec/unet_table/utils_table_line_rec.py
@@ -1,5 +1,6 @@
# Copyright (c) Opendatalab. All rights reserved.
import math
+from typing import Iterator
import cv2
import numpy as np
@@ -9,6 +10,64 @@ from skimage import __version__ as skimage_version
from packaging import version
+class ConnectedComponent:
+ """保存连通域的 bbox、bbox 面积和懒加载坐标,字段语义对齐 skimage.regionprops。"""
+
+ def __init__(
+ self,
+ labels: np.ndarray,
+ label_id: int,
+ bbox: tuple[int, int, int, int],
+ bbox_area: int,
+ ):
+ """记录组件基础信息,像素坐标延迟到真正参与几何计算时再生成。"""
+ self._labels = labels
+ self._label_id = label_id
+ self.bbox = bbox
+ self.bbox_area = bbox_area
+ self._coords = None
+
+ @property
+ def coords(self) -> np.ndarray:
+ """在组件 bbox 内提取 row/col 坐标,保持 skimage 的行优先顺序。"""
+ if self._coords is None:
+ min_row, min_col, max_row, max_col = self.bbox
+ label_roi = self._labels[min_row:max_row, min_col:max_col]
+ ys, xs = np.nonzero(label_roi == self._label_id)
+ self._coords = np.column_stack((ys + min_row, xs + min_col))
+ return self._coords
+
+
+def _iter_connected_component_coords(binary_mask: np.ndarray) -> Iterator[ConnectedComponent]:
+ """用 OpenCV 提取 8 连通域,避免构造 skimage region 对象带来的额外开销。"""
+ mask = np.asarray(binary_mask)
+ if mask.size == 0:
+ return
+
+ mask = np.ascontiguousarray(mask.astype(np.uint8, copy=False))
+ if not np.any(mask):
+ return
+
+ label_count, labels, stats, _ = cv2.connectedComponentsWithStats(
+ mask,
+ connectivity=8,
+ )
+ if label_count <= 1:
+ return
+
+ for label_id in range(1, label_count):
+ left = int(stats[label_id, cv2.CC_STAT_LEFT])
+ top = int(stats[label_id, cv2.CC_STAT_TOP])
+ width = int(stats[label_id, cv2.CC_STAT_WIDTH])
+ height = int(stats[label_id, cv2.CC_STAT_HEIGHT])
+ yield ConnectedComponent(
+ labels=labels,
+ label_id=label_id,
+ bbox=(top, left, top + height, left + width),
+ bbox_area=width * height,
+ )
+
+
def transform_preds(coords, center, scale, output_size, rot=0):
target_coords = np.zeros(coords.shape)
trans = get_affine_transform(center, scale, rot, output_size, inv=1)
@@ -75,19 +134,18 @@ def get_table_line(binimg, axis=0, lineW=10):
##获取表格线
##axis=0 横线
##axis=1 竖线
- labels = measure.label(binimg > 0, connectivity=2) # 8连通区域标记
- regions = measure.regionprops(labels)
+ components = _iter_connected_component_coords(binimg > 0)
if axis == 1:
lineboxes = [
- min_area_rect(line.coords)
- for line in regions
- if line.bbox[2] - line.bbox[0] > lineW
+ min_area_rect(component.coords)
+ for component in components
+ if component.bbox[2] - component.bbox[0] > lineW
]
else:
lineboxes = [
- min_area_rect(line.coords)
- for line in regions
- if line.bbox[3] - line.bbox[1] > lineW
+ min_area_rect(component.coords)
+ for component in components
+ if component.bbox[3] - component.bbox[1] > lineW
]
return lineboxes
@@ -331,6 +389,30 @@ def min_area_rect_box(
return boxes
+def min_area_rect_box_from_components(
+ components, flag=True, W=0, H=0, filtersmall=False, adjust_box=False
+):
+ """对 OpenCV 连通域组件执行与 min_area_rect_box 相同的过滤和外接框计算。"""
+ boxes = []
+ for component in components:
+ if component.bbox_area > H * W * 3 / 4: # 过滤大的单元格
+ continue
+ rect = cv2.minAreaRect(component.coords[:, ::-1])
+
+ box = cv2.boxPoints(rect)
+ box = box.reshape((8,)).tolist()
+ box = image_location_sort_box(box)
+ x1, y1, x2, y2, x3, y3, x4, y4 = box
+ angle, w, h, cx, cy = calculate_center_rotate_angle(box)
+ if w * h < 0.5 * W * H:
+ if filtersmall and (
+ w < 15 or h < 15
+ ): # or w / h > 30 or h / w > 30): # 过滤小的单元格
+ continue
+ boxes.append([x1, y1, x2, y2, x3, y3, x4, y4])
+ return boxes
+
+
def point_line_cor(p, A, B, C):
##判断点与线之间的位置关系
# 一般式直线方程(Ax+By+c)=0
diff --git a/mineru/model/table/rec/unet_table/utils_table_recover.py b/mineru/model/table/rec/unet_table/utils_table_recover.py
index f1f6b2bb..795ece60 100644
--- a/mineru/model/table/rec/unet_table/utils_table_recover.py
+++ b/mineru/model/table/rec/unet_table/utils_table_recover.py
@@ -171,33 +171,98 @@ def box_4_2_poly_to_box_4_1(poly_box: Union[list, np.ndarray]) -> List[Any]:
return [poly_box[0][0], poly_box[0][1], poly_box[2][0], poly_box[2][1]]
+def _ocr_boxes_to_array(dt_rec_boxes: List[List[Union[Any, str]]]) -> np.ndarray:
+ """将 OCR 四点框批量转换为 [xmin, ymin, xmax, ymax],保持旧逻辑使用第 0/2 点。"""
+ if len(dt_rec_boxes) == 0:
+ return np.empty((0, 4), dtype=np.float64)
+ return np.asarray(
+ [
+ [
+ gt_box[0][0][0],
+ gt_box[0][0][1],
+ gt_box[0][2][0],
+ gt_box[0][2][1],
+ ]
+ for gt_box in dt_rec_boxes
+ ],
+ dtype=np.float64,
+ )
+
+
+def _pred_boxes_to_array(pred_bboxes: np.ndarray) -> np.ndarray:
+ """将预测 cell 四点框批量转换为 [xmin, ymin, xmax, ymax],保持旧逻辑使用第 0/2 点。"""
+ pred_bboxes = np.asarray(pred_bboxes)
+ if pred_bboxes.size == 0:
+ return np.empty((0, 4), dtype=np.float64)
+ return np.asarray(
+ [
+ [pred_box[0][0], pred_box[0][1], pred_box[2][0], pred_box[2][1]]
+ for pred_box in pred_bboxes
+ ],
+ dtype=np.float64,
+ )
+
+
def match_ocr_cell(dt_rec_boxes: List[List[Union[Any, str]]], pred_bboxes: np.ndarray):
"""
:param dt_rec_boxes: [[(4.2), text, score]]
:param pred_bboxes: shap (4,2)
:return:
"""
+ ocr_boxes = _ocr_boxes_to_array(dt_rec_boxes)
+ pred_boxes = _pred_boxes_to_array(pred_bboxes)
+ if ocr_boxes.size == 0 or pred_boxes.size == 0:
+ return {}, []
+
+ ocr = ocr_boxes[:, None, :]
+ pred = pred_boxes[None, :, :]
+
+ no_intersection = (
+ (ocr[..., 2] < pred[..., 0])
+ | (ocr[..., 0] > pred[..., 2])
+ | (ocr[..., 3] < pred[..., 1])
+ | (ocr[..., 1] > pred[..., 3])
+ )
+ intersects = ~no_intersection
+
+ inter_x1 = np.maximum(ocr[..., 0], pred[..., 0])
+ inter_y1 = np.maximum(ocr[..., 1], pred[..., 1])
+ inter_x2 = np.minimum(ocr[..., 2], pred[..., 2])
+ inter_y2 = np.minimum(ocr[..., 3], pred[..., 3])
+ inter_area = np.maximum(0, inter_x2 - inter_x1) * np.maximum(0, inter_y2 - inter_y1)
+
+ ocr_area = (ocr[..., 2] - ocr[..., 0]) * (ocr[..., 3] - ocr[..., 1])
+ pred_area = (pred[..., 2] - pred[..., 0]) * (pred[..., 3] - pred[..., 1])
+
+ # 等价实现 is_box_contained(ocr_box, pred_box, 0.6) == 1。
+ ocr_outside_ratio = np.divide(
+ ocr_area - inter_area,
+ ocr_area,
+ out=np.zeros_like(inter_area, dtype=np.float64),
+ where=ocr_area > 0,
+ )
+ contained = intersects & (ocr_outside_ratio < 0.6)
+
+ # 等价实现 calculate_iou(),包括 union 为 0 时返回 1 的历史行为。
+ union_area = ocr_area + pred_area - inter_area
+ iou = np.divide(
+ inter_area,
+ union_area,
+ out=np.ones_like(inter_area, dtype=np.float64),
+ where=union_area != 0,
+ )
+ iou[no_intersection] = 0.0
+ matched_mask = contained | (iou > 0.8)
+
matched = {}
not_match_orc_boxes = []
for i, gt_box in enumerate(dt_rec_boxes):
- for j, pred_box in enumerate(pred_bboxes):
- pred_box = [pred_box[0][0], pred_box[0][1], pred_box[2][0], pred_box[2][1]]
- ocr_boxes = gt_box[0]
- # xmin,ymin,xmax,ymax
- ocr_box = (
- ocr_boxes[0][0],
- ocr_boxes[0][1],
- ocr_boxes[2][0],
- ocr_boxes[2][1],
- )
- contained = is_box_contained(ocr_box, pred_box, 0.6)
- if contained == 1 or calculate_iou(ocr_box, pred_box) > 0.8:
- if j not in matched:
- matched[j] = [gt_box]
- else:
- matched[j].append(gt_box)
- else:
- not_match_orc_boxes.append(gt_box)
+ matched_indices = np.flatnonzero(matched_mask[i])
+ for j in matched_indices:
+ matched.setdefault(int(j), []).append(gt_box)
+ not_match_orc_boxes.extend(
+ [gt_box] * int(pred_boxes.shape[0] - matched_indices.size)
+ )
return matched, not_match_orc_boxes
@@ -307,6 +372,3 @@ def plot_html_table(
table_html += "</table></body></html>"
return table_html
-
-
-