1+ import imageio .v2 as imageio
12import numpy as np
23import matplotlib .pyplot as plt
34from PathPlanning .TimeBasedPathPlanning .GridWithDynamicObstacles import (
@@ -44,7 +45,7 @@ def PlotNodePath(grid: Grid, start: Position, goal: Position, path: NodePath):
4445'''
4546Plot a series of agent paths.
4647'''
47- def PlotNodePaths (grid : Grid , start_and_goals : list [StartAndGoal ], paths : list [NodePath ]):
48+ def PlotNodePaths (grid : Grid , start_and_goals : list [StartAndGoal ], paths : list [NodePath ], save_gif : bool = False ):
4849 fig = plt .figure (figsize = (10 , 7 ))
4950
5051 ax = fig .add_subplot (
@@ -98,7 +99,12 @@ def PlotNodePaths(grid: Grid, start_and_goals: list[StartAndGoal], paths: list[N
9899 max_time = max (path .goal_reached_time () for path in paths )
99100
100101 # Animation loop
102+ frames = []
101103 for i in range (0 , max_time + 1 ):
104+ if save_gif :
105+ plt .savefig (f"frame_{ i :03d} .png" ) # Save each frame as an image
106+ frames .append (imageio .imread (f"frame_{ i :03d} .png" ))
107+
102108 # Update obstacle positions
103109 obs_positions = grid .get_obstacle_positions_at_time (i )
104110 obs_points .set_data (obs_positions [0 ], obs_positions [1 ])
@@ -122,4 +128,7 @@ def PlotNodePaths(grid: Grid, start_and_goals: list[StartAndGoal], paths: list[N
122128
123129 plt .pause (0.2 )
124130
131+ if save_gif :
132+ imageio .mimsave ("path_animation2.gif" , frames , fps = 5 ) # Convert images to GIF
133+
125134 plt .show ()
0 commit comments