Python基于分水岭算法解决走迷宫游戏示例
本文实例讲述了Python基于分水岭算法解决走迷宫游戏。分享给大家供大家参考,具体如下:
#Solvingmazewithmorphologicaltransformation
"""
usage:Solvingmazewithmorphologicaltransformation
neededmodule:cv2/numpy/sys
ref:
1.http://www.mazegenerator.net/
2.http://blog.leanote.com/post/leeyoung/539a629aab35bc44e2000000
@author:RobinChen
"""
importcv2
importnumpyasnp
importsys
defSolvingMaze(image):
#loadanimage
try:
img=cv2.imread(image)
exceptException,e:
print'Error:cannotopentheimage!'
sys.exit()
#showimage
#cv2.namedWindow('image',cv2.WINDOW_NORMAL)
cv2.imshow('maze_image',img)
#converttogray
gray_image=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#showgrayimage
#cv2.imshow('gray_image',gray_image)
#converttobinaryimage
retval,binary_image=cv2.threshold(gray_image,10,255,cv2.THRESH_BINARY_INV)
#cv2.imshow('binary_image',binary_image)
contours,hierarchy=cv2.findContours(binary_image,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
iflen(contours)!=2:
sys.exit("Thisisnota'perfectmaze'withjust2walls!")
h,w,d=img.shape
#Thefirstwall
path=np.zeros((h,w),dtype=np.uint8)#cv2.CV_8UC1
cv2.drawContours(path,contours,0,(255,255,255),-1)#cv2.FILLED
#cv2.imshow('Thefirstwall',path)
#Dilatethewallbyafewpixels
kernel=np.ones((19,19),dtype=np.uint8)
path=cv2.dilate(path,kernel)
#cv2.imshow('Dilatethewallbyafewpixels',path)
#Erodebythesameamountofpixels
path_erode=cv2.erode(path,kernel);
#cv2.imshow('Erodebythesameamountofpixels',path_erode)
#absdiff
path=cv2.absdiff(path,path_erode);
#cv2.imshow('absdiff',path)
#solution
channels=cv2.split(img);
channels[0]&=~path;
channels[1]&=~path;
channels[2]|=path;
dst=cv2.merge(channels);
cv2.imshow("solution",dst);
#waitingforanykeytoclosewindows
cv2.waitKey(0)
cv2.destroyAllWindows()
if__name__=='__main__':
image=sys.argv[-1]
SolvingMaze(image)
更多关于Python相关内容可查看本站专题:《Python游戏开发技巧总结》、《Python数据结构与算法教程》、《PythonSocket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。