bspline_curve.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. """
  2. Path Planner with B-Spline
  3. author: Atsushi Sakai (@Atsushi_twi)
  4. """
  5. import numpy as np
  6. import matplotlib.pyplot as plt
  7. import scipy.interpolate as scipy_interpolate
  8. import cubic_spline as cs
  9. def approximate_b_spline_path(x, y, n_path_points, degree=3):
  10. t = range(len(x))
  11. x_tup = scipy_interpolate.splrep(t, x, k=degree)
  12. y_tup = scipy_interpolate.splrep(t, y, k=degree)
  13. x_list = list(x_tup)
  14. x_list[1] = x + [0.0, 0.0, 0.0, 0.0]
  15. y_list = list(y_tup)
  16. y_list[1] = y + [0.0, 0.0, 0.0, 0.0]
  17. ipl_t = np.linspace(0.0, len(x) - 1, n_path_points)
  18. rx = scipy_interpolate.splev(ipl_t, x_list)
  19. ry = scipy_interpolate.splev(ipl_t, y_list)
  20. return rx, ry
  21. def interpolate_b_spline_path(x, y, n_path_points, degree=3):
  22. ipl_t = np.linspace(0.0, len(x) - 1, len(x))
  23. spl_i_x = scipy_interpolate.make_interp_spline(ipl_t, x, k=degree)
  24. spl_i_y = scipy_interpolate.make_interp_spline(ipl_t, y, k=degree)
  25. travel = np.linspace(0.0, len(x) - 1, n_path_points)
  26. return spl_i_x(travel), spl_i_y(travel)
  27. def main():
  28. print(__file__ + " start!!")
  29. # way points
  30. # way_point_x = [-1.0, 3.0, 4.0, 2.0, 1.0]
  31. # way_point_y = [0.0, -3.0, 1.0, 1.0, 3.0]
  32. way_point_x = [-2, 2.0, 3.5, 5.5, 6.0, 8.0]
  33. way_point_y = [0, 2.7, -0.5, 0.5, 3.0, 4.0]
  34. sp = cs.Spline2D(way_point_x, way_point_y)
  35. s = np.arange(0, sp.s[-1], 0.1)
  36. rx, ry, ryaw, rk = [], [], [], []
  37. for i_s in s:
  38. ix, iy = sp.calc_position(i_s)
  39. rx.append(ix)
  40. ry.append(iy)
  41. ryaw.append(sp.calc_yaw(i_s))
  42. rk.append(sp.calc_curvature(i_s))
  43. n_course_point = 100 # sampling number
  44. rax, ray = approximate_b_spline_path(way_point_x, way_point_y,
  45. n_course_point)
  46. rix, riy = interpolate_b_spline_path(way_point_x, way_point_y,
  47. n_course_point)
  48. # show results
  49. plt.plot(way_point_x, way_point_y, '-og', label="Control Points")
  50. plt.plot(rax, ray, '-r', label="Approximated B-Spline path")
  51. plt.plot(rix, riy, '-b', label="Interpolated B-Spline path")
  52. plt.plot(rx, ry, color='dimgray', label="Cubic Spline")
  53. plt.grid(True)
  54. plt.title("Curves Comparison")
  55. plt.legend()
  56. plt.axis("equal")
  57. plt.show()
  58. if __name__ == '__main__':
  59. main()