自己生成一个随机分布障碍物的矩形地图,并将地图网格化,将障碍物所占网格赋值为-1,目标位置赋值为0,采用梯度法进行路径规划,将规划路线可视化在地图上。上传python文件和htm…
- User
自己生成一个随机分布障碍物的矩形地图,并将地图网格化,将障碍物所占网格赋值为-1,目标位置赋值为0,采用梯度法进行路径规划,将规划路线可视化在地图上。上传python文件和html文件。
- Assistant
自己生成一个随机分布障碍物的矩形地图,并将地图网格化,将障碍物所占网格赋值为-1,目标位置赋值为0,采用梯度法进行路径规划,将规划路线可视化在地图上。上传python文件和html文件。
以下是实现您要求的Python代码,它生成一个带有随机障碍物的矩形地图,将地图网格化,障碍物赋值为-1,目标位置赋值为0,使用梯度法进行路径规划,并将路径可视化在地图上。
# 文件名: path_planning.py
import numpy as np
import matplotlib.pyplot as plt
# 设置随机种子以便复现结果
np.random.seed(42)
# 参数
map_size = (50, 50) # 地图尺寸
obstacle_density = 0.2 # 障碍物占网格的比例
start = (0, 0) # 起点坐标
goal = (map_size[0]-1, map_size[1]-1) # 目标点坐标
# 生成随机障碍物地图
def generate_map(map_size, obstacle_density):
grid = np.zeros(map_size)
num_obstacles = int(map_size[0] * map_size[1] * obstacle_density)
obstacle_indices = np.random.choice(map_size[0] * map_size[1], num_obstacles, replace=False)
for idx in obstacle_indices:
x = idx // map_size[1]
y = idx % map_size[1]
grid[x, y] = -1 # 障碍物赋值为-1
return grid
# 计算势场(梯度)
def compute_potential_field(grid, goal):
potential = np.full_like(grid, np.inf, dtype=float)
potential[grid == -1] = np.inf # 障碍物设置为无限大
potential[goal] = 0 # 目标点势能为0
# 使用广度优先搜索计算势场
from collections import deque
queue = deque()
queue.append(goal)
while queue:
current = queue.popleft()
x, y = current
current_potential = potential[x, y]
# 遍历邻居节点
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
nx, ny = x + dx, y + dy
if 0 <= nx < grid.shape[0] and 0 <= ny < grid.shape[1]:
if grid[nx, ny] != -1 and potential[nx, ny] > current_potential + 1:
potential[nx, ny] = current_potential + 1
queue.append((nx, ny))
return potential
# 使用梯度下降法规划路径
def plan_path(potential, start):
path = [start]
current = start
while True:
x, y = current
if potential[x, y] == 0:
break # 到达目标点
# 找到邻居中具有最小势能的位置
min_potential = potential[x, y]
next_step = None
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
nx, ny = x + dx, y + dy
if 0 <= nx < potential.shape[0] and 0 <= ny < potential.shape[1]:
if potential[nx, ny] < min_potential:
min_potential = potential[nx, ny]
next_step = (nx, ny)
if next_step is None:
print("未找到路径!")
return path
path.append(next_step)
current = next_step
return path
# 主程序
grid = generate_map(map_size, obstacle_density)
# 检查起点和目标点是否在障碍物上
if grid[start] == -1 or grid[goal] == -1:
print("起点或目标点位于障碍物内,请重新生成地图。")
else:
grid[goal] = 0 # 设置目标点
potential = compute_potential_field(grid, goal)
path = plan_path(potential, start)
# 可视化
plt.figure(figsize=(10, 10))
# 显示地图:空白区域、障碍物、势能值
plt.imshow(grid.T, origin='lower', cmap='gray_r')
# 绘制路径
path_array = np.array(path)
plt.plot(path_array[:, 0], path_array[:, 1], 'r', linewidth=2, label='路径')
# 绘制起点和目标点
plt.plot(start[0], start[1], 'go', markersize=10, label='起点')
plt.plot(goal[0], goal[1], 'bo', markersize=10, label='目标点')
plt.title('基于梯度法的路径规划')
plt.legend()
plt.xlabel('X')
plt.ylabel('Y')
plt.grid(True)
plt.savefig('path_planning.png') # 保存图片
plt.show()
要运行此代码,请将其保存为 path_planning.py,然后在命令行中运行:
python path_planning.py
运行后,程序会生成一个名为 path_planning.png 的图片文件,该文件包含地图和规划的路径。
接下来,您可以创建一个简单的 HTML 文件来显示生成的图片。
<!-- 文件名: path_planning.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>基于梯度法的路径规划可视化</title>
</head>
<body>
<h1>基于梯度法的路径规划可视化</h1>
<img src="path_planning.png" alt="路径规划结果">
</body>
</html>
请将上述内容保存为 path_planning.html,并确保 path_planning.png 与 HTML 文件位于同一目录下。然后,您可以在浏览器中打开 path_planning.html,查看可视化结果。
注意事项:
确保您的计算机上安装了必要的Python库:numpy、matplotlib。如未安装,请使用以下命令安装:
pip install numpy matplotlib
如果在运行过程中遇到起点或目标点位于障碍物内的提示,请重新运行程序,以生成新的地图。
您可以根据需要调整地图尺寸、障碍物密度和起点、目标点的位置。
代码说明:
地图生成:generate_map 函数根据给定的地图尺寸和障碍物密度,随机分布障碍物,并将障碍物的位置赋值为 -1。
势场计算:compute_potential_field 函数使用广度优先搜索,从目标点开始,计算每个位置到目标点的最小距离,生成一个势能场。
路径规划:plan_path 函数从起点开始,沿着势能下降的方向移动,直到到达目标点,生成路径。
可视化:使用 matplotlib 绘制地图、路径、起点和目标点,并将结果保存为图片文件。
希望这能满足您的需求!
Not yet included in a published release.