繁体   English   中英

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

[英]Find contours of a square table (matrix shape) in an image using Python OpenCV

我是新手,我想知道如何使用 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)

它为给定图像生成以下图像: 在此处输入图片说明

也许使用霍夫线会做的工作:-> 在这里检查

问候

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM