当存在多个外部边界时,如何使用 OpenCV 检测数独的精确边界?

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

我尝试使用 OpenCV 通过查找面积最大的方形轮廓来提取数独网格。但有些数独有多个外边界,因此程序仅检测最外边界。这会影响程序的后续部分,因为数独按行和列分为 9 个部分,以从每个单元格中提取数字。 如何修改 main_outline() 函数来检测数独轮廓,这是数独的实际边界而不是额外的外部边界?

def main_outline(contour):
                biggest = np.array([])
                max_area = 0
                for i in contour:
                    area = cv2.contourArea(i)
                    if area >50:
                        peri = cv2.arcLength(i, True)
                        approx = cv2.approxPolyDP(i , 0.02* peri, True)
                        if area > max_area and len(approx) ==4:
                            biggest = approx
                            max_area = area
                return biggest ,max_area

su_contour_1= su_puzzle.copy()
su_contour_2= su_puzzle.copy()
su_contour, hierarchy = cv2.findContours(preprocess(su_puzzle),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(su_contour_1, su_contour,-1,(0,255,0),3)
            
black_img = np.zeros((450,450,3), np.uint8)
su_biggest, su_maxArea = main_outline(su_contour)

这个问题可以用这些图片来解释:

输入图片:

Input image

使用当前程序提取图像:

Extracted image with current program

预期提取的图像:

Expected extracted image

我尝试使用递归函数来检测内部边界,但它失败了,因为在检测到确切的边界后,它会进一步找到轮廓,这些轮廓将被检测为单独的数独网格,导致错误的结果。我找不到好的停止标准。

python numpy opencv image-processing
1个回答
0
投票

如果边界始终是蓝色,这可能会很好地工作:

im = cv2.imread("sudoku.png") # read im
b,g,r = cv2.split(im) # split to bgr
bThresh = cv2.threshold(b, 0, 1, cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)[1] # get the threshold
cnts, _ = cv2.findContours(bThresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # find the contours
largestCnt = max(cnts, key = cv2.contourArea) # find the largest contour
x, y, w, h = cv2.boundingRect(largestCnt) # get bounding rect
croppedIm = im[y:y+h, x:x+w] # crop
cv2.imwrite("Cropped.png", croppedIm) # save

可视化以下代码:

imContoured = cv2.drawContours(cv2.merge((r,g,b)).copy(), largestCnt, -1, (255,0,0), 5) # draw largest contour with thick line, red
plt.figure()
plt.imshow(imContoured)
plt.axis("off")

给出以下信息:

最终保存的图像:

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