python - 在python中从数独难题中提取网格

标签 python opencv numpy

我目前正在使用python学习OpenCV,并且尝试在此图像上绘制网格的轮廓以从中提取数独难题
enter image description here

这是我针对此特定问题编写的代码:

CONST_IMAGE_PATH = "sudoku-original.jpg"
CONST_COEFF = 0.02
def main():
   originalImage = cv2.imread(CONST_IMAGE_PATH)
   img = cv2.imread(CONST_IMAGE_PATH,0)
   img = cv2.medianBlur(img,5)
   img = cv2.adaptiveThreshold(img , 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)
   img = cv2.bitwise_not(img,img)
   print "thresholding the image"
   cv2.imshow("Thresholded", img)
   kernel = np.empty((3,3),'uint8')
   kernel[0][0] = 0
   kernel[0][1] = 1
   kernel[0][2] = 0
   kernel[1][0] = 1
   kernel[1][1] = 1
   kernel[1][2] = 1
   kernel[2][0] = 0
   kernel[2][1] = 1
   kernel[2][2] = 0
   dilated = cv2.dilate(img,kernel)
   cv2.imshow("Dilated", dilated)
   print "detecting the grid"
   (contours, _) = cv2.findContours(img.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
   contours = sorted(contours, key = cv2.contourArea , reverse = True)
   screenCnt = None


   for contour in contours: 
        perimeter = cv2.arcLength(contour,True)
        approx = cv2.approxPolyDP(contour, CONST_COEFF*perimeter , True)
        if len(approx) == 4: 
            if perimeter > maxPerimeter: 
                maxPerimeter = perimeter
                screenCnt = approx


   cv2.drawContours(originalImage , [screenCnt], -1, (0,255,0), 3)
   cv2.imshow("SudokuPuzzle", originalImage)
   cv2.waitKey(0)

但是,发生的是与其绘制整个网格,而不是绘制在右下方的框上。
enter image description here

为什么会发生这种情况,我可以在代码中进行哪些更改以绘制整个网格?

最佳答案

一件错误的事情,显然是:

(contours, _) = cv2.findContours(dilated.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

应该是dilated.copy()而不是img.copy()。起初我以为这没什么大不了的,最大轮廓应该仍然是网格边缘,但是测试表明,如果不对图像进行扩张,那么最大轮廓就是这个东西

enter image description here

这就是为什么在if len(approx) == 4子句中忽略它的原因。

关于python - 在python中从数独难题中提取网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37377214/

相关文章:

python - 在Python中读取大型JSON文件

不带关键字参数的 Python 库函数

python - 使用opencv阈值图像以获得与imagemagick相同的结果

python - 缝合最终尺寸和偏移

python - numpy.minimum 用于复数

python - 为什么 Python 请求没有按预期工作

c++ - 将数据从 OpenCV C++ 传递到 NodeJS/JS | Electron

python - 当存在重叠干扰时如何使用 OpenCV 获取矩形框轮廓

python - 具有不同数据类型的 Numpy 数组

python - 稀疏数组的 numpy 向量列表