『OpenCV』使用OpenCV和Python来解决迷宫问题


今天我们将学习在python中使用opencv制作迷宫解谜器 。
『OpenCV』使用OpenCV和Python来解决迷宫问题
本文插图
解决迷宫的例子
首先 , 我们导入所需的Python库
import cv2import numpy as npimport os 让我们从读取图像开始
def readImage(img_file_path):binary_img = Noneimg = cv2.imread(img_file_path,0)ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)binary_img = imgreturn binary_img 现在我们有一个读取迷宫方块的问题 。
『OpenCV』使用OpenCV和Python来解决迷宫问题
本文插图
def blockwork(img,coordinate): size = CELL_SIZEh = CELL_SIZE*(coordinate[0]+1)w = CELL_SIZE*(coordinate[1]+1)h0= CELL_SIZE*coordinate[0]w0= CELL_SIZE*coordinate[1]block = img[h0:h,w0:w]up= bool(block[0,int(size/2)]) *1000down= bool(block[int(size-1),int(size/2)])*100left= bool(block[int(size/2),0]) *10right = bool(block[int(size/2),int(size-1)])*1edge = up+down+left+rightreturn edge, block 变量“ edge”包含每个单个块的边界信息 。 如果该块的特定面是开放的 , 我们设置为1 。 这样会将大量信息压缩为一个数字 , 0

  • 对于上边缘-1000
  • 对于下边缘-100
  • 对于左边缘-10
  • 对于右边缘-1

『OpenCV』使用OpenCV和Python来解决迷宫问题
本文插图
这也 , 我们可以知道给定块的哪一侧是打开的 , 哪一侧是闭合的 。
def solveMaze(original_binary_img, initial_point, final_point, no_cells_height, no_cells_width):edgearray = []for i in range (no_cells_height):edgearray.append([])for j in range(no_cells_width):sz = [i,j]edge, block = blockwork(img, sz)edgearray[i].append(edge)edge= edgearray 在获得所有块的边缘数组之后 , 我们将它附加到一个边缘数组中 。
解迷宫实际上就是解这个数组
『OpenCV』使用OpenCV和Python来解决迷宫问题
本文插图
回溯算法 回溯是一种递归地解决问题的算法技术 , 它尝试逐步地构建一个解 , 每次只构建一个部分 , 并删除那些在任何时间点都不能满足问题约束的解 。
『OpenCV』使用OpenCV和Python来解决迷宫问题
本文插图
#The solvemaze method is continued here... shortestPath = [] img = original_binary_img sp = [] rec = [0] p = 0 sp.append(list(initial_point))while True:h,w = sp[p][0],sp[p][1]#h stands for height and w stands for widthif sp[-1]==list(final_point):breakif edge[h][w] > 0:rec.append(len(sp))if edge[h][w]>999:#If this edge is open upwardsedge[h][w] = edge[h][w]-1000h = h-1sp.append([h,w])edge[h][w] =edge[h][w]-100p = p+1continueif edge[h][w]>99:#If the edge is open downwardedge[h][w] =edge[h][w]-100h = h+1sp.append([h,w])edge[h][w] =edge[h][w]-1000p=p+1continueif edge[h][w]>9:#If the edge is open leftedge[h][w] = edge[h][w]-10w = w-1sp.append([h,w])edge[h][w] = edge[h][w]-1p = p+1continueif edge[h][w]==1:#If the edge is open rightedge[h][w] = edge[h][w]-1w = w+1sp.append([h,w])edge[h][w] = edge[h][w]-10p=p+1continueelse:#Removing the coordinates that are closed or don't show any pathsp.pop()rec.pop()p = rec[-1]for i in sp:shortestPath.append(tuple(i))return shortestPath


推荐阅读