def test_matplotlib(): if PYTHON_VERSION in ('2.7', '3.3'): return #for now, python 3.5 installs a version of matplotlib that complains #about $DISPLAY variable, so lets just ignore for now. if PYTHON_VERSION == '3.5' and TRAVIS: return import matplotlib.pyplot as plt import numpy as np from moviepy.editor import VideoClip from moviepy.video.io.bindings import mplfig_to_npimage x = np.linspace(-2, 2, 200) duration = 2 fig, ax = plt.subplots() def make_frame(t): ax.clear() ax.plot(x, np.sinc(x**2) + np.sin(x + 2 * np.pi / duration * t), lw=3) ax.set_ylim(-1.5, 2.5) return mplfig_to_npimage(fig) animation = VideoClip(make_frame, duration=duration) animation.write_gif(os.path.join(TMP_DIR, 'matplotlib.gif'), fps=20)
def video(): if 1: snd = AudioFileClip("space.mp3") clip = VideoClip(c.animation, duration=snd.duration / 30.) clip = clip.set_audio(snd).set_duration(snd.duration / 30.) clip.write_videofile('cam.mp4', fps=24)
def __init__(self, make_rgba_frame, duration=None): self.rgba_buffer = None self.last_t = None def save_last_rgba_frame(t): # only create a new frame if the time is different from that of the last frame if t != self.last_t: self.rgba_buffer = make_rgba_frame(t) if not isinstance(self.rgba_buffer, np.ndarray): raise Exception(f'The rgba buffer is not a numpy array but of type "{type(self.rgba_buffer)}".') if self.rgba_buffer.dtype != np.uint8: raise Exception(f'The rgba buffer needs to be an 8-bit uint array, not "{self.rgba_buffer.dtype}".') # update the time stamp of the last created frame self.last_t = t # frame function for image data def make_frame(t): save_last_rgba_frame(t) return self.rgba_buffer[..., :3] # frame function for mask data def make_mask_frame(t): save_last_rgba_frame(t) return self.rgba_buffer[..., 3] / 255 super(RGBAVideoClip, self).__init__(make_frame, duration=duration) self.mask = VideoClip(make_mask_frame, ismask=True, duration=duration)
def save_video(self): """ Generate video out of self.state_history and save it. This variable needs to be updated during the simulation. """ import matplotlib.pyplot as plt from moviepy.editor import VideoClip from moviepy.video.io.bindings import mplfig_to_npimage history_of_states = self.state_history #duration_in_seconds = len(history_of_states) / 4 duration_in_seconds = len(history_of_states) fig, ax = plt.subplots() frames_per_second = len(history_of_states) / duration_in_seconds def make_frame(t): ax.clear() ax.grid(False) ax.imshow(history_of_states[int(t * frames_per_second)], cmap="gist_ncar") ax.tick_params(axis='both', which='both', bottom=False, top=False, left=False, right=False, labelleft=False, labelbottom=False) return mplfig_to_npimage(fig) animation = VideoClip(make_frame, duration=duration_in_seconds) animation.write_videofile(self.env.video_filename, fps=frames_per_second)
def test_matplotlib(): #for now, python 3.5 installs a version of matplotlib that complains #about $DISPLAY variable, so lets just ignore for now. if sys.version_info < (3, 4): return if sys.version_info.major == 3 and sys.version_info.minor == 5: return import matplotlib.pyplot as plt import numpy as np from moviepy.editor import VideoClip from moviepy.video.io.bindings import mplfig_to_npimage x = np.linspace(-2, 2, 200) duration = 2 fig, ax = plt.subplots() def make_frame(t): ax.clear() ax.plot(x, np.sinc(x**2) + np.sin(x + 2 * np.pi / duration * t), lw=3) ax.set_ylim(-1.5, 2.5) return mplfig_to_npimage(fig) animation = VideoClip(make_frame, duration=duration) animation.write_gif('/tmp/matplotlib.gif', fps=20)
def make_gif(self, filename): def make_frame(t): fig = self.iterate(t) return mplfig_to_npimage(fig) animation = VideoClip(make_frame, duration=self.T_max) animation.write_gif(filename, fps=20)
def render_video(width, height, duration, filename, bg_color=(0, 0, 0, 1)): """Render a video.""" import numpy as np from moviepy.editor import VideoClip def make_frame(frame_num): surface = build_frame( width, height, height * 0.4, num_iters=11, num_points=3, r_mult=0.5, c_mult=0.5, d_angle=frame_num * 25 * 2 * math.pi / 300, bg_color=bg_color, ) buf = surface.get_data() frame_uint32 = np.ndarray(shape=(height, width), dtype=np.uint32, buffer=buf) frame = np.zeros(shape=(height, width, 3), dtype=np.uint8) frame[:, :, 0] = ((frame_uint32 >> 16) & 0xff).astype(np.uint8) frame[:, :, 1] = ((frame_uint32 >> 8) & 0xff).astype(np.uint8) frame[:, :, 2] = (frame_uint32 & 0xff).astype(np.uint8) return frame # render video animation = VideoClip(make_frame, duration=duration) animation.write_gif(filename, fps=25)
def render_gif(pov_file, args): prog_args = [] FPS = None initial_clock = 0 final_clock = None for arg in args: if '=' in arg: key, value = arg.split('=') key = key.strip().lower() if key == 'initial_clock': initial_clock = float(value) elif key == 'final_clock': final_clock = float(value) elif key == 'fps': FPS = float(value) else: prog_args.append(arg) else: prog_args.append(arg) if final_clock is None: raise ValueError('Final_Clock must be set at top of file') if FPS is None: raise ValueError('FPS must be set at top of file') make_frame = frame_gen(pov_file, prog_args, initial_clock) clip = VideoClip(make_frame, duration=final_clock - initial_clock) output_gif = pov_file.replace('.pov', '.gif') clip.write_gif(output_gif, fps=FPS, program='ffmpeg')
def cubes_to_animation(cubes, clim=None, figsize=(10,11), title=None, fontsize=24, fps=16, **kwargs): from moviepy.editor import VideoClip from moviepy.video.io.bindings import mplfig_to_npimage if len(cubes.shape)<3: cubes = cubes.reshape([1, *cubes.shape]) if clim is None: clim = (np.min(cubes[0]), np.max(cubes[0])) fig = plt.figure(figsize=figsize) nframe = cubes.shape[1] def make_frame(t): ind = int(round(t*fps)) plt.cla() plt.imshow(cubes[0, ind, :, :], interpolation='none', clim=clim, **kwargs ) # plt.axis('off') titlestr = 'Frame no. {}'.format(ind) if title: titlestr = title + ' - ' + titlestr plt.title(titlestr, fontsize=fontsize) return mplfig_to_npimage(fig) animation = VideoClip(make_frame, duration=nframe/fps) plt.clf() return animation
def clip_title(fig, title='title', fontsize=40): ''' Make a videoclip with a centered white title ''' from moviepy.editor import VideoClip from moviepy.video.io.bindings import mplfig_to_npimage duration = 1 ax = plt.gca() left, width = .25, .5 bottom, height = .25, .5 right = left + width top = bottom + height def make_frame(t): ax = plt.gca() ax = fig.add_axes([0, 0, 1, 1]) ax.text(0.5 * (left + right), 0.5 * (bottom + top), title, horizontalalignment='center', verticalalignment='center', fontsize=fontsize, color='white', transform=ax.transAxes) return mplfig_to_npimage(fig) animation = VideoClip(make_frame, duration=duration) return animation
def demo(filename, tracking, output, t_start=0., t_end=None, shift=0., labels=None, landmark=None, height=200): # parse label file if labels is not None: with open(labels, 'r') as f: labels = {} for line in f: identifier, label = line.strip().split() identifier = int(identifier) labels[identifier] = label video = Video(filename) import os os.environ['IMAGEIO_FFMPEG_EXE'] = 'ffmpeg' # from moviepy.video.io.VideoFileClip import VideoFileClip from moviepy.editor import VideoClip, AudioFileClip make_frame = get_make_frame(video, tracking, landmark=landmark, labels=labels, height=height, shift=shift) video_clip = VideoClip(make_frame, duration=video.duration) audio_clip = AudioFileClip(filename) clip = video_clip.set_audio(audio_clip) if t_end is None: t_end = video.duration clip.subclip(t_start, t_end).write_videofile(output, fps=video.frame_rate)
def create_videoclip(frames, duration, frame_rate, audio_in=None): """ Create a VideoClip object :param frames: a iterator returning numpy frame objects :param duration: Duration of clip in seconds :param audio_in: file name of audio file, or None :return: """ def make_frame(t): nonlocal current_frame nonlocal current_frame_index required_frame_index = int(t * frame_rate) if required_frame_index > current_frame_index: current_frame = next(frames) current_frame_index += 1 rgb_frame = np.empty( (current_frame.shape[0], current_frame.shape[1], 3), dtype=np.uint8) rgb_frame[:, :] = current_frame[:, :, 0:3] return rgb_frame current_frame = next(frames) current_frame_index = 0 video_clip = VideoClip(make_frame, duration=duration) if audio_in: print("Adding audio clip", audio_in) audio_clip = AudioFileClip(audio_in).subclip(0, duration) video_clip = video_clip.set_audio(audio_clip) return video_clip
def create_NN_comparison(clip, h5, nnh5, inds2plot=np.arange(100), pad=400, outfname=None): """ Give movipy.videofile, dlc tracked h5 and RNN h5, plot indices in inds2plot and save as outfname. """ tlag = h5.shape[0] - nnh5.shape[0] h5 = h5[tlag:] center = medfilt2d(h5[:, 8, :2], [7, 1]) h5 = egoh5(h5) connections = [[0, 2, 5, 10, 12], [0, 1, 4, 7, 9, 12], [0, 3, 6, 8, 11, 12], [1, 2, 3], [4, 5, 6], [7, 8], [9, 10, 11]] fig, ax = plt.subplots(figsize=(10, 10)) def make_frame(i): t = inds2plot[int(i * clip.fps)] ax.clear() ax.imshow(clip.get_frame((t + tlag) / clip.fps)) for l in connections: ax.plot(h5[t, l, 0] + center[t, 0], h5[t, l, 1] + center[t, 1], color='royalblue', alpha=0.5, lw=3)[0] ax.plot(nnh5[t, l, 0] + center[t, 0], nnh5[t, l, 1] + center[t, 1], color='orangered', alpha=0.5, lw=3)[0] ax.set_xlim([center[t, 0] - pad, center[t, 0] + pad]) ax.set_ylim([center[t, 1] - pad, center[t, 1] + pad]) ax.axis('off') return mplfig_to_npimage(fig) animation = VideoClip(make_frame, duration=inds2plot.shape[0] / clip.fps) # animation.write_gif('matplotlib.gif', fps=clip.fps) if outfname is None: outfname = 'videos/vid_' + ''.join( [np.random.choice(list(string.ascii_letters)) for _ in range(20)]) + '.mp4' animation.write_videofile(outfname, fps=clip.fps, audio=False, threads=12) print('Video saved as ', outfname) else: if outfname[-4:] != '.mp4': outfname += '.mp4' outfname = 'videos/' + outfname animation.write_videofile(outfname, fps=clip.fps, audio=False, threads=12) print('Video saved as ', outfname)
def ipython_display(self, *args, **kwargs): """ Fixes inheritance naming issue with moviepy's ipython_display """ seg_copy = self.copy() # Class should also always be set to VideoClip for expected video display seg_copy.__class__ = VideoClip().__class__ return seg_copy.ipython_display(*args, **kwargs)
def make_gif(self, file_name): def make_frame(t): fig = self.iterate(t) img = mplfig_to_npimage(fig) plt.close(fig) return img animation = VideoClip(make_frame, duration=self.duration) animation.write_gif(file_name, fps=self.fps)
def save_animation(self, name): self._index = 0 duration = self.num_data // self.fps anim = VideoClip(make_frame=self.make_frame, duration=duration) # anim.write_gif(os.path.join(self.DIR, name), fps=self.fps) anim.write_videofile(os.path.join(self.DIR, name), fps=self.fps, audio=False) print(duration)
def save(self, path): fname, ext = os.path.splitext(path) duration = (len(self.frames) - 1) / float(self.fps) self.animation = VideoClip(self._make, duration=duration) if 'gif' in ext: self.animation.write_gif(path, fps=self.fps) else: self.animation.write_videofile(path, fps=self.fps) self._iter = -1
def plot_voxels(gridLabels, suncg_labels, vox_min, vox_unit, save_path=None, animate=False): nbr_classes = len(suncg_labels) canvas = scene.SceneCanvas(keys='interactive', bgcolor='w', size=(1920, 1080)) view = canvas.central_widget.add_view() azimuth = 30 view.camera = scene.TurntableCamera(up='y', distance=4, fov=70, azimuth=azimuth, elevation=30.) # Sample colormap and adjust alpha colormap = get_colormap('cubehelix') cm_sampled = [] for i, (iclass, sample_f) in enumerate( zip(suncg_labels, np.linspace(0, 1, nbr_classes))): if iclass.lower() in ('free', 'ceiling'): alpha = 0 elif iclass.lower() in ('floor', 'wall', 'window'): alpha = 0.6 else: alpha = 1.0 cm_sampled.append(Color(color=colormap[sample_f].rgb, alpha=alpha)) my_cm = AlphaAwareCM(cm_sampled) volume = scene.visuals.Volume(gridLabels, relative_step_size=0.1, method='mip', parent=view.scene, cmap=my_cm, clim=[0, nbr_classes - 1], emulate_texture=False) volume.transform = scene.transforms.MatrixTransform() volume.transform.scale(3 * [vox_unit]) volume.transform.translate(3 * [-vox_unit * gridLabels.shape[0] / 2.0]) if save_path is None: return def make_frame(t): view.camera.set_state({'azimuth': azimuth + t * 90}) return canvas.render() if animate: animation = VideoClip(make_frame, duration=3) animation.write_gif('voxel.gif', fps=8, opt='OptimizePlus') else: img = canvas.render() cv2.imwrite('voxel.png', img[::-1])
def moviepy_animate(self): self.prepare() if USE_MOVIEPY: self.ani = VideoClip( self.moviepy_update, duration=self.bf.particles.get_number_of_frames() / FPS) # FIXME: duration in seconds else: for i in range(self.bf.particles.get_number_of_frames()): print(i) self.moviepy_update(i)
def foldin(cliplist, length): a = 0 duration = min(cliplist, key=lambda x: x.duration).duration print(duration) result = VideoClip(duration=0) result.size = (0, 0) while result.duration < duration: for i in cliplist: if (a < i.duration and a + length < i.duration): seg = i.subclip(a, a + length) result = concatenate_videoclips([result, seg]) return result
def cli(ctx, opt_dir_in, opt_fp_out, opt_fps, opt_bitrate, opt_codec, opt_ext, opt_slice, opt_random, opt_force): """Converts still image sequence to video""" from glob import glob from pathlib import Path import random import cv2 as cv import numpy as np import blend_modes from moviepy.editor import VideoClip from tqdm import tqdm from app.utils import file_utils log = app_cfg.LOG log.info('Generating movie file') if not opt_fp_out: opt_fp_out = str( Path(opt_dir_in).parent / f'{Path(opt_dir_in).name}.mp4') if Path(opt_fp_out).is_dir() and not opt_force: log.error(f'{opt_fp_out} exists. Use "-f/--force" to overwrite') # glob comp images fps_im = sorted( [im for im in glob(str(Path(opt_dir_in) / f'*.{opt_ext}'))]) if opt_slice: fps_im = fps_im[opt_slice[0]:opt_slice[1]] if opt_random: random.shuffle(fps_im) opt_bitrate = f'{opt_bitrate}M' # megabits / second num_frames = len(fps_im) duration_sec = num_frames / opt_fps def make_frame(t): #global fps_im frame_idx = int(np.clip(np.round(t * opt_fps), 0, num_frames - 1)) fp_im = fps_im[frame_idx] im = cv.cvtColor(cv.imread(fp_im), cv.COLOR_BGR2RGB) # Moviepy uses RGB return im log.info('Generating movieclip...') VideoClip(make_frame, duration=duration_sec).write_videofile(opt_fp_out, fps=opt_fps, codec=opt_codec, bitrate=opt_bitrate) log.info('Done.')
def main(): parser = argparse.ArgumentParser( prog='AniMaker', description='动画短片制作器by lzy2002 site:lzy2002.com') parser.add_argument('-i', '--inputs', help='输入文件所在目录', required=True) parser.add_argument('-o', '--output', help='输出文件', default='movie.mp4') parser.add_argument('-f', '--fps', help='帧频fps', default=24) parser.add_argument('-rf', '--recordfps', help='录制帧频fps', default=60) parser.add_argument('-t', '--time', help='时长s', default=5) args = parser.parse_args() animation = VideoClip(make_frame(args.inputs, float(args.recordfps), int(args.fps), float(args.time)), duration=float(args.time)) animation.write_videofile(args.output, fps=int(args.fps))
def saveMovie(self, zoomfactor=1.0, savename='None', appendix='', update=False, fps=25): """ save tif file as mp4 using moviepy library. The duration of movie file is determined as 3 times of realtime video. Input: zoomfactor = 0.5 (default), save image using resampling savename = default format [tif file name]_z[zoomefactor].mp4 Return: VidoeClip object in moviepy library """ if ('moviepy' not in dir()): from moviepy.editor import VideoClip if ('cv2' not in dir()): import cv2 if (savename == 'None'): savename = '{}_z{:.1f}_{}.mp4'.format(self._meta['fname'][:-4], zoomfactor, appendix) if not update: if os.path.exists(savename): if self._debug: print('... movie file already exists: %s' % savename) return False if self._single: if self._debug: print('... not movie file') return False cmap = plt.get_cmap(self._meta['cmapname']) def make_frame(t): #self._curframe = int(t * (self._frameN - 1) / (self._duration * 3.0)) self._curframe = int(t * fps) img0 = self.getframe(frame=self._curframe, dtypes='uint8') if zoomfactor != 1.0: img0 = cv2.resize(img0, None, fx=zoomfactor, fy=zoomfactor, interpolation=cv2.INTER_CUBIC) img = np.delete(cmap(img0), 3, 2) #return img return (img * 255.0).astype('uint8') #animation = VideoClip(make_frame, duration=self._duration * 3.0) animation = VideoClip(make_frame, duration=float(self._meta.N()/fps)) animation.write_videofile(savename, fps=fps, codec='libx264', \ threads=8, audio=False, preset='medium', verbose=False) self._animation = animation print("""To play movie file in jupyter notebook: from IPython.display import Video Video("{}")""".format(savename))
def gen_mv(self): # generates the music video combining gif and audio def make_frame(t): ind = int(t//self.period) frame = self.screens[ind] return frame[:,:,None] * np.ones((1,1,3),np.uint8) total_duration = len(self.screens)*self.period # in seconds animation = VideoClip(make_frame, duration=total_duration) # pdb.set_trace() audio = AudioFileClip(self.mfile) animation.set_audio(audio).write_videofile("test.mp4",fps=20)
def animate_wave_function_collapse(fn, seconds_per_state=0.5): size = (32, 32) tn = wfc.seq_target_name(fn, 1, "overlapping", size) ts, result = dep.create(tn) full_duration = len(result) * seconds_per_state def makeframe(t): state_index = int(t / seconds_per_state) return result[min(state_index, len(result)-1)] anim = VideoClip(makeframe, duration=full_duration) nfn = os.path.splitext(fn)[0] + ".collapse.mp4" anim.write_videofile(nfn, fps=FRAMERATE) nfn = os.path.splitext(fn)[0] + ".collapsed.png" imsave(nfn, result[-1])
def make_skeleton_animation(frames, index, fps, movies_dir): DEFAULT_FPS = 30.0 def make_frame(t): verticies = frames[int(t * DEFAULT_FPS)] edges = zip(range(len(CONNECT)), CONNECT) arr = render_offscreen(verticies, edges, WIDTH, HEIGHT) return arr duration = frames.shape[0] / DEFAULT_FPS animation = VideoClip(make_frame, duration=duration) file_path = os.path.join(movies_dir, "sequence_{}.mp4".format(index)) animation.write_videofile(file_path, fps=fps)
def trajectory_video(trajectory, filename, xlim=(-10, 10), ylim=(-10, 10), callback=None, axisOff=True): """Create video of the track and saves it in working directory Parameters --------- filename : string name of the file to be saved into xlim : touple(2) of float xlimits of the fideo ylim : touple(2) of float ylimits of the video callback: what to axisOff : bool Returns -------- saved mp4 video at fiven filepath """ WIDTH = 900 HEIGHT = 600 DPI = 150 FPS = 25 DURATION = np.max(trajectory.time) - np.min(trajectory.time) fig, axis = plt.subplots(figsize=(1.0 * WIDTH / DPI, 1.0 * HEIGHT / DPI), dpi=DPI) def make_frame(t): axis.clear() (tx, ty) = trajectory.position_for_time(t + np.min(trajectory.time)) axis.plot(tx, ty, "ko") axis.set_xlim(xlim) axis.set_ylim(ylim) axis.set_title("Time {:.2f} s".format(t)) if not callback is None: callback(axis) if axisOff: plt.axis('off') return mplfig_to_npimage(fig) animation = VideoClip(make_frame, duration=DURATION) #animation.write_gif(filename, fps=FPS) animation.write_videofile(filename, fps=FPS) pass
def save_movie(make_frame, duration, filename, fps=20): """Writes an animation to disk""" anim = VideoClip(make_frame, duration=duration) if filename.endswith('.gif'): anim.write_gif(filename, fps=fps) elif filename.endswith('.mp4'): anim.write_videofile(filename, fps=fps) else: raise ValueError( f'Invalid file type for {filename}. Must be .gif or .mp4') return anim
def implay(array): try: if array.dtype != np.uint8: array = (array * 255).astype(np.uint8) def make_frame(t): return array[..., round(t * 30.0)] clip = VideoClip(make_frame, duration=array.shape[-1] / 30.0) clip.preview(fps=30) #_ = raw_input("quit...") finally: import pygame.display pygame.display.quit()
def ani_gen(self, path, title="", cmap='binary', duration=3e2): bset.clear() fig, ax = plt.subplots(1, figsize=(4, 4), facecolor=(1, 1, 1)) def make_frame(t): ax.clear() ax.axis('off') ax.set_title(title, fontsize=16) self.step() self.plot(ax, cmap) return (mplfig_to_npimage(fig)) ani = VideoClip(make_frame, duration=duration) ani.write_videofile(path, fps=50) return