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

yipeiwu_com5年前Python基础

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

#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相关内容可查看本站专题:《Python游戏开发技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

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

相关文章

Python for循环与getitem的关系详解

这篇文章主要介绍了Python for循环与getitem的关系详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一个类里面如果由_...

用python 实现在不确定行数情况下多行输入方法

如下所示: stopword = '' str = '' for line in iter(raw_input, stopword): str += line + '\n' pri...

python 数据清洗之数据合并、转换、过滤、排序

python 数据清洗之数据合并、转换、过滤、排序

前面我们用pandas做了一些基本的操作,接下来进一步了解数据的操作, 数据清洗一直是数据分析中极为重要的一个环节。 数据合并 在pandas中可以通过merge对数据进行合并操作。...

Python实现全角半角字符互转的方法

前言 相信对于每一个编程人员来说,在文本处理的时候,经常会遇到全角半角不一致的问题。于是需要程序能够快速的在两者之间互转。由于全角半角本身存在着映射关系,所以处理起来并不复杂。 具体规则...

对Python3中的print函数以及与python2的对比分析

对Python3中的print函数以及与python2的对比分析

本文首先介绍在python3中print函数的应用,然后对比在pyhton2中的应用。(本文作者所用版本为3.6.0) 首先我们通过help(print)命令来查看print函数的相关信...