使用Python OpenCV在图像中查找方形表(矩阵形状)的轮廓

问题描述 投票:0回答:2

我是新手,我想知道如何使用Python OpenCV(cv2库)找到如下图像的轮廓:

enter image description here

我打算在每个方格中填入一个数字,然后将其转换为numpy数组,所以我想我需要弄清楚如何首先得到矩阵中每个方块的轮廓(也许是图中方块的坐标)

我尝试使用一些代码片段:

img = cv2.imread(img_path, 1)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

binary = cv2.bitwise_not(gray)

contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for contour in contours:
    (x, y, w, h) = cv2.boundingRect(contour)
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

但它不起作用

python opencv opencv-contour
2个回答
1
投票

试试这个:

img = cv2.imread(img_path, 1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gauss = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 3, 0)
ret,thresh = cv2.threshold(gauss,0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)
rev=255-thresh

_ ,contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST ,cv2.CHAIN_APPROX_SIMPLE)
print(contours)
min_rect_len = 15
max_rect_len = 20

for contour in contours:
    (x, y, w, h) = cv2.boundingRect(contour)
    if h>min_rect_len and w>min_rect_len:
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 1)
cv2.imwrite(img_path[:-4] + "_with_contours.jpg", img)

它为给定的图像生成以下图像:enter image description here


1
投票

也许使用霍夫线可以完成这项工作: - >检查here

问候

© www.soinside.com 2019 - 2024. All rights reserved.