当前位置: 首页 > 面试题库 >

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

骆文彬
2023-03-14
问题内容

我有不同类型的发票文件,我想找到每个发票表
文件。在这张桌子上,位置不是恒定的。所以我去做图像处理。
我先找到了我的轮廓,然后我试着把它转换成我的轮廓
我终于可以抓住桌子的边框了。对于我下面使用的任务
代码。

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文件。

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

我怎么解决这个问题?能给我一个解决问题的主意真是太好了
问题。
提前谢谢。


问题答案:

瓦布哈夫是对的。你可以用不同的形态做实验
将像素提取或分组为不同的形状、线条等
例如,方法如下:
1从放大开始,将文本转换为实心点。
2然后应用findContours函数作为下一步来查找文本边框。
三。在有了文本边界框之后,可以应用一些启发式算法根据文本框的坐标将文本框分组。通过这种方式,您可以找到一组按行和列对齐的文本区域。
4然后,可以对组应用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)

当然为了使算法更加健壮和适用于各种场合
不同的输入图像必须相应地调整。
更新:更新了与OpenCV API更改有关的代码
`找到了一群人。如果安装了旧版本的OpenCV,请使用
相应的呼叫。[相关[发布](html" target="_blank">http://codingdict.com/questions172999)。



 类似资料:
  • 问题内容: 我目前正在建立一个基本上相当于搜索引擎和网络漫画画廊之间的交叉点的网站,该画廊侧重于引用来源并给予作者称赞。 我正在尝试找出一种搜索图像以在其中查找字符的方法。 例如: 假设我将红色字符和绿色字符另存为“ Red Man”和“ Green Man”,我如何确定图像是否包含一个或另一个。 不需要100%识别,或者什么是我想创建的更多功能,我不确定从哪里开始。我已经做了很多谷歌搜索来进行图

  • 问题内容: 我们可以使用java,imagemagick或jmagick找到哪种颜色在图像中占主导地位吗? 问题答案: 在Java中迭代每个像素并确定颜色

  • 问题内容: 您是否知道在 找不到 图像文件时如何从呈现的HTML页面中隐藏经典的 “未找到图像” 图标? 有使用JavaScript / jQuery / CSS的工作方法吗? 问题答案: 您可以使用JavaScript中的事件来在图像加载失败时采取行动: 在jQuery中(自您询问之后): 或对于所有图像: 如果隐藏图像可能会更改布局,则应使用代替。网络上的许多站点都使用默认的“无图像”图像,当

  • 我有一个下面的HTML代码,它指向屏幕上的SVG(图像)元素 我可以在div标记之前找到该元素,但是如果我尝试在SVG中访问该元素,并且它的子chrome无法找到该元素 XPath://div[@class='pie-div ng-star插入']-这在div之前工作得很好,但是如果我试图访问它的子元素SVG和路径,它根本找不到它(尽管代码在屏幕上可见) 我尝试过的Xpath://div[@cla

  • 我目前正在从事一个股票市场项目,教学生如何与股票市场互动。我现在正在研究的一个问题围绕着效率和记忆力的问题。我在Adobe illustrator中制作了所有2D图标(例如设置图标,投资组合图标等),我将这些文件导出为png文件,并将它们放入我的程序中。我目前使用 JavaFX,JavaFX 的一个功能是所谓的图像视图,这是一种处理图像打开和查看的方法。 假设用户想在游戏中按下设置图标,当用户悬停

  • 问题内容: 我有两个从PIL图像转换的Numpy数组(3维uint8)。 我想查找第一张图像是否包含第二张图像,如果是,则找出匹配的第一张图像内左上像素的坐标。 有没有一种方法可以在Numpy中以足够快的方式完成此操作,而不是使用(4!非常慢)纯Python循环? 2D示例: 怎么做这样的事情? 然后将是。 问题答案: 这可以使用SciPy的公司来完成correlate2d,然后用argmax找到