def animate(case): from matplotlib.animation import ArtistAnimation theta1s = np.linspace(0, 2*np.pi, 300) fig, ax = plt.subplots() rA, container = 0, [] for theta1 in theta1s: rB, rC, rD, rE, rD2 = pos(theta1, case) link1, = ax.plot(np.real([rA, rB]), np.imag([rA, rB]), 'ro-') link31, = ax.plot(np.real([rC, rD]), np.imag([rC, rD]), 'go-') link32, = ax.plot(np.real([rC, rD2]), np.imag([rC, rD2]), 'g-') link4, = ax.plot(np.real([rD, rE]), np.imag([rD, rE]), 'bo-') ax.plot(np.real(rE), np.imag(rE), 'b,-') A = ax.text(np.real(rA), np.imag(rA)+.02, r'$A$') B = ax.text(np.real(rB), np.imag(rB)+.02, r'$B$') C = ax.text(np.real(rC), np.imag(rC)+.02, r'$C$') D1 = ax.text(np.real(rD), np.imag(rD)+.02, r'$D_1$') D2 = ax.text(np.real(rD2), np.imag(rD2)+.02, r'$D_2$') E = ax.text(np.real(rE), np.imag(rE)+.02, r'$E$') container.append([link1, link31, link32, link4, A, B, D2, C, D1, E]) link3, = ax.plot(np.real(rC), np.imag(rC), 'ro') ani = ArtistAnimation(fig, container, interval=20, blit=True) ax.set_aspect('equal') ax.grid() plt.show() ani.save('mechanism_9.mp4', fps=60, bitrate=5000, dpi=400)
def show_anim(set_num, anim_num): import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import ArtistAnimation anims = _read_hdr() s = anims.sets[set_num] anim = s.animations[anim_num] images = [anims.render_pixelmap(frame) for frame in anim.frames] fps = anim.fps borders = np.array([[x, x + w, -y - h, -y] for frame in anim.frames for x, y, w, h in [frame.origin + frame.shape]]) extremes = ((borders[:, 0].min(), borders[:, 1].max()), (borders[:, 2].min(), borders[:, 3].max())) fig, ax = plt.subplots() artists = [[plt.imshow(image, animated=True, extent=borders[i])] for i, image in enumerate(images)] ani = ArtistAnimation(fig, artists, interval=1000.0 / fps, blit=True) ax.axis("off") ax.set_xlim(extremes[0]) ax.set_ylim(extremes[1]) plt.show()
def animate(phi1s): from matplotlib.animation import ArtistAnimation fig, ax = plt.subplots() container = [] for phi in phi1s: rB, rD, rF, rG = pos(phi) pinA, = ax.plot(rA[0], rA[1], 'bo') pinC, = ax.plot(rC[0], rC[1], 'bo') link1, = ax.plot([rA[0], rB[0]], [rA[1], rB[1]], 'ro-') link3, = ax.plot([rF[0], rD[0]], [rF[1], rD[1]], 'go-') link5, = ax.plot([rA[0], rG[0]], [rA[1], rG[1]], 'bo-') A = ax.text(rA[0]+.05, rA[1]+.05, 'A', fontsize=12) B = ax.text(rB[0]+.05, rB[1]+.05, 'B', fontsize=12) C = ax.text(rC[0]+.05, rC[1]+.05, 'C', fontsize=12) D = ax.text(rD[0]+.05, rD[1]+.05, 'D', fontsize=12) F = ax.text(rF[0]+.05, rF[1]+.05, 'F', fontsize=12) G = ax.text(rG[0]+.05, rG[1]+.05, 'G', fontsize=12) container.append([pinA, pinC, link1, link3, link5, A, B, C, D, F, G]) ax.grid() ax.set_aspect('equal') ani = ArtistAnimation(fig, container, interval=20, blit=True)
def animate(case): from matplotlib.animation import ArtistAnimation phi1s = np.linspace(0, 2 * np.pi, 300) fig, ax = plt.subplots() rA, container = 0, [] for phi in phi1s: rB, rC, rD, rE, rF = pos(phi, case) link1, = ax.plot(np.real([rA, rB]), np.imag([rA, rB]), 'ro-') link2, = ax.plot(np.real([rB, rC]), np.imag([rB, rC]), 'go-') link3, = ax.plot(np.real([rC, rE]), np.imag([rC, rE]), 'bo-') link4, = ax.plot(np.real([rE, rF]), np.imag([rE, rF]), 'ko-') ax.plot(np.real(rD), np.imag(rD), 'bo-') ax.plot(np.real(rF), np.imag(rF), 'b,-') A = ax.text(np.real(rA), np.imag(rA) + .002, r'$A$') B = ax.text(np.real(rB), np.imag(rB) + .002, r'$B$') C = ax.text(np.real(rC), np.imag(rC) + .002, r'$C$') D = ax.text(np.real(rD), np.imag(rD) + .002, r'$D$') E = ax.text(np.real(rE), np.imag(rE) + .002, r'$E$') F = ax.text(np.real(rF), np.imag(rF) + .002, r'$F$') container.append([link1, link2, link3, link4, A, B, C, D, E, F]) ani = ArtistAnimation(fig, container, interval=20, blit=True) ax.set_aspect('equal') ax.set_ylim(ymax=case[1] + .02) ax.grid() plt.show() ani.save('mechanism_3.mp4', fps=60, bitrate=5000, dpi=400)
def animation(*args, **kwargs): """ Artist animation wrapper to avoid another import """ return ArtistAnimation(*args, **kwargs)
def plot_paths(layout, paths): images = [] cmap = colors.ListedColormap(['white', 'black', 'red', 'green', 'blue']) lengths = [len(path) for path in paths] lengths.sort() longest_path = lengths[-1] fig = plt.figure() for i in range(longest_path): steps = [] for path in paths: if path.get(i) != None: steps.append(path.get(i)) # print(steps) layout_arr = transform_array_to_int(layout, steps) img = plt.pcolor(layout_arr[::-1], cmap=cmap, edgecolors='k', linewidths=1) images.append([img]) if i == 0: plt.savefig('pics/start.png') images.insert(0, images[1]) images.append(images[-1]) animation = ArtistAnimation(fig, images, interval=250) print('Animation steps:', len(images)) animation.save('video/anim.mp4', dpi=800)
def animate(theta1s, AB, AD, BC, CD, variation=0): rA, rD = 0, AD fig, ax = plt.subplots() container = [] for theta1 in theta1s: rB, rC = pos(theta1, AB, AD, BC, CD)[variation] link1, = ax.plot(np.real([rA, rB]), np.imag([rA, rB]), 'ro-') link2, = ax.plot(np.real([rB, rC]), np.imag([rB, rC]), 'go-') link3, = ax.plot(np.real([rD, rC]), np.imag([rD, rC]), 'bo-') A = ax.text(np.real(rA), np.imag(rA) + .01, r'$A$') B = ax.text(np.real(rB), np.imag(rB) + .01, r'$B$') C = ax.text(np.real(rC), np.imag(rC) + .01, r'$C$') D = ax.text(np.real(rD), np.imag(rD) + .01, r'$D$') container.append([link1, link2, link3, A, B, C, D]) from matplotlib.animation import ArtistAnimation ani = ArtistAnimation(fig, container, interval=20, blit=True) ax.set_ylim(ymax=CD + .05) ax.grid() ax.set_aspect('equal') ani.save('mechanism_1_{0:d}.mp4'.format(variation), fps=60, bitrate=5000, dpi=400)
def pred_animation(y_test, y_pred, is_save=False): fig = plt.figure(figsize=(15, 10)) ims = [] plt.imshow(room_image, extent=(0, 7.8, 0, 8.8)) # Plot antenna position plt.scatter(7.25, 1.5, color='green', marker=7, s=500) plt.scatter(7.2, 7.1, color='green', marker=7, s=500) for m in range(3): plt.scatter(0.6, 2.763 - m * 0.063, color='cyan', marker=7, s=500) # Plot true position and predicted position (Animation) for i in range(len(y_test)): im_test = [ plt.scatter(y_test[i, 0], y_test[i, 1], color='black', marker='X', s=1200) ] im_pred = [ plt.scatter(y_pred[i, 0], y_pred[i, 1], color='blue', s=1200, alpha=0.7) ] ims.append(im_test + im_pred) plt.xlim(0, 7.8) plt.ylim(0, 8.8) ani = ArtistAnimation(fig, ims, interval=500) if is_save: ani.save(os.path.join(FIGURE_SAVE_PATH, 'pred_anim.mp4'), writer="ffmpeg") plt.show()
def animate(phi1s, variation=0, fps=60, AB=1, BC=1): """ Animate movement of the mechanism """ rA = 0 fig, ax = plt.subplots() container = [] for phi in phi1s: rB, rC, rBC = pos(phi, AB, BC)[variation] link1, = ax.plot(np.real([rA, rB]), np.imag([rA, rB]), 'ro-') link2, = ax.plot(np.real([rB, rC]), np.imag([rB, rC]), 'go-') A = ax.text(np.real(rA), np.imag(rA) + .07, 'A') B = ax.text(np.real(rB), np.imag(rB) + .07, 'B') C = ax.text(np.real(rC), np.imag(rC) + .07, 'C') container.append([link1, link2, A, B, C]) ax.plot(np.real(rC), np.imag(rC), 'b,-') from matplotlib.animation import ArtistAnimation ani = ArtistAnimation(fig, container, interval=fps, blit=True) ax.grid() ax.set_aspect('equal') ani.save('R_RRT.mp4', fps=60, bitrate=5000, dpi=400)
def demo(self, performance, limit, defaultPause=0.1, interval=0.1): import matplotlib.pyplot as plt from matplotlib.animation import ArtistAnimation figure = plt.figure() artists = [] timer = 0.0 self.leds.clear() action = performance(self.leds) while timer < limit: try: pause = next(action) except StopIteration: break if pause is None: pause = defaultPause art = self.leds.plot(show=False) num = int((pause) / interval) if num == 0: continue artists += [[art]] * num timer += pause ani = ArtistAnimation(figure, artists, interval=interval * 1000, repeat=False, blit=True) # noqa plt.show()
def animate(self, *args, **kwargs) -> ArtistAnimation: """Animate the snapshots taken. Uses matplotlib.animation.ArtistAnimation Returns ------- ArtistAnimation """ return ArtistAnimation(self._figure, self._photos, *args, **kwargs)
def create_animation(df, img, include_backwards=True, fps=24, n_seconds=2, figsize=(8, 8), repeat=True): """Create animation from a displacement field. Parameters ---------- df : DisplacementField Instance of the ``DisplacementField`` representing the coordinate transformation. img : np.ndarray Image. include_backwards : bool If True, then animation also played backwards after its played forwards. fps : int Frames per second. n_seconds : int Number of seconds to play the animation forwards. figsize : tuple Size of the figure. repeat : bool If True, then animation always replayed at the end. Returns ------- ani : matplotlib.animation.ArtistAnimation Animation showing the transformation. Notes ----- To enable animation viewing in a jupyter notebook write: ``` from matplotlib import rc rc('animation', html='html5') ``` """ n_frames = int(n_seconds * fps) interval = (1 / fps) * 1000 frames = [] fig = plt.figure(figsize=figsize) plt.axis('off') for i in range(n_frames + 1): df_new = df * (i / n_frames) warped_img = df_new.warp(img) frames.append([plt.imshow(warped_img, cmap='gray')]) if include_backwards: frames += frames[::-1] ani = ArtistAnimation(fig, frames, interval=interval, repeat=repeat) return ani
def animate_vibration_mode_stress(self, k, alpha=1, l=1, show=None, savename=None, playtime=5, fps=60, repeat_delay=0, title=None): if k > self.num_eigenpairs - 1: raise ValueError(f"Too high an eigen-number. Have only solved for {self.num_eigenpairs} eigenpairs.") displacement_vec = self.retrieve_vibration_eigenvector(k) N_frames = int(playtime * fps) ts = np.linspace(0, 2*np.pi, N_frames) max_stretch = self.find_max_stress(displacement=displacement_vec*alpha) # Set a bigger font size for text: plt.rcParams.update({'font.size': 20}) norm = mpl.colors.Normalize(vmin=-max_stretch, vmax=max_stretch) fig, ax = plt.subplots(figsize=(1.5*16,1.5*9)) plt.subplots_adjust(left=0.05, bottom=0.05, right=0.99, top=0.94) ax.set_xlabel("x [m]") ax.set_ylabel("y [m]") if title is None: fig.suptitle(f"Vibration mode {k} for {self.area} with {len(self.triang)} Elements") elif type(title) is str: fig.suptitle(title) else: pass artists = [self.display_mesh_stress(displacement=alpha*np.sin(l*t)*displacement_vec, norm=norm, show=False, ax=ax).findobj() for t in ts] ani = ArtistAnimation(fig, artists, interval=1000//fps, repeat_delay=repeat_delay, repeat=True, blit=True) cbar = fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=None), ax=ax) cbar.ax.get_yaxis().labelpad = 50 cbar.set_label(r"Mean Total Stress $\sigma$ [Pa]", rotation=270, fontsize=24) if savename is not None: ani.save(f"root/project_2/animations/{savename}.mp4") if show is None: if savename is None: show = True else: show = False if show: plt.show() return # Clean up memory fig.clear() plt.close(fig) del fig, ax, artists, ani, norm, cbar import gc gc.collect() return
def pred_evolution_gif(fig, frames_list, interval=300, save_dir='', save=True, no_margins=True, show=False): print("\n\n\n\n=================") print("checking for ffmpeg...") if not os.path.isfile('./../../../opt/conda/bin/ffmpeg'): print("please 'pip install ffmpeg' to create gif") print("gif not created") else: print("ffmpeg found") print("creating the gif ...\n") gif = ArtistAnimation(fig, frames_list, interval, repeat=True) # create gif if save: if no_margins: plt.tight_layout() plt.gca().set_axis_off() plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.margins(0, 0) plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) if save_dir == '': time = datetime.now().strftime("%Y%m%d-%H%M%S") save_dir = 'results/gif' + time + '.gif' plt.rcParams[ 'animation.ffmpeg_path'] = r'//opt//conda//bin//ffmpeg' # set directory of ffmpeg binary file Writer = animation.writers['ffmpeg'] ffmwriter = Writer(fps=1000 // interval, metadata=dict(artist='Me'), bitrate=1800) #set the save writer gif.save('results/temp_video.mp4', writer=ffmwriter) codeBASH = f"ffmpeg -i 'results/temp_video.mp4' -loop 0 {save_dir}" #convert mp4 to gif os.system(codeBASH) os.remove("results/temp_video.mp4") plt.close('all') if show: plt.show() plt.close('all') print("\n\n=================") print('done\n\n')
def sim_show(self): fig = plt.figure() artists = [] for config in self.config_history: plot = plt.imshow(config) artists.append([plot]) anima = ArtistAnimation(fig, artists, interval=200, repeat=False) plt.show(anima)
def save(self, filename, fps: float = 10): """ Save Gif. Args: filename: Filename of the Gif fps: Frames per second """ animation = ArtistAnimation(self.fig, self.images) animation.save(filename, writer="imagemagick", fps=fps)
def gif_from_path( path=None, figsize=(10, 10), fps=0.5, interval=500, repeat_delay=1000, filename=None, dpi=400, ): """ Create an animated gif from a director of image files. Parameters ---------- path :str, required path to directory of images figsize : tuple, optional output figure size passed to matplotlib.pyplot fps : float, optional frames per second interval : int, optional interval between frames in miliseconds, default 500 repeat_delay : int, optional time before animation repeats in miliseconds, default 1000 filename : str, required output file name dpi : int, optional image dpi passed to matplotlib writer """ assert filename, "You must provide an output filename ending in .gif" imgs = os.listdir(path) imgs.sort(key=lambda var: [ int(x) if x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var) ]) fig, ax = plt.subplots(figsize=figsize) ax.axis("off") ims = [] for i in imgs: c = plt.imread(str(PurePath(path, i))) im = plt.imshow(c, animated=True) ims.append([im]) writer = PillowWriter(fps=fps) ani = ArtistAnimation(fig, ims, interval=interval, blit=True, repeat_delay=repeat_delay) plt.tight_layout() ani.save(filename, writer=writer, dpi=dpi)
def save_gif(images, n=0, fname=None): """saves a series of images as a gif""" fig = plt.figure() plt.axis('off') ims = [] for img in images: im = plt.imshow(img, animated=True, vmin=0., vmax=1.) ims.append([im]) anim = ArtistAnimation(fig, ims, interval=100, repeat=False) fname = fname if fname is not None else 'figs/cav_transition/test{}.gif'.format(n) anim.save(fname)
def main(): fig = plt.figure() plt.axis([0, SIZE, 0, SIZE]) #xmin xmax ymin ymax plt.xticks([]) plt.yticks([]) x, y, z = random_direction(math.floor(SIZE / 2), math.floor(SIZE / 2), random_step_size()) while z != 1: x, y, z = random_direction(x, y, random_step_size()) animation = ArtistAnimation(fig, images, interval=100, repeat=0) plt.show()
def main(): robotmap = robot_map(20, 20, 0.09, 0.9) robotmap.generate_map() row, col = robotmap.get_start_position() target_row, target_col = robotmap.get_target_position() ret, dfs_path, res_path = dijkstra_search(robotmap, row, col, target_row, target_col) print('start position:', row, col) print('target position:', target_row, target_col) dfs_path = np.array(dfs_path) res_path = np.array(res_path) if ret == False: print('can not find a path') sys.exit(0) else: print('success to find a path') fig = plt.figure() ax = plt.axes() ax.set_xlim([0, robotmap.shape[0]]) ax.set_xlabel('X') ax.set_ylim([0, robotmap.shape[1]]) ax.set_ylabel('Y') ax.set_title('maze') images = [] image = robotmap.get_image() # draw start and target image[row, col] = 50 image[target_row, target_col] = 200 im = plt.imshow(image, cmap=plt.cm.get_cmap('jet'), animated=True, interpolation='nearest') images.append([im]) # draw path for i in range(1, dfs_path.shape[0] - 1): image[dfs_path[i, 0], dfs_path[i, 1]] = 100 im = plt.imshow(image, cmap=plt.cm.get_cmap('jet'), animated=True, interpolation='nearest') images.append([im]) image = robotmap.get_image() image[row, col] = 50 image[target_row, target_col] = 200 for i in range(1, res_path.shape[0] - 1): image[res_path[i, 0], res_path[i, 1]] = 150 for i in range(10): im = plt.imshow(image, cmap=plt.cm.get_cmap('jet'), animated=True, interpolation='nearest') images.append([im]) ani = ArtistAnimation(fig, images, interval=len(images), blit=True, repeat_delay=100) # ani.save('dijkstra_search.gif', dpi=80, writer='imagemagick') plt.show()
def show_animation(self) -> None: """Displays the animation in a pop-up. Optionally saves the animation.""" use("TkAgg") fig = plt.figure() ims = self._generate_images() ani = ArtistAnimation(fig, ims, interval=50, blit=True) should_save = input('Do you want to save the animation? [Y/N]\n') if should_save == 'y' or should_save == 'Y': ani.save('julia_sets.mp4', writer="ffmpeg") plt.title(f'Animated Julia sets with c = {self.anim_constant}*e^(i*a)') plt.show()
def gen_visualisation(): """ Generates an .mp4 movies representing the restructuring of the initial graph based on output files from spring.cpp """ fig = plt.figure() try: center = sys.argv[1] # ensure test_file specified except IndexError: print('Usage: genvis.py test_file') sys.exit(1) nodes = 0 frames = 0 data = [] images = [] # load the initial graph as the first frame with open(center, 'r') as f: for i, l in enumerate(f): if i == 0: frames = int(l.strip('\n')) elif i == 1: nodes = int(l.strip('\n')) elif 1 < i <= nodes + 1: x, y = map(float, l.strip('\n').split(' ')) data.append([x, y]) elif i > nodes + 1: break scat = plt.scatter(*zip(*data), s=10) # add the frame to list images.append([scat]) # loop over all other output files and generate frames for i in range(frames): data = [] with open(str(i) + '.out', 'r') as f: for l in f: x, y = map(float, l.strip('\n').split(' ')) data.append([x, y]) scat = plt.scatter(*zip(*data), s=10) images.append([scat]) # create animation line_anim = ArtistAnimation(fig, images, interval=50, blit=True) line_anim.save('graph_layout.mp4') # plt.show() # cleanup output files files = [f for f in os.listdir(".") if f.endswith(".out")] for f in files: os.remove(f)
def main() -> None: figure = plt.figure(figsize=(19.20, 10.80), dpi=100) plt.xlim([100, 220]) plt.ylim([25, 100]) file_path: os.path = os.path.join( os.getcwd(), '../scenarios/DEU_B471-1_1_T-1_mod_2.xml') common_road_input: Tuple[ Scenario, PlanningProblemSet] = CommonRoadFileReader(file_path).open() scenario: Scenario = common_road_input[0] planning_problem: Optional[PlanningProblem] = common_road_input[ 1].planning_problem_dict.get(800) # Draw goal region DrawHelp.draw(DrawHelp.convert_to_drawable(planning_problem.goal)) plt.annotate("goal region", xy=(156, 62), xytext=(160, 55), arrowprops=arrowprops) # Draw lanes DrawHelp.draw(DrawHelp.convert_to_drawable(scenario.lanelet_network)) # Draw static obstacles for obstacle in scenario.static_obstacles: DrawHelp.draw(DrawHelp.convert_to_drawable(obstacle)) x, y = obstacle.occupancy_at_time(0).shape.center plt.annotate("static obstacle", xy=(x + 2, y + 3), xytext=(x, y + 9), arrowprops=arrowprops) # Generates frames of dynamic obstacles frames: List[List[Artist]] = createDynamicObstaclesArtists( scenario.dynamic_obstacles) # Add predictions of ego vehicle to the frames extend_frames_with_prediction(planning_problem.initial_state, frames, scenario.dt) # Add an animation of the frames # NOTE The assignment is needed to force execution ani: ArtistAnimation = ArtistAnimation(figure, frames, blit=True, interval=int( round(scenario.dt * 1000)), repeat=True) ani.save("2018-12-26_BasicUnoptimzedScenario.mp4", writer="ffmpeg") plt.gca().set_aspect('equal') plt.show()
def play(data: List[int], animation): if animation: images = [] fig = plt.figure() comp = Arcade(data) tiles = defaultdict(int) ball = Ball(tiles) paddle_x = 18 expected_paddle = 18 log = [] score = 0 prediction = None while not comp.done: log = comp.board_update() for i in range(len(log) // 3): if log[i * 3 + 2] == 4: ball.move(log[i * 3], log[i * 3 + 1]) if log[i * 3 + 2] == 3: paddle_x = log[i * 3] if log[i * 3] == -1 and log[i * 3 + 1] == 0: score = log[i * 3 + 2] else: tiles[complex(log[i * 3], log[i * 3 + 1])] = log[i * 3 + 2] prediction = predict_ball(ball) remaining = Counter(tiles.values())[2] if animation: images.append([draw_screen(tiles)]) if not prediction: prediction = paddle_x if prediction > ball.x: prediction = ball.x + 1 if prediction < ball.x: prediction = ball.x - 1 if prediction > expected_paddle: comp.add_input(1) expected_paddle += 1 elif prediction < expected_paddle: comp.add_input(-1) expected_paddle -= 1 else: comp.add_input(0) if animation: ani = ArtistAnimation(fig, images, interval=100) plt.show() return score
def animate(images, fig_title=''): fig = plt.figure(figsize=(0.1, 0.1)) # don't take up room initially fig.suptitle(fig_title) fig.set_size_inches(7.2, 5.4, forward=False) # resize but don't update gui ims = [] for image in images: im = plt.imshow(normalize_image(image), cmap='gray', vmin=0, vmax=1, animated=True) ims.append([im]) ani = ArtistAnimation(fig, ims, interval=50, blit=False, repeat_delay=1000) plt.close(ani._fig) return ani
def animation_viz(step, vizdir, epi): implots = [] fig = plt.figure(num=2, figsize=(20, 6)) fig.clf() for i in range(step): img = mpimg.imread(vizdir + str(epi) + "/eval-step" + str(i) + ".png") imgplot = plt.imshow(img) implots.append([imgplot]) animation = ArtistAnimation(fig, implots, interval=33, blit=True, repeat=False) plt.ioff() return animation
def plot_anim_max_acts( index, layer, model, figsize=(6, 6), interval=100, repeat_delay=1000, blit=True, fn=max_act, **kwargs ): """ Plots the gradient ascent of an activation image as an animation. Keyword arguments: layer -- The name of the layer in the model. Layers must be named in model. index -- The filter index to visualise, currently only one at a time. model -- The keras model to optimise to. figsize -- The size of the grid in inches interval -- Passed to matplotlib ArtistAnimation. repeat_delay -- Passed to matplotlib ArtistAnimation. blit -- Passed to matplotlib ArtistAnimation. fn -- The function to use to generate the images. Must return a single array of images. kwargs -- Any valid argument to `fn`. """ # Initialise the figure fig = plt.figure(figsize=figsize) # Get the image(s) images = list(fn(layer=layer, index=index, model=model, **kwargs)) # Generate a list of image plots. imshows = [[plt.imshow(deprocess_image(x), animated=True)] for x in images] plt.axis('off') # Get an animation object anim = ArtistAnimation( fig, imshows, interval=interval, repeat_delay=repeat_delay, blit=True ) # Closing the plot prevents showing the static plot. plt.close() return anim
def run_oned_linear_convection(method, nx, nt, x_min, x_max, dx, dt, c): # Generate figure for animation fig = pyplot.figure() ax = fig.add_subplot() frames = [] # Generate initial data u = get_oned_data(InitialDataType.SQUARE, nx=nx, dx=dx) # Apply `method` for `nt` times # and save each frame to create an animation for i in range(nt): oned_linear_convection(u=u, nx=nx, dx=dx, dt=dt, c=c) frames.append(ax.plot(np.linspace(x_min, x_max, nx), u, "r")) # Now create the animation at 1 frame every 25 milliseconds animation = ArtistAnimation(fig, frames, repeat=False, interval=25) # And render to an mp4 animation.save(f"{method.__name__}.mp4")
def visualise_sequence(self, max_time: float, frame_interval: float = 1): import matplotlib.pyplot as plt from matplotlib.animation import ArtistAnimation fig = plt.figure() images = [] for time in np.linspace(0, max_time, int(max_time / frame_interval)): image = self.create_frame(time) ax_img = plt.imshow(image.pixels, cmap='gray', animated=True) images.append([ax_img]) ani = ArtistAnimation(fig, images, interval=frame_interval * 1000, blit=True, repeat_delay=2 * max_time) plt.show()
def run_simulation(self): images = [] for i, person in enumerate(self.configuration.people): person.sit_down(self.configuration) x = plt.imshow(self.configuration.classroom.get_occupancy_matrix(), animated=True) images.append([x]) print(f"Finished step {i}") fig = plt.figure("animation") animation = ArtistAnimation(fig, images, interval=200, repeat_delay=0, blit=True) plt.show(animation)