waypoint_genarate.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import numpy as np
  2. from scipy.interpolate import CubicSpline
  3. import math
  4. def generate_spline_trajectory(points, total_time, num_samples=100):
  5. """
  6. 使用三次样条曲线生成一条平滑轨迹。
  7. :param points: 输入点列表,格式 [(x1, y1), (x2, y2), ...]
  8. :param total_time: 轨迹总时间
  9. :param num_samples: 采样点的数量
  10. :return: 轨迹点列表 [(time, x, y, yaw), ...]
  11. """
  12. # 将时间与输入点关联,时间从 0 均匀分布到 total_time
  13. t_points = np.linspace(0, total_time, len(points))
  14. x_points, y_points = zip(*points)
  15. # 构建三次样条函数
  16. cs_x = CubicSpline(t_points, x_points) # x(t)
  17. cs_y = CubicSpline(t_points, y_points) # y(t)
  18. # 采样时间点
  19. t_samples = np.linspace(0, total_time, num_samples)
  20. # 计算采样点的坐标和角度
  21. trajectory = []
  22. for t in t_samples:
  23. x = cs_x(t)
  24. y = cs_y(t)
  25. dx_dt = cs_x.derivative()(t) # x 的导数
  26. dy_dt = cs_y.derivative()(t) # y 的导数
  27. yaw = math.atan2(dy_dt, dx_dt) # 计算角度
  28. trajectory.append((t, x, y, yaw))
  29. return trajectory
  30. def generate_xml_trajectory(trajectory):
  31. """
  32. 将轨迹数据转换为 XML 格式字符串。
  33. :param trajectory: 输入轨迹点列表 [(time, x, y, yaw), ...]
  34. :return: 格式化的 XML 字符串
  35. """
  36. xml_str = ''''''
  37. # 添加每个 waypoint
  38. for t, x, y, yaw in trajectory:
  39. xml_str += f''' <waypoint>
  40. <time>{t:.6f}</time>
  41. <pose>{x:.6f} {y:.6f} 0.000000 0.000000 0.000000 {yaw:.6f}</pose>
  42. </waypoint>\n'''
  43. return xml_str
  44. if __name__ == "__main__":
  45. # 输入点:需要连接的 (x, y) 坐标
  46. input_points = [(-7, -7), (-7, -6), (-7, -5), (-7, -4), (-7, -3), (-7, -2),(-7, -1),(-7, 0),(-7, 1),(-7, 2),(-7, 3),(-7, 4),(-7, 5)]
  47. total_time = 20.0 # 总时间为 2 秒
  48. # 生成三次样条轨迹
  49. trajectory = generate_spline_trajectory(input_points, total_time, num_samples=50)
  50. # 生成 XML 格式的轨迹
  51. xml_output = generate_xml_trajectory(trajectory)
  52. # 保存到文件
  53. with open("/home/mj/planning_ws/src/turn_on_robot/spline_trajectory.xml", "w") as f:
  54. f.write(xml_output)
  55. print("轨迹生成完成,结果已保存到 spline_trajectory.xml")