簡體   English   中英

如何使用 Python openCV 僅在此表格圖像中找到左上框的位置(x、y、寬度、高度)?

[英]How do I find the location (x, y, width, height) of the top left box only in this image of a table using Python openCV?

我有這張圖片,我需要找到左上角框的位置以及它的寬度和高度。 如何在 openCV 中使用 Python 執行此操作? 在此處輸入圖像描述

這是在 Python/OpenCV/Numpy 中執行此操作的一種方法。

  • 讀取輸入
  • 轉換為灰色
  • 二進制閾值
  • 計算每行和每列中黑色像素的總和
  • 將總和閾值設置為圖像高度和寬度的 80% 以上的計數
  • 查找這些總和中具有非零值的所有坐標
  • 過濾坐標以刪除彼此相距 10 像素以內的任何值,以避免重復超過 1 像素的線條
  • 獲取過濾后坐標的第一個和第二個坐標作為左上角矩形的邊界
  • 在這些邊界處裁剪輸入圖像
  • 保存結果

輸入:

在此處輸入圖像描述

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM