Python 如何在图像中找到表状结构

Python 如何在图像中找到表状结构,python,image,opencv,image-processing,Python,Image,Opencv,Image Processing,我有不同类型的发票文件,我想在每个发票文件中查找表。在这张桌子上,位置不是恒定的。所以我选择了图像处理。首先,我尝试将我的发票转换为图像,然后根据表格边框找到轮廓,最后我可以捕捉表格位置。 对于我在下面代码中使用的任务 with Image(page) as page_image: page_image.alpha_channel = False #eliminates transperancy img_buffer=np.asarray(bytearray(page_image

我有不同类型的发票文件,我想在每个发票文件中查找表。在这张桌子上,位置不是恒定的。所以我选择了图像处理。首先,我尝试将我的发票转换为图像,然后根据表格边框找到轮廓,最后我可以捕捉表格位置。 对于我在下面代码中使用的任务

with Image(page) as page_image:
    page_image.alpha_channel = False #eliminates transperancy
    img_buffer=np.asarray(bytearray(page_image.make_blob()), dtype=np.uint8)
    img = cv2.imdecode(img_buffer, cv2.IMREAD_UNCHANGED)

    ret, thresh = cv2.threshold(img, 127, 255, 0)
    im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    margin=[]
    for contour in contours:
        # get rectangle bounding contour
        [x, y, w, h] = cv2.boundingRect(contour)
        # Don't plot small false positives that aren't text
        if (w >thresh1 and h> thresh2):
                margin.append([x, y, x + w, y + h])
    #data cleanup on margin to extract required position values.
在这个代码中,
thresh1
thresh2
我将根据文件进行更新

因此,使用这段代码,我可以成功地读取图像中表格的位置,使用这个位置,我将处理我的发票pdf文件。比如说

blur = cv2.GaussianBlur(g, (3, 3), 0)
ret, thresh1 = cv2.threshold(blur, 150, 255, cv2.THRESH_BINARY)
bitwise = cv2.bitwise_not(thresh1)
erosion = cv2.erode(bitwise, np.ones((1, 1) ,np.uint8), iterations=5)
dilation = cv2.dilate(erosion, np.ones((3, 3) ,np.uint8), iterations=5)
样本1:

样本2:

样本3:

输出:

样本1:

样本2:

样本3:

但是,现在我有了一个新的格式,它没有任何边框,但它是一个表。如何解决这个问题?因为我的整个操作只依赖于表的边框。但是现在我没有桌子了。我怎样才能做到这一点?我没有任何摆脱这个问题的想法。我的问题是,有没有办法根据表结构找到位置

例如,我的问题输入如下所示:

我想找到它的位置如下:

我怎样才能解决这个问题? 能给我一个解决这个问题的主意真是太好了


提前感谢。

您可以尝试应用一些形态学变换(如膨胀、侵蚀或高斯模糊)作为findContours功能之前的预处理步骤

比如说

blur = cv2.GaussianBlur(g, (3, 3), 0)
ret, thresh1 = cv2.threshold(blur, 150, 255, cv2.THRESH_BINARY)
bitwise = cv2.bitwise_not(thresh1)
erosion = cv2.erode(bitwise, np.ones((1, 1) ,np.uint8), iterations=5)
dilation = cv2.dilate(erosion, np.ones((3, 3) ,np.uint8), iterations=5)
最后一个参数,迭代显示将发生的膨胀/侵蚀程度(在您的案例中,在文本上)。具有较小的值将导致即使在字母表内也会产生较小的独立轮廓,而较大的值将聚集许多附近的元素。您需要找到理想的值,以便仅获取图像的该块


请注意,我选择了150作为阈值参数,因为我一直致力于从具有不同背景的图像中提取文本,效果更好。您可以选择继续使用已获取的值,因为它是黑白图像。

Vaibhav是正确的。您可以使用不同的形态变换进行实验,以将像素提取或分组为不同的形状、线条等。例如,方法可以如下所示:

  • 从展开开始,将文本转换为实心点
  • 然后应用findContours函数作为查找文本的下一步 边界框
  • 使用文本边界框后,可以应用一些 启发式算法将文本框按其属性分组 协调。这样,您可以找到一组对齐的文本区域 分为行和列
  • 然后,您可以通过x和y坐标和/或某些坐标应用排序 对组进行分析,以尝试查找分组的文本框是否可以 摆一张桌子
  • 我写了一个小样本来说明这个想法。我希望代码是不言自明的。我也在那里发表了一些评论

    import os
    import cv2
    import imutils
    
    # This only works if there's only one table on a page
    # Important parameters:
    #  - morph_size
    #  - min_text_height_limit
    #  - max_text_height_limit
    #  - cell_threshold
    #  - min_columns
    
    
    def pre_process_image(img, save_in_file, morph_size=(8, 8)):
    
        # get rid of the color
        pre = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # Otsu threshold
        pre = cv2.threshold(pre, 250, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
        # dilate the text to make it solid spot
        cpy = pre.copy()
        struct = cv2.getStructuringElement(cv2.MORPH_RECT, morph_size)
        cpy = cv2.dilate(~cpy, struct, anchor=(-1, -1), iterations=1)
        pre = ~cpy
    
        if save_in_file is not None:
            cv2.imwrite(save_in_file, pre)
        return pre
    
    
    def find_text_boxes(pre, min_text_height_limit=6, max_text_height_limit=40):
        # Looking for the text spots contours
        # OpenCV 3
        # img, contours, hierarchy = cv2.findContours(pre, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
        # OpenCV 4
        contours, hierarchy = cv2.findContours(pre, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    
        # Getting the texts bounding boxes based on the text size assumptions
        boxes = []
        for contour in contours:
            box = cv2.boundingRect(contour)
            h = box[3]
    
            if min_text_height_limit < h < max_text_height_limit:
                boxes.append(box)
    
        return boxes
    
    
    def find_table_in_boxes(boxes, cell_threshold=10, min_columns=2):
        rows = {}
        cols = {}
    
        # Clustering the bounding boxes by their positions
        for box in boxes:
            (x, y, w, h) = box
            col_key = x // cell_threshold
            row_key = y // cell_threshold
            cols[row_key] = [box] if col_key not in cols else cols[col_key] + [box]
            rows[row_key] = [box] if row_key not in rows else rows[row_key] + [box]
    
        # Filtering out the clusters having less than 2 cols
        table_cells = list(filter(lambda r: len(r) >= min_columns, rows.values()))
        # Sorting the row cells by x coord
        table_cells = [list(sorted(tb)) for tb in table_cells]
        # Sorting rows by the y coord
        table_cells = list(sorted(table_cells, key=lambda r: r[0][1]))
    
        return table_cells
    
    
    def build_lines(table_cells):
        if table_cells is None or len(table_cells) <= 0:
            return [], []
    
        max_last_col_width_row = max(table_cells, key=lambda b: b[-1][2])
        max_x = max_last_col_width_row[-1][0] + max_last_col_width_row[-1][2]
    
        max_last_row_height_box = max(table_cells[-1], key=lambda b: b[3])
        max_y = max_last_row_height_box[1] + max_last_row_height_box[3]
    
        hor_lines = []
        ver_lines = []
    
        for box in table_cells:
            x = box[0][0]
            y = box[0][1]
            hor_lines.append((x, y, max_x, y))
    
        for box in table_cells[0]:
            x = box[0]
            y = box[1]
            ver_lines.append((x, y, x, max_y))
    
        (x, y, w, h) = table_cells[0][-1]
        ver_lines.append((max_x, y, max_x, max_y))
        (x, y, w, h) = table_cells[0][0]
        hor_lines.append((x, max_y, max_x, max_y))
    
        return hor_lines, ver_lines
    
    
    if __name__ == "__main__":
        in_file = os.path.join("data", "page.jpg")
        pre_file = os.path.join("data", "pre.png")
        out_file = os.path.join("data", "out.png")
    
        img = cv2.imread(os.path.join(in_file))
    
        pre_processed = pre_process_image(img, pre_file)
        text_boxes = find_text_boxes(pre_processed)
        cells = find_table_in_boxes(text_boxes)
        hor_lines, ver_lines = build_lines(cells)
    
        # Visualize the result
        vis = img.copy()
    
        # for box in text_boxes:
        #     (x, y, w, h) = box
        #     cv2.rectangle(vis, (x, y), (x + w - 2, y + h - 2), (0, 255, 0), 1)
    
        for line in hor_lines:
            [x1, y1, x2, y2] = line
            cv2.line(vis, (x1, y1), (x2, y2), (0, 0, 255), 1)
    
        for line in ver_lines:
            [x1, y1, x2, y2] = line
            cv2.line(vis, (x1, y1), (x2, y2), (0, 0, 255), 1)
    
        cv2.imwrite(out_file, vis)
    
    导入操作系统
    进口cv2
    导入imutils
    #这仅在页面上只有一个表时有效
    #重要参数:
    #-变形大小
    #-最小文本高度限制
    #-最大文字高度限制
    #-细胞单位阈值
    #-min_列
    def pre_process_image(img,将_保存在_文件中,变形大小=(8,8)):
    #去掉颜色
    pre=cv2.CVT颜色(img,cv2.COLOR\U BGR2GRAY)
    #大津阈值
    pre=cv2.阈值(pre,250255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
    #放大文本使其成为实心点
    cpy=pre.copy()
    struct=cv2.getStructuringElement(cv2.morp\u RECT,morp\u size)
    cpy=cv2.deflate(~cpy,struct,anchor=(-1,-1),迭代次数=1)
    pre=~cpy
    如果在_文件中保存_不是无:
    cv2.imwrite(将\u保存在\u文件中,预处理)
    返回前
    def查找文本框(前置,最小文本高度限制=6,最大文本高度限制=40):
    #寻找文本点轮廓
    #OpenCV 3
    #img、轮廓、层次=cv2.findContours(前、cv2.RETR\u列表、cv2.CHAIN\u近似值\u简单值)
    #OpenCV 4
    轮廓,层次=cv2.findContours(前、cv2.RETR\u列表、cv2.CHAIN\u近似值\u简单值)
    #基于文本大小假设获取文本边界框
    框=[]
    对于等高线中的等高线:
    box=cv2.boundingRect(轮廓)
    h=框[3]
    如果最小文字高度限制=min_列,rows.values())
    #按x坐标对行单元格进行排序
    表_单元格=[表_单元格中tb的列表(已排序(tb)]]
    #按y坐标排序行
    table_cells=列表(已排序(table_cells,key=lambda r:r[0][1]))
    返回表单元
    def生成行(表格单元格):
    
    如果table_cells为None或len(table_cells)文档图像中有许多类型的表,它们的变化和布局太多。不管你写了多少条规则,总会出现一个你的规则失败的表格。这些类型的问题通常使用基于ML(机器学习)的解决方案来解决。您可以在github上找到许多预实现的代码,用于解决使用ML或DL(深度学习)在图像中检测表的问题

    下面是我的代码以及深度学习模型,该模型可以检测各种类型的表以及表中的结构单元:

    就精度而言,该方法目前(2020年5月10日)在各种公共数据集上达到了最先进水平

    更多详情