如何仅在使用Python openCV的表格图像中找到左上角框的位置(x、y、宽度、高度)?

如何仅在使用Python openCV的表格图像中找到左上角框的位置(x、y、宽度、高度)?,python,opencv,image-processing,python-tesseract,Python,Opencv,Image Processing,Python Tesseract,我有这张图片,我只需要找到左上框的位置以及宽度和高度。如何在openCV中使用Python实现这一点?这里有一种在Python/openCV/Numpy中实现这一点的方法 读取输入 变灰 二进制阈值 计算每行和每列中黑色像素的总和 阈值计数总和超过图像高度和宽度的80% 查找这些和中具有非零值的所有坐标 过滤坐标以删除彼此之间在10像素范围内的任何值,以避免从大于1像素的线中复制 获取过滤坐标的第一个和第二个坐标作为左上矩形的边界 在这些边界处裁剪输入图像 保存结果 输入: 我不知道从哪里

我有这张图片,我只需要找到左上框的位置以及宽度和高度。如何在openCV中使用Python实现这一点?

这里有一种在Python/openCV/Numpy中实现这一点的方法

  • 读取输入
  • 变灰
  • 二进制阈值
  • 计算每行和每列中黑色像素的总和
  • 阈值计数总和超过图像高度和宽度的80%
  • 查找这些和中具有非零值的所有坐标
  • 过滤坐标以删除彼此之间在10像素范围内的任何值,以避免从大于1像素的线中复制
  • 获取过滤坐标的第一个和第二个坐标作为左上矩形的边界
  • 在这些边界处裁剪输入图像
  • 保存结果
输入:


我不知道从哪里开始。谢谢,但我在运行代码时遇到一个错误:column\u coords\u filt=[column\u coords[0]]索引器:索引0超出大小为0的轴0的界限是同一个图像吗?是的,我把名字改成了保存在我电脑上的图像的名字,我必须看到你使用的图像。它和我上传到这个页面的图像是一样的,只是在我的程序中它的名字和你在代码中给它命名的名字不同。这是唯一的区别。同样的图像。
import cv2
import numpy as np

# read input
img = cv2.imread("table_cells.png")
hh, ww = img.shape[:2]

# convert to gray
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# threshold to binary
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]

# get sum of black values in rows and columns
row_sums = np.sum(thresh==0, axis=1)
column_sums = np.sum(thresh==0, axis=0)

# threshold sums to counts above 80% of hh and ww
row_sums[np.where(row_sums<0.8*ww)] = 0
column_sums[np.where(column_sums<0.8*hh)] = 0

# find coordinates that have non-zero values
row_coords = np.argwhere(row_sums>0)
column_coords = np.argwhere(column_sums>0)
num_rows = len(row_coords)
num_cols = len(column_coords)

# filter row_coords to avoid duplicates within 10 pixels
row_coords_filt = [row_coords[0]]
for i in range(num_rows-1):
    if (row_coords[i] > row_coords[i-1]+10):
        row_coords_filt.append(row_coords[i])

column_coords_filt = [column_coords[0]]
for i in range(num_cols-1):
    if (column_coords[i] > column_coords[i-1]+10):
        column_coords_filt.append(column_coords[i])

# print row_coords_filt
print('grid row coordinates:')
for c in row_coords_filt:
    print (c)

print('')

# print column_coords_filt
print('grid column coordinates:')
for c in column_coords_filt:
    print (c)

# get left, right, top, bottom of upper left rectangle
left = int(column_coords_filt[0])
right = int(column_coords_filt[1])
top = int(row_coords_filt[0])
bottom = int(row_coords_filt[1])

# crop rectangle
rectangle = img[top:bottom, left:right]

# save output
cv2.imwrite('table_cells_crop.png', rectangle)

cv2.imshow('thresh', thresh)
cv2.imshow('rectangle', rectangle)
cv2.waitKey(0)
cv2.destroyAllWindows()
grid row coordinates:
[30]
[315]
[599]
[884]

grid column coordinates:
[41]
[790]
[1540]
[2289]