使用 python 从包含 table 网格的图像中提取数据

Extract data from image containing table grid using python

我有下面附上的图片。我需要提取网格内的数据以及表格结构并将其转换为 dataframe/csv.

我正在使用 OCR 来提取文本和坐标,但为了提取 table 结构,我想提取水平和垂直网格线。

OpenCV 中是否有一种方法可以很好地泛化?

到目前为止,我遇到的方法是: 1.霍夫线 2.提取矩形轮廓 3.绘制垂直和水平轮廓

您可以使用 openCV 定义网格结构并从所有单独区域提取信息,查看这篇文章 A Box detection algorithm for any image containing boxes

一切都完美解释

恕我直言@Chrys Bltr,link 中的解决方案有点矫枉过正。这是一个更简单的解决方案,所以我认为:

import numpy as np
import cv2
import matplotlib.pyplot as plt

img_rgb = cv2.imread('your/image')
img = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)

th = cv2.adaptiveThreshold(img,255, cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,3,3)

_, ctrs, _ = cv2.findContours(img,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
im_h, im_w = img.shape
im_area = im_w * im_h
for ctr in ctrs:
    x, y, w, h = cv2.boundingRect(ctr)
    # Filter contours based on size
    if 0.01 * im_area < w * h < 0.1*im_area:
        cv2.rectangle(img_rgb, (x, y), (x+w, y+h), (0, 255, 0), 2)

plt.imshow(img_rgb, cmap='gray', vmin=0, vmax=255)

您可以在上面的过滤过程中存储矩形信息,然后在每个单独的矩形区域内进行OCR。