脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python基于分水岭算法解决走迷宫游戏示例

Python基于分水岭算法解决走迷宫游戏示例

2020-12-10 00:18白交_Robin Python

这篇文章主要介绍了Python基于分水岭算法解决走迷宫游戏,结合具体实例形式分析了分水岭算法解决迷宫问题的相关步骤与操作技巧,需要的朋友可以参考下

本文实例讲述了Python基于分水岭算法解决走迷宫游戏。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#Solving maze with morphological transformation
"""
usage:Solving maze with morphological transformation
needed module:cv2/numpy/sys
ref:
1.http://www.mazegenerator.net/
2.http://blog.leanote.com/post/leeyoung/539a629aab35bc44e2000000
@author:Robin Chen
"""
import cv2
import numpy as np
import sys
def SolvingMaze(image):
#load an image
  try:
    img = cv2.imread(image)
  except Exception,e:
    print 'Error:can not open the image!'
    sys.exit()
#show image
  #cv2.namedWindow('image', cv2.WINDOW_NORMAL)
  cv2.imshow('maze_image',img)
#convert to gray
  gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#show gray image
  #cv2.imshow('gray_image',gray_image)
#convert to binary image
  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)
  if len(contours) != 2:
    sys.exit("This is not a 'perfect maze' with just 2 walls!")
  h, w, d = img.shape
#The first wall
  path = np.zeros((h,w),dtype = np.uint8)#cv2.CV_8UC1
  cv2.drawContours(path, contours, 0, (255,255,255),-1)#cv2.FILLED
  #cv2.imshow('The first wall',path)
#Dilate the wall by a few pixels
  kernel = np.ones((19, 19), dtype = np.uint8)
  path = cv2.dilate(path, kernel)
  #cv2.imshow('Dilate the wall by a few pixels',path)
#Erode by the same amount of pixels
  path_erode = cv2.erode(path, kernel);
  #cv2.imshow('Erode by the same amount of pixels',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);
#waiting for any key to close windows
  cv2.waitKey(0)
  cv2.destroyAllWindows()
if __name__ == '__main__':
  image = sys.argv[-1]
  SolvingMaze(image)

希望本文所述对大家Python程序设计有所帮助。

原文链接:http://blog.csdn.net/chendejiao/article/details/43231659

延伸 · 阅读

精彩推荐