pythonopencv画迷宫
时间: 2023-07-26 15:06:26 浏览: 69
下面是使用Python和OpenCV库绘制迷宫的示例代码。
```python
import cv2
import numpy as np
# 定义迷宫尺寸和墙的厚度
maze_size = 15
wall_thickness = 10
# 创建一个空白图像作为迷宫背景
maze = np.zeros((maze_size * wall_thickness, maze_size * wall_thickness), dtype=np.uint8)
# 绘制边界
cv2.rectangle(maze, (0, 0), (maze_size * wall_thickness - 1, maze_size * wall_thickness - 1), 255, wall_thickness)
# 生成随机迷宫
visited = np.zeros((maze_size, maze_size), dtype=np.bool)
stack = [(0, 0)]
while stack:
x, y = stack[-1]
visited[x, y] = True
neighbors = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
unvisited_neighbors = [(nx, ny) for nx, ny in neighbors
if 0 <= nx < maze_size and 0 <= ny < maze_size and not visited[nx, ny]]
if unvisited_neighbors:
nx, ny = unvisited_neighbors[np.random.randint(len(unvisited_neighbors))]
dx, dy = nx - x, ny - y
if dx == 1:
cv2.line(maze, ((x + 1) * wall_thickness, (y + 1) * wall_thickness),
((x + 2) * wall_thickness, (y + 1) * wall_thickness), 255, wall_thickness)
elif dx == -1:
cv2.line(maze, ((x + 1) * wall_thickness, y * wall_thickness),
((x + 2) * wall_thickness, y * wall_thickness), 255, wall_thickness)
elif dy == 1:
cv2.line(maze, ((x + 1) * wall_thickness, (y + 1) * wall_thickness),
((x + 1) * wall_thickness, (y + 2) * wall_thickness), 255, wall_thickness)
elif dy == -1:
cv2.line(maze, (x * wall_thickness, (y + 1) * wall_thickness),
(x * wall_thickness, (y + 2) * wall_thickness), 255, wall_thickness)
stack.append((nx, ny))
else:
stack.pop()
# 显示迷宫
cv2.imshow('Maze', maze)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个例子中,我们首先定义了迷宫的尺寸和墙的厚度。然后创建一个空白图像作为迷宫背景,并绘制了迷宫的边界。接着,我们使用深度优先搜索算法(DFS)生成了一个随机迷宫。最后,我们将迷宫显示在屏幕上。
运行代码后,你将看到一个新窗口弹出,其中显示了一个迷宫。你可以根据需要调整迷宫的大小和墙的厚度,并进一步修改代码以实现自己想要的效果。