def test_issue_407(): red = ColorClip((800, 600), color=(255, 0, 0)).set_duration(5) red.fps = 30 assert red.fps == 30 assert red.w == 800 assert red.h == 600 assert red.size == (800, 600) # ColorClip has no fps attribute. green = ColorClip((640, 480), color=(0, 255, 0)).set_duration(2) blue = ColorClip((640, 480), color=(0, 0, 255)).set_duration(2) assert green.w == blue.w == 640 assert green.h == blue.h == 480 assert green.size == blue.size == (640, 480) with pytest.raises(AttributeError): green.fps with pytest.raises(AttributeError): blue.fps video = concatenate_videoclips([red, green, blue]) assert video.fps == red.fps
def test_issue_547(): red = ColorClip((640, 480), color=(255, 0, 0)).set_duration(1) green = ColorClip((640, 480), color=(0, 255, 0)).set_duration(2) blue = ColorClip((640, 480), color=(0, 0, 255)).set_duration(3) video = concatenate_videoclips([red, green, blue], method="compose") assert video.duration == 6 assert video.mask.duration == 6 video = concatenate_videoclips([red, green, blue]) assert video.duration == 6
def test_clips_array(): red = ColorClip((1024, 800), color=(255, 0, 0)) green = ColorClip((1024, 800), color=(0, 255, 0)) blue = ColorClip((1024, 800), color=(0, 0, 255)) video = clips_array([[red, green, blue]]) with pytest.raises(ValueError) as exc_info: video.resize(width=480).write_videofile(join(TMP_DIR, "test_clips_array.mp4")) assert str(exc_info.value) == "Attribute 'duration' not set" close_all_clips(locals())
def make_zoom(scale_func, path=im_path, cx=32, cy=32, scale=10, duration=5, fps=10, oversample=2.0): ic = ImageClip(path).resize(oversample) bg = ColorClip((ic.w, ic.h), (0xFF, 0xFF, 0xFF)).set_duration(duration) ic.duration = duration cx *= oversample cy *= oversample total_frames = int(duration * fps) def zoom_between_frames(startf, endf): scales = [ scale_func(startf + f * (endf - startf) / total_frames) for f in range(total_frames) ] return make_zoom_movie(ic, scales, fps, (cx, cy)) # we seem to get two multiple frames at the start... # and end sometimes ret = CompositeVideoClip([ bg, zoom_between_frames(total_frames, 2.0 * total_frames), zoom_between_frames(0, total_frames) ]) ret.size = ic.size # ret.duration = duration return ret.resize(1.0 / oversample)
def generate(self, avatars, text, usernames, kwargs): name = uuid.uuid4().hex + '.mp4' if len(text) >= 400: text = text[:400] + '...' @after_this_request def remove(response): # pylint: disable=W0612 try: os.remove(name) except (FileNotFoundError, OSError, PermissionError): pass return response clip = VideoFileClip("assets/letmein/letmein.mp4") textclip = TextClip(txt=text, bg_color='White', fontsize=32, font='Verdana', method='caption', align='west', size=(clip.size[0], None)).set_duration(clip.duration) color = ColorClip((clip.size[0], textclip.size[1]), color=(255, 255, 255), ismask=False).set_duration(clip.duration) video = CompositeVideoClip([clip.set_position(("center", textclip.size[1])), color, textclip], size=(clip.size[0], textclip.size[1] + clip.size[1])) video.write_videofile(name, threads=4, preset='superfast', verbose=False) clip.close() video.close() return send_file(name, mimetype='video/mp4')
def main(url, output): driver = webdriver.Chrome() remote_url = url driver.get(remote_url) png = chrome_takeFullScreenshot(driver) with open("website_image.png", 'wb') as f: f.write(png) driver.close() clip = ImageClip('website_image.png') video_width = int(clip.size[0] + 800) video_height = int(video_width/1.5) bg_clip = ColorClip(size=(video_width, video_height), color=[228, 220, 220]) scroll_speed = 180 total_duration = (clip.h - 800)/scroll_speed fl = lambda gf,t : gf(t)[int(scroll_speed*t):int(scroll_speed*t)+800,:] clip = clip.fl(fl, apply_to=['mask']) video = CompositeVideoClip([bg_clip, clip.set_pos("center")]) video.duration = total_duration if not output.endswith('.mp4'): output += '.mp4' video.write_videofile(output, fps=26) os.remove('website_image.png')
def make(self): videos = [] for notes in self.sheet.lines: clips = [] for note in notes: if note[0] == 'rest': img = ColorClip((720, 404), (0, 0, 0), duration=note[1] / 1000) clips.append(img) continue target_video = self.get_video(note[0], note[1], note[2]) clips.append(target_video) video = concatenate_videoclips(clips).margin(10) videos.append(video) num_of_lines = len(self.sheet.lines) if num_of_lines == 1: result = videos[0] elif num_of_lines == 2: result = clips_array([[videos[0]], [videos[1]]]) elif num_of_lines == 4: result = clips_array([[videos[0], videos[1]], [videos[2], videos[3]]]) else: print("Num of lines should be 1, 2, or 4") exit(1) self.result = './result/' + self.name + '.mp4' result.write_videofile(self.result)
def _create_green_exp_canvas(self, margin=0): """ A green helper canvas to mark the position of robot expression. """ h, w, _ = self.exp_assets['null'].get_frame(0).shape h += margin * 2 w += margin * 2 self.exp_canvas = ColorClip(size=(w, h), color=[0, 255, 0])
def test_clips_array_duration(): # NOTE: anyone knows what behaviour this sets ? If yes please replace # this comment. red = ColorClip((256, 200), color=(255, 0, 0)) green = ColorClip((256, 200), color=(0, 255, 0)) blue = ColorClip((256, 200), color=(0, 0, 255)) video = clips_array([[red, green, blue]]).set_duration(5) with pytest.raises(AttributeError) as exc_info: video.write_videofile(join(TMP_DIR, "test_clips_array.mp4")) assert "No 'fps'" in str(exc_info.value) # this one should work correctly red.fps = green.fps = blue.fps = 30 video = clips_array([[red, green, blue]]).set_duration(5) video.write_videofile(join(TMP_DIR, "test_clips_array.mp4")) close_all_clips(locals())
def process_clip(): clip = VideoFileClip(file_path, target_resolution=[720, 1280]) # I WAS going to get the last 10 seconds but nvm if clip.duration > 10: clip = clip.subclip(0, -clip.duration + 10) safe_duration = max(0, clip.duration - 0.1) # Startup startup_sound = AudioFileClip( "assets/tobecontinued/roundabout_start.mp3") startup = ColorClip([1, 1], color=0)\ .set_opacity(0)\ .set_duration(startup_sound.duration).set_audio(startup_sound) if startup_sound.duration > clip.duration: startup = startup.subclip( startup_sound.duration - clip.duration, startup_sound.duration) else: startup = startup.fx(vfx.freeze, freeze_duration=clip.duration - startup_sound.duration) startup_compos = CompositeVideoClip([clip, startup]) # Freeze fram stuff freeze_frame_sound = AudioFileClip( "assets/tobecontinued/roundabout.mp3") freeze_frame = ImageClip(clip.get_frame(safe_duration))\ .fx(vfx.blackwhite).set_duration(freeze_frame_sound.duration) arrow = ImageClip("assets/tobecontinued/arrow.png")\ .set_pos( lambda t: (min(529, int((1400*t)-400)), 550) ) freeze_compos = CompositeVideoClip([freeze_frame, arrow])\ .set_duration(freeze_frame_sound.duration).set_audio(freeze_frame_sound) # Final clip final_clip = concatenate_videoclips( [startup_compos, freeze_compos]) return final_clip, [ clip, freeze_frame_sound, freeze_frame, arrow, freeze_compos, startup, startup_sound, startup_compos ]
def write_video(out_path, audio_clip, lyric_clips): [print(c.duration) for c in lyric_clips] print(audio_clip.duration) full_text_clip = concatenate_videoclips(lyric_clips) video = CompositeVideoClip(clips=[ ColorClip(size=VIDEO_SIZE, color=BACKGROUND_COLOR, duration=audio_clip.duration), full_text_clip, ], ) video.fps = 24 video.audio = audio_clip video.write_videofile(out_path)
def make_video(video_paths): """ Makes videos """ videos = [] for path in video_paths: video = audio_fadein( audio_fadeout( fadein( fadeout( VideoFileClip(path, target_resolution=(1080, 1920)), 1), 1), 1), 1) videos.append(video) black_image = ColorClip((1920, 1080), color=[0, 0, 0], duration=0.5) result_clip = concat(videos, transition=black_image, method="compose") result_clip.write_videofile("result.mp4", fps=60, preset="ultrafast")
PEP-0008, with exceptions made for the purposes of improving book formatting. Example code is provided "as is". Permissions ============ In general, you may use the code we've provided with this book in your programs . You do not need to contact us for permission unless you're reproducing a significant portion of the code and using it in educational distributions. Examples: * Writing an education program or book that uses several chunks of code from this course requires permission. * Selling or distributing a digital package from material taken from this book does require permission. * Answering a question by citing this book and quoting example code does not require permission. Attributions usually include the title, author, publisher and an ISBN. For example, "Practical Python Projects, by Yasoob Khalid. Copyright 2020 Yasoob." If you feel your use of code examples falls outside fair use of the permission given here, please contact me at [email protected]. """ from moviepy.editor import ImageClip, ColorClip, CompositeVideoClip clip = ImageClip('website_image.png') bg_clip = ColorClip(size=(1600, 1000), color=[228, 220, 220]) scroll_speed = 180 total_duration = (clip.h - 800) / scroll_speed fl = lambda gf, t: gf(t)[int(scroll_speed * t):int(scroll_speed * t) + 800, :] clip = clip.fl(fl, apply_to=['mask']) video = CompositeVideoClip([bg_clip, clip.set_pos("center")]) video.duration = total_duration video.write_videofile("movie.mp4", fps=26)
def test_issue_416(): # ColorClip has no fps attribute. green = ColorClip((640, 480), color=(0, 255, 0)).set_duration(2) video1 = concatenate_videoclips([green]) assert video1.fps is None
def test_issue_359(): with ColorClip((800, 600), color=(255, 0, 0)).set_duration(5) as video: video.fps = 30 video.write_gif(filename=os.path.join(TMP_DIR, "issue_359.gif"), tempfiles=True)
def test_issue_145(): video = ColorClip((800, 600), color=(255, 0, 0)).set_duration(5) with pytest.raises(Exception): concatenate_videoclips([video], method="composite")
def generate_video_matrix(vid_files, titles=None, out_file=None, columns=None, fps=None, crop_rect=None): os.environ["IMAGEMAGICK_BINARY"] = glob.glob( r"C:\Program Files\ImageMagick-*\magick.exe")[0] try: import moviepy except: subprocess.call("pip install moviepy") from moviepy.editor import VideoFileClip, TextClip, ColorClip, clips_array, vfx import numpy as np from moviepy.video.fx.all import crop if out_file is None: out_file = "combined.mp4" if type(vid_files[0]) == str: vid_clips = [ VideoFileClip(x, resize_algorithm="fast_bilinear") for x in vid_files ] else: vid_clips = vid_files max_h = np.max([x.h for x in vid_clips]) vid_clips = [x.fx(vfx.resize, max_h / x.h) for x in vid_clips] if crop_rect: vid_clips = [ crop( x, x1=crop_rect[0], y1=crop_rect[1], width=crop_rect[2], height=crop_rect[3], ) for x in vid_clips ] vid_clips = [v.margin(2) for v in vid_clips] min_duration = np.min([v.duration for v in vid_clips]) print("Set duration to min of all videos: %i" % min_duration) vid_clips = [v.set_duration(min_duration) for v in vid_clips] def create_text_clip(text, dura): global src return TextClip(text, font="Verdana", fontsize=max_h / 20, color="white").set_duration(dura) if titles is None: titles = [os.path.splitext(os.path.basename(x))[0] for x in vid_files] text_clips = [create_text_clip(x, min_duration) for x in titles] arr = [] if columns is not None: for i in range(0, len(vid_clips), columns): arr.append(vid_clips[i:i + columns]) arr.append(text_clips[i:i + columns]) remainder = len(vid_clips) % columns if remainder != 0: remainder = columns - remainder blank_clip = ColorClip((1, 1), color=(0, 0, 0), duration=0) arr[-1].extend([blank_clip] * remainder) arr[-2].extend([blank_clip] * remainder) else: arr.append(vid_clips) arr.append(text_clips) final = clips_array(arr) final.write_videofile(out_file, fps=fps)