Python 2.7 如何使用Opencv和Python从数独游戏中提取所有单元格,并将图像存储在本地?
到目前为止,这就是我所拥有的Python 2.7 如何使用Opencv和Python从数独游戏中提取所有单元格,并将图像存储在本地?,python-2.7,opencv,Python 2.7,Opencv,到目前为止,这就是我所拥有的 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.fi
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()
运行它会返回我的数独游戏左上角单元格的裁剪图像。但是,当我试图通过模板匹配将其应用于拼图的其余部分时,我得到以下错误:
我用谷歌搜索了错误,但无法解决问题。我认为这可能与我正在使用的Python版本(2.7)有关。如果能让程序应用模板匹配并提取所有单元格,我将不胜感激,因为我对Opencv和图像处理一般来说都是新手
感谢这个错误,它看起来像是只接受灰色图像(
depth==CV_8U | | depth==CV_32F
同样,模板必须是灰色的type===tmpl.type()
)。您可以尝试将两者都转换为灰色
cropped = img[cy-30:cy+30,cx-30:cx+29]