def animate(self, compute_step, iterations, train_data_update_freq=20, test_data_update_freq=100, one_test_at_start=True, more_tests_at_start=False, save_movie=False):
def animate_step(i):
if (i == iterations // train_data_update_freq): #last iteration
compute_step(iterations, True, True)
else:
for k in range(train_data_update_freq):
n = i * train_data_update_freq + k
request_data_update = (n % train_data_update_freq == 0)
request_test_data_update = (n % test_data_update_freq == 0) and (n > 0 or one_test_at_start)
if more_tests_at_start and n < test_data_update_freq: request_test_data_update = request_data_update
compute_step(n, request_test_data_update, request_data_update)
# makes the UI a little more responsive
plt.pause(0.001)
if not self.is_paused():
return self._mpl_update_func()
self._animation = animation.FuncAnimation(self._mpl_figure, animate_step, int(iterations // train_data_update_freq + 1), init_func=self._mlp_init_func, interval=16, repeat=False, blit=False)
if save_movie:
mywriter = animation.FFMpegWriter(fps=24, codec='libx264', extra_args=['-pix_fmt', 'yuv420p', '-profile:v', 'high', '-tune', 'animation', '-crf', '18'])
self._animation.save("./tensorflowvisu_video.mp4", writer=mywriter)
else:
plt.show(block=True)
python类FFMpegWriter()的实例源码
def __init__(self, var_xarray, Nsteps, vmin, vmax, animationname):
# Global definitions
self.var = var_xarray
self.Nsteps = Nsteps
self.vmin = vmin
self.vmax = vmax
# Figure and axes
self.fig = plt.figure()
# self.ax = self.fig.axes()
# Animation definitio
anim = animation.FuncAnimation(self.fig, self.update, xrange(Nsteps), interval=1, blit=False)
# Writer FFMpeg needed for mp4 film
mywriter = animation.FFMpegWriter(bitrate=500)
anim.save(animationname, writer=mywriter, fps=1, extra_args=['-vcodec', 'libx264'], dpi=300)
# No init_plot needed
def animate(self, compute_step, iterations, train_data_update_freq=20, test_data_update_freq=100, one_test_at_start=True, more_tests_at_start=False, save_movie=False):
def animate_step(i):
if (i == iterations // train_data_update_freq): #last iteration
compute_step(iterations, True, True)
else:
for k in range(train_data_update_freq):
n = i * train_data_update_freq + k
request_data_update = (n % train_data_update_freq == 0)
request_test_data_update = (n % test_data_update_freq == 0) and (n > 0 or one_test_at_start)
if more_tests_at_start and n < test_data_update_freq: request_test_data_update = request_data_update
compute_step(n, request_test_data_update, request_data_update)
# makes the UI a little more responsive
plt.pause(0.001)
if not self.is_paused():
return self._mpl_update_func()
self._animation = animation.FuncAnimation(self._mpl_figure, animate_step, int(iterations // train_data_update_freq + 1), init_func=self._mlp_init_func, interval=16, repeat=False, blit=False)
if save_movie:
mywriter = animation.FFMpegWriter(fps=24, codec='libx264', extra_args=['-pix_fmt', 'yuv420p', '-profile:v', 'high', '-tune', 'animation', '-crf', '18'])
self._animation.save("./tensorflowvisu_video.mp4", writer=mywriter)
else:
plt.show(block=True)
def train(self, training_agent, total_episode, save_movie=False):
def animate_func(step):
#self.step = step
if step > total_episode:
print("Finish training ")
#plt.close()
else:
training_agent(episode=step, visual=self)
plt.pause(1.001) # makes the UI a little more responsive
if not self.ispause:
return self._update()
self.am = animation.FuncAnimation(self._fig, animate_func, total_episode, init_func=self._init, interval=16, repeat=False, blit=False)
if save_movie:
mywriter = animation.FFMpegWriter(fps=24, codec='libx264', extra_args=['-pix_fmt', 'yuv420p', '-profile:v', 'high', '-tune', 'animation', '-crf', '18'])
self.am.save("./video.mp4", writer=mywriter)
else:
plt.show(block=True)
def plot_anim(self, movesets, **kwargs):
pass
# DOESNT WORK SINE THE LENGTH OF A MOVESET IS VARIABLE
# setup = self.plot_moveset(movesets[0], show=False, export=True, export_plots=True, plot=True)
# fig = setup['fig']
# ax = setup['ax']
# plots = setup['plots']
#
# def update(i):
# label = 'Generation {}'.format(i)
# path, bumps = self.plot_moveset(movesets[i], export_data=True)
# path_xs, path_ys = Labyrinth._transform_array_into_xy(path)
# bumps_xs, bumps_ys = Labyrinth._transform_array_into_xy(bumps)
# # plots[0].set_offsets(bumps_xs, bumps_ys)
# # plots[1].set_offsets(path[0])
# # plots[2].set_offsets((path_xs[-1], path_ys[-1]))
# for i, j in enumerate(range(len(path)-2, -1, -1), 3):
# plots[i].set_positions([path_xs[i], path_ys[i]], [path_xs[i + 1], path_ys[i + 1]])
# # plots[len(plots)-1]
# return plots
#
# mywriter = animation.FFMpegWriter()
# ani = animation.FuncAnimation(fig, update, frames=np.arange(0, len(movesets)), interval=200)
# ani.save('asd.mp4', writer=mywriter)
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
tensorflowvisu.py 文件源码
项目:tensorflow-mnist-tutorial
作者: martin-gorner
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def animate(self, compute_step, iterations, train_data_update_freq=20, test_data_update_freq=100, one_test_at_start=True, more_tests_at_start=False, save_movie=False):
def animate_step(i):
if (i == iterations // train_data_update_freq): #last iteration
compute_step(iterations, True, True)
else:
for k in range(train_data_update_freq):
n = i * train_data_update_freq + k
request_data_update = (n % train_data_update_freq == 0)
request_test_data_update = (n % test_data_update_freq == 0) and (n > 0 or one_test_at_start)
if more_tests_at_start and n < test_data_update_freq: request_test_data_update = request_data_update
compute_step(n, request_test_data_update, request_data_update)
# makes the UI a little more responsive
plt.pause(0.001)
if not self.is_paused():
return self._mpl_update_func()
self._animation = animation.FuncAnimation(self._mpl_figure, animate_step, int(iterations // train_data_update_freq + 1), init_func=self._mlp_init_func, interval=16, repeat=False, blit=False)
if save_movie:
mywriter = animation.FFMpegWriter(fps=24, codec='libx264', extra_args=['-pix_fmt', 'yuv420p', '-profile:v', 'high', '-tune', 'animation', '-crf', '18'])
self._animation.save("./tensorflowvisu_video.mp4", writer=mywriter)
else:
plt.show(block=True)
def visualize(self, num=100, save=False):
"""
Visualizes given Sorting Algorithm
:param num: Number of points that has to be chosen for visualization
:param save: Boolean indicating whether to save animation in 'output' directory
"""
plt.title(self.sorter.name + " Visualization")
plt.xlabel("Array Index")
plt.ylabel("Element")
data = np.arange(num)
ran.shuffle(data)
self.sorter.sort(data, visualization=True)
self.hist_arr = self.sorter.hist_array
self.scatter = plt.scatter(np.arange(self.hist_arr.shape[1]), self.hist_arr[0]) # plt.scatter(x-array,y-array)
self.animation = animation.FuncAnimation(self.fig, self.__update, frames=self.hist_arr.shape[0], repeat=False,
blit=False, interval=1)
if save:
import os
import errno
path = "output"
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
path = os.path.join('output', self.sorter.name + ".mp4")
p1 = Process(
target=lambda: self.animation.save(path, writer=animation.FFMpegWriter(fps=100)))
p1.start()
plt.show()
def __init__(self, var_xarray, Nsteps, vmin, vmax, animationname):
# Global definitions
self.var = var_xarray
self.Nsteps = Nsteps
self.vmin = vmin
self.vmax = vmax
# Figure and axes
self.fig = plt.figure(figsize=(8,3))
self.ax=plt.axes(projection=ccrs.PlateCarree())
self.ax.set_extent([-90, 15, 25, 70],ccrs.PlateCarree())
self.plt_hdl = self.var[0, ...].plot.pcolormesh('nav_lon','nav_lat',ax=self.ax,
vmin=self.vmin, vmax=self.vmax,
transform=ccrs.PlateCarree())
plt.title(self.var[0, ...].coords['time_centered'].values, size=10) # to modify the title
#self.ax.title.set_size(10)
lon_tcks = range(-80,20,20)
lat_tcks = range(30,70,10)
self.ax.set_xticks(lon_tcks, crs=ccrs.PlateCarree())
self.ax.set_yticks(lat_tcks, crs=ccrs.PlateCarree())
self.ax.coastlines(resolution='50m') # Currently can be one of “110m”, “50m”, and “10m”
self.ax.gridlines()
# Animation definitio
anim = animation.FuncAnimation(self.fig, self.update, xrange(Nsteps), interval=1, blit=False)
# Writer FFMpeg needed for mp4 film
mywriter = animation.FFMpegWriter(bitrate=500)
anim.save(animationname, writer=mywriter, fps=1, extra_args=['-vcodec', 'libx264'], dpi=300)
#anim.save(animationname, writer=mywriter, fps=1, extra_args=['-vcodec', 'libx264'])
# No init_plot needed
def dfAnimate( df, movieName = None, nShaddow = 0, xRatio= 1.0, rate = 1 , xlim = None , ylim = None , xlabel = "x(m)" , ylabel = "Elevation(m)") :
"""
Animate a dataFrame where time is the index, and columns are the "spatial" position
"""
from matplotlib import animation
print ("Making animation file : " , movieName)
global pause
pause = False
def onClick(event):
global pause
pause ^= True
nShaddow = max(1,nShaddow)
fig, ax = plt.subplots()
fig.canvas.mpl_connect('button_press_event', onClick )
ls = []
for i in range(nShaddow) :
if i == 0 :
color = "black"
else :
color = "blue"
ltemp, = ax.plot( [], [], lw=1 , alpha = 1-i*1./nShaddow , color = color)
ls.append(ltemp)
xVal = df.columns
ax.grid(True)
if xlim :
ax.set_xlim( xlim )
else :
ax.set_xlim( min(xVal) , max(xVal) )
if ylim :
ax.set_ylim( ylim )
else :
ax.set_ylim( df.min().min() , df.max().max() )
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
def run(itime):
ax.set_title("{}s".format(df.index[itime*rate]) )
for s in range(nShaddow):
if not pause :
if itime > s :
ls[s].set_data( xVal , df.iloc[ rate*(itime - s) , : ] )
return ls
ani = animation.FuncAnimation( fig , run, range(len(df)), blit=True, interval=30, repeat=False)
if movieName is None :
plt.show()
else :
mywriter = animation.FFMpegWriter(fps = 25 , codec="libx264")
ani.save( movieName +'.mp4' , writer=mywriter)
def makeAnimation(filename , movieName = None, nShaddow = 20, xRatio= 1.0, version = "foamStar" , rate = 1) :
"""
Make a 2D animation of the wave field.
"""
print "Making animation file : " , movieName
nShaddow = max(1,nShaddow)
data = pd.read_csv(filename, comment = "#" , header=None , delim_whitespace=True, dtype = float).as_matrix()
if version == "foamStar" :
with open(filename , "r") as f :
f.readline() ; f.readline() ; xVal = [float(x) for x in f.readline().split()[2:]]
#Remove x = 0.0
if 0.0 in xVal :
i = xVal.index(0.0)
xVal.pop(i)
data = np.delete(data, i+1 , axis = 1)
xVal = np.array(xVal)
xVal /= xRatio
else :
xVal = np.linspace(0,1 , len(data[1,:]) -1 )
fig, ax = plt.subplots()
ls = []
for i in range(nShaddow) :
if i == 0 :
color = "black"
else :
color = "blue"
ltemp, = ax.plot([], [], lw=1 , alpha = 1-i*1./nShaddow , color = color)
ls.append(ltemp)
ax.grid(True)
ax.set_xlim( min(xVal) , max(xVal) )
ax.set_ylim( -1.5 , +1.5 )
ax.set_xlabel("x")
ax.set_ylabel("Elevation(m)")
def run(itime):
ax.set_title("{}s".format(data[itime*rate,0]) )
for s in range(nShaddow):
if itime > s :
ls[s].set_data( xVal , data[ rate*(itime - s),1:] )
return ls
ani = animation.FuncAnimation( fig , run, range(len(data)), blit=True, interval=30, repeat=False)
if movieName is None :
plt.show()
else :
mywriter = animation.FFMpegWriter(fps = 25 , codec="libx264")
ani.save( movieName +'.mp4',writer=mywriter)