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

使用Python OpenCV查找图像中方桌(矩阵形状)的轮廓,python,opencv,opencv-contour,Python,Opencv,Opencv Contour,我是新手,我想知道如何使用Python OpenCV(cv2库)找到下面这样的图像轮廓: 我将在每个正方形中填入一个数字,然后将其转换为numpy数组,因此我想我需要先弄清楚如何获得矩阵中每个正方形的轮廓(可能是图片中正方形的坐标) 我尝试使用一些代码片段: img = cv2.imread(img_path, 1) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) binary = cv2.bitwise_not(gray) contours,

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

我将在每个正方形中填入一个数字,然后将其转换为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)
但是它不起作用

试试这个:

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)
它为给定图像生成以下图像: 试试这个:

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)
它为给定图像生成以下图像:

也许使用hough线可以完成以下任务: ->检查


关于

也许使用hough线可以完成以下工作: ->检查

问候