replay.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """
  2. 算法结果回放
  3. """
  4. import json
  5. import math
  6. import matplotlib.pyplot as plt
  7. import input.make_map as mp
  8. from utils import drawcar as tools, reeds_shepp as rs
  9. from input import make_car
  10. import numpy as np
  11. import imageio
  12. def replay(map_scene,output_result):
  13. picture_scene = map_scene.replace('/', '/').replace('.json', '.jpg')
  14. gif_scene = map_scene.replace('input', 'image_save').replace('.json', '.gif')
  15. if output_result[-6].isdigit():
  16. Num =output_result.rsplit('/result_', 1)[-1].rsplit('.', 1)[0]
  17. if Num[-2].isdigit():
  18. gif_scene = gif_scene.replace('.gif', f'{Num[-3:]}.gif')
  19. else:
  20. gif_scene = gif_scene.replace('.gif', f'{Num[-2:]}.gif')
  21. C = make_car.C
  22. ox, oy,sp,gp = mp.make_map(map_scene)
  23. sx, sy, syaw0 = sp['x'], sp['y'], sp['yaw']
  24. gx, gy, gyaw0 = gp['3']['x_end'], gp['3']['y_end'], gp['3']['yaw']
  25. with open(output_result,'r',encoding='UTF-8') as f:
  26. result=json.load(f)
  27. x = result['output_x']
  28. y = result['output_y']
  29. yaw = result['output_yaw']
  30. direction = result['output_dir']
  31. plt.rcParams['xtick.direction'] = 'in'
  32. picture = plt.imread(picture_scene)
  33. ox1,ox2,oy1,oy2 = min(ox), max(ox), min(oy), max(oy)
  34. frames = [] # 用于保存每一帧图像
  35. for k in range(len(x)):
  36. if k % 3 == 0:
  37. fig, ax = plt.subplots()
  38. ax.imshow(picture, extent=[ox1, ox2, oy1, oy2], aspect='auto')
  39. ax.lines.clear()
  40. ax.plot(x, y, linewidth=0.5, color='b', linestyle='--')
  41. # ax.plot(ox, oy, ",k")
  42. if k < len(x) - 2:
  43. dy = (yaw[k + 1] - yaw[k]) / C.MOVE_STEP
  44. steer = rs.pi_2_pi(math.atan(-C.WB * dy / direction[k]))
  45. else:
  46. steer = 0.0
  47. tools.draw_car(ax, gx, gy, gyaw0, 0.0, 'dimgray')
  48. tools.draw_car(ax, x[k], y[k], yaw[k], steer)
  49. ax.set_title("Simulation Result", loc='left', fontweight="heavy")
  50. ax.axis("equal")
  51. # 保存当前帧图像
  52. fig.canvas.draw()
  53. image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')
  54. image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,))
  55. frames.append(image)
  56. plt.show()
  57. # 将所有保存的帧图像整合成 GIF 动态图
  58. imageio.mimsave(gif_scene, frames, fps=15)
  59. if output_result[-6].isdigit():
  60. if Num[-2].isdigit():
  61. print(f"车位{Num[-2:]}仿真完成")
  62. else:
  63. print(f"车位{Num[-1]}仿真完成")
  64. else:
  65. print("仿真结束!")