到目前为止,这就是我所拥有的......
import cv2
list1=[]
img=cv2.imread("sudoku.jpg")
C,H,W = img.shape[::-1]
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,47,255,cv2.THRESH_BINARY) # filter out background noise
_, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for i in range(len(contours)): #for loop necessary to contour multiple boxes
perimeter=cv2.arcLength(contours[i],True)
if perimeter < 240 and perimeter > 150: #got these values by experimenting to find values that contour boxes but not the numbers within
#cv2.drawContours(img, contours, i, (0,255,0), 2)
list1.append(i)
#crop_img = img[0:61, 0:61]
for x in list1:
M=cv2.moments(contours[x])
cx = int(M["m10"]/M["m00"])
cy = int(M["m01"]/M["m00"])
cropped = img[cy-30:cy+30,cx-30:cx+29]
w,h,c = cropped.shape
for i in range (10):
template = cv2.imread("no"+str(i)+".png")
result = cv2.matchTemplate(cropped, template, cv2.TM_CCOEFF)
min_val,max_val,min_loc,max_loc = cv2.minMaxLoc(result)
if(max_val > 0.9):
grid1.append(i)
print grid1
cv2.imshow("img",cropped)
cv2.waitKey(0)
cv2.destroyAllWindows()
一切正常
cropped = img[cy-30:cy+30,cx-30:cx+29]
并运行此操作将返回我的数独谜题左上角单元格的裁剪图像。但是,当我尝试通过模板匹配将其应用于其余拼图时,我收到以下错误: Error
我用Google搜索了错误,但无法解决问题。我认为这可能与我正在使用的Python版本有关(2.7)。任何有关让程序应用模板匹配和提取所有单元格的帮助都将非常感激,因为我对Opencv和图像处理一般都是新手
由于
答案 0 :(得分:0)
从错误中看,matchTemplate
只接受灰色图片(depth == CV_8U || depth == CV_32F
,模板必须为灰色type == _tmpl.type()
)。您可以尝试将两者都转换为灰色。