我们从Python开源项目中,提取了以下20个代码示例,用于说明如何使用matplotlib.animation.writers()。
def plot_hist(str_name, save_name='dist'): data_array = utils.get_data(str_name) params = np.squeeze(np.array(data_array['information'])) ind_array = data_array['params']['epochsInds'] DKL_YgX_YgT = utils.extract_array(params, 'DKL_YgX_YgT') p_ts = utils.extract_array(params, 'pts') H_Xgt = utils.extract_array(params, 'H_Xgt') f, (axes) = plt.subplots(3, 1) #axes = [axes] f.subplots_adjust(left=0.14, bottom=0.1, right=.928, top=0.94, wspace=0.13, hspace=0.55) colors = LAYERS_COLORS line_ani = animation.FuncAnimation(f, update_bars_num_of_ts, len(p_ts), repeat=False, interval=1, blit=False, fargs=[p_ts,H_Xgt,DKL_YgX_YgT, axes,ind_array]) Writer = animation.writers['ffmpeg'] writer = Writer(fps=50) #Save the movie line_ani.save(save_name+'_movie.mp4',writer=writer,dpi=250) plt.show()
def make_video(xy,filename): FFMpegWriter = manimation.writers['ffmpeg'] metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie support!') writer = FFMpegWriter(fps=15, metadata=metadata) mydpi=100; #fig = plt.figure(figsize=(128/mydpi,128/mydpi)) fig = plt.figure(figsize=(32/mydpi,32/mydpi)) plt.xlim(-200, 200) plt.ylim(-200, 200) fig_num=len(xy); #color=['ro','bo','go','ko','yo','mo','co']; color=['r','b','g','k','y','m','c']; with writer.saving(fig, filename, len(xy)): for i in range(len(xy)): for j in range(len(xy[0])): #plt.plot(xy[i,j,1],xy[i,j,0],color[j%len(color)]); plt.scatter(xy[i,j,1],xy[i,j,0],c=color[j%len(color)],s=0.5); writer.grab_frame();
def make_video(xy,filename): os.system("rm -rf pics/*"); FFMpegWriter = manimation.writers['ffmpeg'] metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie support!') writer = FFMpegWriter(fps=15, metadata=metadata) fig = plt.figure() plt.xlim(-200, 200) plt.ylim(-200, 200) fig_num=len(xy); color=['ro','bo','go','ko','yo','mo','co']; with writer.saving(fig, filename, len(xy)): for i in range(len(xy)): for j in range(len(xy[0])): plt.plot(xy[i,j,1],xy[i,j,0],color[j%len(color)]); writer.grab_frame();
def save_frames(images, filename): num_sequences, n_steps, w, h = images.shape fig = plt.figure() im = plt.imshow(combine_multiple_img(images[:, 0]), cmap=plt.cm.get_cmap('Greys'), interpolation='none') plt.axis('image') def updatefig(*args): im.set_array(combine_multiple_img(images[:, args[0]])) return im, ani = animation.FuncAnimation(fig, updatefig, interval=500, frames=n_steps) # Either avconv or ffmpeg need to be installed in the system to produce the videos! try: writer = animation.writers['avconv'] except KeyError: writer = animation.writers['ffmpeg'] writer = writer(fps=3) ani.save(filename, writer=writer) plt.close(fig)
def writevideo(self): #print animation.writers.list() #matplotlib.rcParams['animation.ffmpeg_args'] = ['-report', '/tmp/ffmpeg.log'] #FFMpegWriter = animation.writers['ffmpeg'] metadata = dict(title='Github Data Projects', artist='0x0FFF', comment='Evolution of open source data projects') writer = FFMpegWriter(fps=30, bitrate=8000, metadata=metadata ) i = 0 #self.iters = 200 with writer.saving(self.fig, "/projects/personal/writer_test.mp4", 120): while i < self.iters: self.update_animation(i) writer.grab_frame() i += 1 return
def plot_animation(name_s, save_name): """Plot the movie for all the networks in the information plane""" # If we want to print the loss function also print_loss = False #The bins that we extened the x axis of the accuracy each time epochs_bins = [0, 500, 1500, 3000, 6000, 10000, 20000] data_array = utils.get_data(name_s[0][0]) data = data_array['infomration'] epochsInds = data_array['epochsInds'] loss_train_data = data_array['loss_train'] loss_test_data = data_array['loss_test_data'] f, (axes) = plt.subplots(2, 1) f.subplots_adjust(left=0.14, bottom=0.1, right=.928, top=0.94, wspace=0.13, hspace=0.55) colors = LAYERS_COLORS #new/old version if False: Ix = np.squeeze(data[0,:,-1,-1, :, :]) Iy = np.squeeze(data[1,:,-1,-1, :, :]) else: Ix = np.squeeze(data[0, :, -1, -1, :, :])[np.newaxis,:,:] Iy = np.squeeze(data[1, :, -1, -1, :, :])[np.newaxis,:,:] #Interploation of the samplings (because we don't cauclaute the infomration in each epoch) interp_data_x = interp1d(epochsInds, Ix, axis=1) interp_data_y = interp1d(epochsInds, Iy, axis=1) new_x = np.arange(0,epochsInds[-1]) new_data = np.array([interp_data_x(new_x), interp_data_y(new_x)]) """" train_data = interp1d(epochsInds, np.squeeze(train_data), axis=1)(new_x) test_data = interp1d(epochsInds, np.squeeze(test_data), axis=1)(new_x) """ if print_loss: loss_train_data = interp1d(epochsInds, np.squeeze(loss_train_data), axis=1)(new_x) loss_test_data=interp1d(epochsInds, np.squeeze(loss_test_data), axis=1)(new_x) line_ani = animation.FuncAnimation(f, update_line, len(new_x), repeat=False, interval=1, blit=False, fargs=(print_loss, new_data, axes,new_x,train_data,test_data,epochs_bins, loss_train_data,loss_test_data, colors)) Writer = animation.writers['ffmpeg'] writer = Writer(fps=100) #Save the movie line_ani.save(save_name+'_movie2.mp4',writer=writer,dpi=250) plt.show()
def plot_animation_each_neuron(name_s, save_name, print_loss=False): """Plot the movie for all the networks in the information plane""" # If we want to print the loss function also #The bins that we extened the x axis of the accuracy each time epochs_bins = [0, 500, 1500, 3000, 6000, 10000, 20000] data_array = utils.get_data(name_s[0][0]) data = np.squeeze(data_array['information']) f, (axes) = plt.subplots(1, 1) axes = [axes] f.subplots_adjust(left=0.14, bottom=0.1, right=.928, top=0.94, wspace=0.13, hspace=0.55) colors = LAYERS_COLORS #new/old version Ix = np.squeeze(data[0,:, :, :]) Iy = np.squeeze(data[1,:, :, :]) #Interploation of the samplings (because we don't cauclaute the infomration in each epoch) #interp_data_x = interp1d(epochsInds, Ix, axis=1) #interp_data_y = interp1d(epochsInds, Iy, axis=1) #new_x = np.arange(0,epochsInds[-1]) #new_data = np.array([interp_data_x(new_x), interp_data_y(new_x)]) """" train_data = interp1d(epochsInds, np.squeeze(train_data), axis=1)(new_x) test_data = interp1d(epochsInds, np.squeeze(test_data), axis=1)(new_x) if print_loss: loss_train_data = interp1d(epochsInds, np.squeeze(loss_train_data), axis=1)(new_x) loss_test_data=interp1d(epochsInds, np.squeeze(loss_test_data), axis=1)(new_x) """ line_ani = animation.FuncAnimation(f, update_line_each_neuron, Ix.shape[1], repeat=False, interval=1, blit=False, fargs=(print_loss, Ix, axes,Iy,train_data,test_data,epochs_bins, loss_train_data,loss_test_data, colors,epochsInds)) Writer = animation.writers['ffmpeg'] writer = Writer(fps=100) #Save the movie line_ani.save(save_name+'_movie.mp4',writer=writer,dpi=250) plt.show()
def ani_frame(): dpi = 600 fig = plt.figure() ax = fig.add_subplot(111) ax.set_aspect('equal') plt.xlim(0,151); plt.ylim(0,151); ws2 = copy.deepcopy(ws); fig.set_size_inches([5,5]) plt.tight_layout() ws2.plot(ax = ax); shifts = np.linspace(0,50,100); def update_fig(n): ax.cla(); ws2 = copy.deepcopy(ws); ws2.move_forward(shifts[n]); ws2.plot(ax = ax); ax.set_xlim(0,151); ax.set_ylim(0,151); return ax #legend(loc=0) ani = animation.FuncAnimation(fig,update_fig,100,interval=30) writer = animation.writers['ffmpeg'](fps=30) ani.save('forward.mp4',writer=writer,dpi=dpi) return ani
def ani_frame(): dpi = 600 fig = plt.figure() ax = fig.add_subplot(111) ax.set_aspect('equal') plt.xlim(0,151); plt.ylim(0,151); ws2 = copy.deepcopy(ws); fig.set_size_inches([5,5]) plt.tight_layout() ws2.plot(ax = ax); shifts = np.linspace(-1,1,100); def update_fig(n): ax.cla(); ws2 = copy.deepcopy(ws); ws2.bend(shifts[n], head = True, exponent = 2); ws2.plot(ax = ax); ax.set_xlim(0,151); ax.set_ylim(0,151); return ax #legend(loc=0) ani = animation.FuncAnimation(fig,update_fig,100,interval=30) writer = animation.writers['ffmpeg'](fps=30) ani.save('bend.mp4',writer=writer,dpi=dpi) return ani
def __init__(self, plots, times, time_stamp = True, time_stamp_text = time_stamp_text, time_stamp_font_size = 1, time_stamp_color = 'k', time_stamp_position = None, figure = None, save = None, dpi = 300, fps = 30, pause = None, verbose = True): self.plots = plots; self.times = times; if figure is None: self.figure = plt.gcf(); else: self.figure = figure; self.pause = pause; # time stamp text if time_stamp: self.time_stamp_text = time_stamp_text; tt = time_stamp_text(0,0); if time_stamp_position is None: self.time_stamp = figure.suptitle(tt, fontsize = time_stamp_font_size, color = time_stamp_color); else: self.time_stamp = plt.annotate(tt, time_stamp_position, xycoords = 'figure fraction', verticalalignment = 'center', horizontalalignment = 'left', fontsize = time_stamp_font_size, color = time_stamp_color); else: self.time_stamp = None; # movie saver if save is not None: FFMpegWriter = manimation.writers['ffmpeg'] #FFMpegWriter = manimation.writers['mencoder'] metadata = dict(title='Strain %s Worm %d', artist='Chirstoph Kirst', comment='C Elegans Dataset, Bargmann Lab') self.writer = FFMpegWriter(fps=fps, metadata=metadata); self.writer.setup(self.figure, save, dpi = dpi); else: self.writer = None; self.time_id = np.argmax(times[:,-1]);
def anim_to_mp4(anim, audio_file, filename, save_dir): writer = animation.writers['ffmpeg'] writer = writer(fps=REFRESH_RATE, bitrate=SAMPLING_RATE) filename = os.path.join(save_dir, filename) if not hasattr(anim, '_encoded_video'): anim.save(filename + '_temp.mp4', writer=writer) call(['rm', filename + '.mp4']) call([ 'ffmpeg', '-i', filename + '_temp.mp4', '-i', os.path.join(save_dir, audio_file), filename + '.mp4']) call(['rm', filename + '_temp.mp4'])
def initialize_movie_writer(**kwargs): ''' Initializes movie writer for simulation animation. Parameters ---------- There are only optional keyword inputs here. 'metadata': metadata for movie. 'title', 'artist', 'comment' are metadata inputs. 'qm' : sets frame rate. Framerate is 40/qm. Returns --------- FFMpegWriter : manimation object writer for animation''' FFMpegWriter = manimation.writers['ffmpeg'] if 'metadata' in kwargs: metadata = kwargs['metadata'] else: metadata = dict(title='Movie Test', artist='Matplotlib', comment='Movie support!') if 'qm' in kwargs: qm = kwargs['qm'] if 1 <= qm <= 4: qm = qm else: qm = 1 else: qm = 1 return FFMpegWriter(fps=int(40. / qm), bitrate=3000, metadata=metadata)
def animate(image_arrays, title="demo", size_inch=3, format="mp4"): print "Let's create awesome animation!" dpi = 100 fig = plt.figure() ax = fig.add_subplot(111) ax.set_aspect('equal') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) height, width = image_arrays[0].shape image_count = len(image_arrays) im = ax.imshow(rand(width, height), cmap='gray', interpolation='nearest') im.set_clim([0, 1]) fig.set_size_inches([size_inch, size_inch]) # size of created video tight_layout() def update_img(n): im.set_data(image_arrays[n]) return im # legend(loc=0) ani = animation.FuncAnimation(fig, update_img, frames=image_count, interval=30) filename = "" if format == "mp4": writer = animation.writers['ffmpeg'](fps=30) filename = '%s.mp4' % title ani.save(filename, writer=writer, dpi=dpi) elif format == "gif": filename = '%s.gif' % title ani.save(filename, writer='imagemagick') else: print "unsupported format type!:%s" % format return print "%s is created!" % filename return ani # test to creating animation
def save(self, filename, fps=15, bitrate=1800): from matplotlib import animation _writer = animation.writers['ffmpeg'] writer = _writer(fps=fps, metadata=dict(artist='Ming'), bitrate=bitrate) self.ani.save(filename, writer)
def ani_frame(): fig = plt.figure() ax = fig.add_subplot(111) ax.set_aspect('equal') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) im = ax.imshow(rand(300,300),cmap='gray',interpolation='nearest') im.set_clim([0,1]) fig.set_size_inches([5,5]) tight_layout() def update_img(n): tmp = rand(300,300) im.set_data(tmp) return im #legend(loc=0) ani = animation.FuncAnimation(fig,update_img,300,interval=30) writer = animation.writers['ffmpeg'](fps=30) ani.save('demo.mp4',writer=writer,dpi=dpi) return ani
def save_true_generated_frames(true, generated, filename): num_sequences, n_steps, w, h = true.shape # Background is 0, foreground as 1 true = np.copy(true[:16]) true[true > 0.1] = 1 # Set foreground be near 0.5 generated = generated * .5 # Background is 1, foreground is near 0.5 generated = 1 - generated[:16, :n_steps] # Subtract true from generated so background is 1, true foreground is 0, # and generated foreground is around 0.5 images = generated - true # images[images > 0.5] = 1. fig = plt.figure() im = plt.imshow(combine_multiple_img(images[:, 0]), cmap=plt.cm.get_cmap('gist_heat'), interpolation='none', vmin=0, vmax=1) plt.axis('image') def updatefig(*args): im.set_array(combine_multiple_img(images[:, args[0]])) return im, ani = animation.FuncAnimation(fig, updatefig, interval=500, frames=n_steps) try: writer = animation.writers['avconv'] except KeyError: writer = animation.writers['ffmpeg'] writer = writer(fps=3) ani.save(filename, writer=writer) plt.close(fig)
def animate(self, save=False): """ Animates the Given algorithm with given Graph :param save: Boolean indicating weather output has to be written into output/ """ result = self.fn(self.graph) for matrix, active in result: self.frames.append(matrix) self.active.append(active) # Draw the original matrix if self.pos is None: self.pos = nx.nx_pydot.graphviz_layout(self.graph) nx.draw_networkx_nodes(self.graph, self.pos, ax=self.ax1, node_color='g', alpha=0.8, node_size=self.node_size).set_edgecolor('k') nx.draw_networkx_edges(self.graph, self.pos, ax=self.ax1, alpha=0.6) if self.weights: nx.draw_networkx_edge_labels(self.graph, self.pos, ax=self.ax1, edge_labels=nx.get_edge_attributes(self.graph, 'weight')) if self.lables: nx.draw_networkx_labels(self.graph, self.pos, ax=self.ax1) # Draw its adjacancy matrix vmin = 0 vmax = np.max(np.ma.array(self.frames[-1], mask=np.isinf(self.frames[-1]))) cmap = plt.get_cmap('jet') cmap.set_bad('white', 1.) masked_array = np.ma.array(self.frames[0], mask=np.isinf(self.frames[0])) self.ax2.imshow(masked_array, interpolation='nearest', vmin=vmin, vmax=vmax, alpha=0.7) if self.matrix_labels: self.__plot_matrix_labels(self.frames[0], self.ax2) # Now start the animation x = animation.FuncAnimation(self.fig, self.__update, interval=1000, blit=False, repeat=False, init_func=self.__init_animation, frames=len(self.frames)) if save: import errno import os path = "output" try: os.makedirs(path) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise Writer = animation.writers['ffmpeg'] writer = Writer(fps=1, metadata=dict(artist='V'), bitrate=1800) from multiprocessing import Process import os path = os.path.join('output', '%s.mp4' % self.fn.__name__) Process(target=x.save, args=(path,), kwargs={'writer': writer}).start() plt.show()
def build_figure(self): # plot each markevery case for linear x and y scales figsize = (10, 8) fig = plt.figure(num=1, figsize=figsize) axes_list = [] num_rows = len(self.row_list) outer_grid = gridspec.GridSpec(num_rows, 1) for row in range(num_rows): # outer_ax = fig.add_subplot(outer_grid[row]) # if self.row_list[row][1] != '': # outer_ax.set_title(self.row_list[1]) inner_grid = gridspec.GridSpecFromSubplotSpec(1, self.num_ex, subplot_spec=outer_grid[row], wspace=0.0, hspace=0.0) image_row = self.row_list[row][0] for col in range(self.num_ex): ax = plt.Subplot(fig, inner_grid[col]) ax.set_xticks([]) ax.set_yticks([]) axes_list.append(fig.add_subplot(ax)) if row==0: axes_list[-1].set_title('ex{}'.format(col)) axes_list[-1].imshow(image_row[0][col], interpolation='none') plt.axis('off') fig.tight_layout() plt.show() # initialization function: plot the background of each frame # Set up formatting for the movie files Writer = animation.writers['imagemagick_file'] writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800) # call the animator. blit=True means only re-draw the parts that have changed. anim = animation.FuncAnimation(fig, self.animate, init_func=self.init, frames=13, interval=50, blit=True) anim.save('basic_animation.gif', writer='imagemagick') plt.show()