def render(): if img1 is None: alert = QMessageBox() alert.setText('64비트 이미지를 선택해주세요.') alert.exec_() return if not pixelized: alert = QMessageBox() alert.setText('픽셀화를 해주세요.') alert.exec_() return if img2 is None: alert = QMessageBox() alert.setText('128비트 이미지를 선택해주세요.') alert.exec_() return image = Image.open(img2) resize(image).save('./resource/128bit.png') clips = [ImageClip(f'./resource/{m}').set_duration(1) for m in ['1bit.png', '2bit.png', '4bit.png', '8bit.png']] clips.append(ImageClip('./resource/16bit.png').set_duration(1.6)) clips.append(ImageClip('./resource/32bit.png').set_duration(1.8)) clips.append(ImageClip('./resource/64bit.png').set_duration(2)) clips.append(ImageClip('./resource/128bit.png').set_duration(1)) concat_clip = concatenate_videoclips(clips, method="compose") concat_clip.audio = AudioFileClip(r"./resource/audio.mp3") concat_clip.write_videofile("result.mp4", fps=24) alert = QMessageBox() alert.setText('렌더링 완료 result.mp4가 생성되었습니다.') alert.exec_()
def load_clip(index): image = self.sequence[index] text = titles[index] if text.startswith("W:"): text = text[2:] show_full_height = True else: show_full_height = False if height is None and width is None: clip = ImageClip(image, duration=image_duration) else: if zoom_images: clip = ImageClip(image, duration=image_duration) \ .fx(image_effect, screensize=(width, height), \ duration=20, show_full_height=show_full_height) elif show_full_height: clip = ImageClip(image, duration=image_duration) \ .fx(resize, height=height).set_position('center', 'center') clip = CompositeVideoClip([clip], size=(width, height)) else: clip = ImageClip(image, duration=image_duration) \ .fx(resize, height=height, width=width) #Adds text label etc. on clip clip = make_clip(clip, text, height, width, font, font_color, fontsize) return clip
def test_issue_285(): clip_1, clip_2, clip_3 = ( ImageClip("media/python_logo.png", duration=10), ImageClip("media/python_logo.png", duration=10), ImageClip("media/python_logo.png", duration=10), ) merged_clip = concatenate_videoclips([clip_1, clip_2, clip_3]) assert merged_clip.duration == 30
def find_objects(clip, size_threshold=500, preview=False): """ Returns a list of ImageClips representing each a separate object on the screen. size_threshold : all objects found with size < size_threshold will be considered false positives and will be removed """ image = clip.get_frame(0) if not clip.mask: clip = clip.add_mask() mask = clip.mask.get_frame(0) labelled, num_features = ndi.measurements.label(image[:, :, 0]) # find the objects slices = [] for obj in ndi.find_objects(labelled): if mask[obj[0], obj[1]].mean() <= 0.2: # remove letter holes (in o,e,a, etc.) continue if image[obj[0], obj[1]].size <= size_threshold: # remove very small slices continue slices.append(obj) indexed_slices = sorted(enumerate(slices), key=lambda slice: slice[1][1].start) letters = [] for i, (sy, sx) in indexed_slices: """ crop each letter separately """ sy = slice(sy.start - 1, sy.stop + 1) sx = slice(sx.start - 1, sx.stop + 1) letter = image[sy, sx] labletter = labelled[sy, sx] maskletter = (labletter == (i + 1)) * mask[sy, sx] letter = ImageClip(image[sy, sx]) letter.mask = ImageClip(maskletter, is_mask=True) letter.screenpos = np.array((sx.start, sy.start)) letters.append(letter) if preview: import matplotlib.pyplot as plt print(f"Found {num_features} objects") fig, ax = plt.subplots(2) ax[0].axis("off") ax[0].imshow(labelled) ax[1].imshow([range(num_features)], interpolation="nearest") ax[1].set_yticks([]) plt.show() return letters
def test_exifrotate(): image_file = 'media/balloons_portrait.jpg' with ImageClip(image_file, duration=1) as clip: assert clip.img.meta['EXIF_MAIN']['ExifImageWidth'] == 4032 assert clip.img.meta['EXIF_MAIN']['ExifImageHeight'] == 3024 assert clip.img.meta['EXIF_MAIN']['Orientation'] == 6 assert clip.size == (3024, 4032) with ImageClip(image_file, duration=1, imageio_params={'exifrotate': False}) as clip: assert clip.size == (4032, 3024)
def _make_circle(radius, color=(0, 255, 0)): circle_clip = ImageClip( circle((2 * radius, 2 * radius), (radius, radius), radius, color, (0, 0, 0))) #Make mask from it (channel 1 - green) since it's single color circle_mask = ImageClip(circle((2 * radius, 2 * radius), (radius, radius), radius, 1, 0), ismask=True) #And use it as a mask circle_clip = circle_clip.set_mask(circle_mask) return circle_clip, radius
def _make_round_credits( round_credits: RoundCredits, round_index: int, width: int, height: int, color: str = 'white', stroke_color: str = 'black', stroke_width: str = 2, font: str = 'Impact-Normal', fontsize: int = 60, gap: int = 0 ) -> Clip: texts = [] texts += [["\n", "\n"]] * 16 if round_credits.audio != []: texts += _make_credit_texts( str(round_credits.audio[0]), "ROUND {} MUSIC".format(round_index + 1)) for audio_credit in round_credits.audio[1:]: texts += _make_credit_texts(str(audio_credit)) if round_credits.video != []: texts += _make_credit_texts( str(round_credits.video[0]), "ROUND {} VIDEOS".format(round_index + 1)) for video_credit in round_credits.video[1:]: texts += _make_credit_texts(str(video_credit)) texts += [["\n", "\n"]] * 2 # Make two columns for the credits left, right = ("".join(t) for t in zip(*texts)) left, right = [TextClip(txt, color=color, stroke_color=stroke_color, stroke_width=stroke_width, font=font, fontsize=fontsize, align=al) for txt, al in [(left, 'East'), (right, 'West')]] # Combine the columns cc = CompositeVideoClip([left, right.set_position((left.w + gap, 0))], size=(left.w + right.w + gap, right.h), bg_color=None) scaled = resize(cc, width=width) # Scale to the required size # Transform the whole credit clip into an ImageClip credits_video = ImageClip(scaled.get_frame(0)) mask = ImageClip(scaled.mask.get_frame(0), ismask=True) lines_per_second = height / CREDIT_DISPLAY_TIME def scroll(t): return ("center", -lines_per_second * t) credits_video = credits_video.set_position(scroll) credits_duration = credits_video.h / lines_per_second credits_video = credits_video.set_duration(credits_duration) return credits_video.set_mask(mask)
def findObjects(clip, rem_thr=500, preview=False): """ Returns a list of ImageClips representing each a separate object on the screen. rem_thr : all objects found with size < rem_Thr will be considered false positives and will be removed """ image = clip.get_frame(0) if clip.mask is None: clip = clip.add_mask() mask = clip.mask.get_frame(0) labelled, num_features = ndi.measurements.label(image[:, :, 0]) #find the objects slices = ndi.find_objects(labelled) # cool trick to remove letter holes (in o,e,a, etc.) slices = [e for e in slices if mask[e[0], e[1]].mean() > 0.2] # remove very small slices slices = [e for e in slices if image[e[0], e[1]].size > rem_thr] # Sort the slices from left to right islices = sorted(enumerate(slices), key=lambda s: s[1][1].start) letters = [] for i, (ind, (sy, sx)) in enumerate(islices): """ crop each letter separately """ sy = slice(sy.start - 1, sy.stop + 1) sx = slice(sx.start - 1, sx.stop + 1) letter = image[sy, sx] labletter = labelled[sy, sx] maskletter = (labletter == (ind + 1)) * mask[sy, sx] letter = ImageClip(image[sy, sx]) letter.mask = ImageClip(maskletter, ismask=True) letter.screenpos = np.array((sx.start, sy.start)) letters.append(letter) if preview: import matplotlib.pyplot as plt print("found %d objects" % (num_features)) fig, ax = plt.subplots(2) ax[0].axis('off') ax[0].imshow(labelled) ax[1].imshow([range(num_features)], interpolation='nearest') ax[1].set_yticks([]) plt.show() return letters
def chose2(): print("This takes some time..") time.sleep(2) for (dirpath, dirnames, filenames) in walk(os.getcwd()): files.extend(filenames) break for i in files: if (i[-3:]) == "jpg": images.append(ImageClip(i).resize([640, 1136]).set_duration(3)) if (i[-3:]) == "mp4": videos.append(VideoFileClip(i)) final_clip = concatenate_videoclips(videos + images, method="compose") final_clip.write_videofile("input.mp4") time.sleep(2) stream = os.popen( r'ffmpeg -i input.mp4 -lavfi "[0:v]scale=1920*2:1080*2,boxblur=luma_radius=min(h\,w)/20:luma_power=1:chroma_radius=min(cw\,ch)/20:chroma_power=1[bg];[0:v]scale=-1:1080[ov];[bg][ov]overlay=(W-w)/2:(H-h)/2,crop=w=1920:h=1080" Output.mp4' ) output = stream.read() os.rename(os.getcwd() + r"\input.mp4", os.getcwd() + r"\withBlackBorders.mp4") print("\nFinished! Enjoy Output.mp4")
def test_PR_528(util): with ImageClip("media/vacation_2017.jpg") as clip: new_clip = scroll(clip, w=1000, x_speed=50) new_clip = new_clip.with_duration(0.2) new_clip.fps = 24 new_clip.write_videofile(os.path.join(util.TMP_DIR, "pano.mp4"), logger=None)
def test_afterimage(): ai = ImageClip("media/afterimage.png") masked_clip = mask_color(ai, color=[0, 255, 1]) # for green some_background_clip = ColorClip((800, 600), color=(255, 255, 255)) final_clip = CompositeVideoClip([some_background_clip, masked_clip], use_bgclip=True).with_duration(0.2) final_clip.write_videofile(os.path.join(TMP_DIR, "afterimage.mp4"), fps=30)
def make_clip(self, value, width=None, height=None): """ value to show on gauge Width and height can also be changed since it's SVG """ #calculates to which angle we need to turn cursor based on speed angle = self.map_speed(value) #Turns the cursor. We need to use this instead of rotate function since we need #to forget previous transformations self.cursor.root.set("transform", "rotate(%f %f %f)" % (angle, self.cursor_x, self.cursor_y)) svg_bytestring = self.svg.to_str() png_file = io.BytesIO() if width is not None and height is not None: current_width = float(self.svg.width) current_height = float(self.svg.height) scale = max(height/current_height, width/current_width) cairosvg.svg2png(bytestring=svg_bytestring,write_to=png_file, parent_width=width, parent_height=height, scale=scale) else: #Converts to png and saves to bytestring cairosvg.svg2png(bytestring=svg_bytestring,write_to=png_file) #Reads as numpy image #TODO: does transparency work? return ImageClip(imread(png_file.getvalue()), transparent=self.transparent)
def test_find_objects(filename, expected_screenpos): clip = ImageClip(filename) objects = find_objects(clip) assert len(objects) == len(expected_screenpos) for i, object_ in enumerate(objects): assert np.array_equal(object_.screenpos, np.array(expected_screenpos[i]))
def define_image(op, ext_duration=None): """ Define a static image clip from source file. source - absolute path to the file duration - duration in seconds ext_duration - clip to obtain the duration from Mainly used for intro/outro and static background. """ if ext_duration: # clip = ImageClip(op.source, duration=find_video_period(ext_duration)) clip = ImageClip(op.source, duration=ext_duration.duration) else: clip = ImageClip(op.source, duration=op.duration) return clip
def create_image_clip(image_filename): # having some encoding issues in moviepy if isinstance(image_filename, unicode): image_filename = image_filename.encode(sys.getdefaultencoding()) image_filename = os.path.abspath(image_filename) assert (os.path.exists(image_filename)) return ImageClip(image_filename)
def addlogo(file_dir,img="",time=20,X=30,Y=30): clip = VideoFileClip(file_dir) img_clip = ImageClip(img) #位置 img_clip = img_clip.set_pos((X,Y)).set_duration(time) clip = CompositeVideoClip([clip, img_clip]) filen = os.path.basename(file_dir) clip.write_videofile(work_path+"\\"+filen) clip.close()
def clip_from_path(path): if path == '': return None elif path.suffix.lower() in IMAGE_EXTENSIONS: from moviepy.video.VideoClip import ImageClip return ImageClip(str(path)) else: from moviepy.video.io.VideoFileClip import VideoFileClip return VideoFileClip(str(path))
def generate_intro(): logger.info('Generating intro...') color = (255, 255, 255) size = (1280, 720) clip = ColorClip(size, color, duration=3) logo = ImageClip(config.LOGO_PATH).set_duration(clip.duration) \ .resize(width=400, height=200) \ .set_pos(('center', 'center')) return CompositeVideoClip([clip, logo])
def test_afterimage(): ai = ImageClip("media/afterimage.png") masked_clip = mask_color(ai, color=[0, 255, 1]) # for green some_background_clip = ColorClip((800, 600), color=(255, 255, 255)) final_clip = CompositeVideoClip([some_background_clip, masked_clip], use_bgclip=True) final_clip.duration = 5 final_clip.write_videofile("/tmp/afterimage.mp4", fps=30)
def createVideo(folder, file_movie_name): list_img = [] for img in os.listdir(folder): list_img.append(folder + "/" + img) list_img.sort() clips = [ImageClip(m).set_duration(3) for m in list_img] concat_clip = concatenate_videoclips(clips, method="compose") concat_clip.write_videofile(file_movie_name, fps=24)
def add_pics(self, clip): logger.info('Adding pics...') pic_clip = [clip] for i in range(self.pic_num): x_pos, y_pos, x_size, y_size = self.generate_coordinates(clip) pic_path = config.PIC_PATH + str(i) + '.jpg' pic = ImageClip(pic_path).set_duration(clip.duration).resize((x_size, y_size)) \ .set_pos((x_pos, y_pos)).add_mask().rotate(random.randint(-180, 180)) pic_clip.append(pic) return CompositeVideoClip(pic_clip)
def freeze_at_start(clip, freeze_duration=None, total_duration=None): """ Momentarily freeze the clip on its first frame. With ``duration``you can specify the duration of the freeze. With ``total_duration`` you can specify the total duration of the clip and the freeze (i.e. the duration of the freeze is automatically calculated). If neither is provided, the freeze will have an infinite length. """ freezed_clip = ImageClip(clip.get_frame(0)) if clip.mask: freezed_clip.mask = ImageClip(clip.mask.get_frame(0)) if total_duration: freeze_duration = total_duration - clip.duration if freeze_duration: freezed_clip = freezed_clip.set_duration(freeze_duration) return concatenate([freezed_clip, clip])
def output_mp4(name, data, durations, max_workers=None, method='chain'): # sanity check the images sizes = {frame.shape for frame in data} assert method == 'compose' or len(sizes) == 1, sizes # turn the image into clips clips = [ImageClip(data, duration=d) for (data, d) in zip(data, durations)] # save the mp4 movie = concatenate_videoclips(clips, method=method) movie.write_videofile(str(output_path / (name + '.mp4')), fps=24, threads=max_workers or cpu_count(), bitrate='10M')
def test_issue_782(): clip = ImageClip('flower.png') clip_2 = clip.fx(vfx.mirror_y) if clip.image_transform == clip_2.image_transform: assert False else: pass clip_3 = clip.fx(vfx.mirror_x) if clip.image_transform == clip_3.image_transform: assert False else: assert True
def create_thumbnail(self): logger.info('Creating thumbnail...') color = (255, 255, 255) size = (1280, 720) background = ColorClip(size, color) logo = ImageClip(config.LOGO_PATH).set_duration(1) \ .resize(width=400, height=200) \ .set_pos(('center', 'center')) text = TextClip(txt=str(self.id), size=(500, 500)).set_position( ('center', 'bottom')) CompositeVideoClip([background, logo, text]).save_frame(config.THUMB_PATH) logger.info('Thumbnail saved...')
def clip(self, frames_and_durations): if self.dynamic: clip = super().clip(frames_and_durations) else: clip = ImageClip(imageio.imread( next((output_path / self.dirname).glob('*.png'))), duration=sum(frames_and_durations.values())) if self.margin: params = self.margin.copy() params['mar'] = params.pop('margin') params['color'] = white clip = margin(clip, **params) return clip
def test_afterimage(): with ImageClip("media/afterimage.png") as ai: masked_clip = mask_color(ai, color=[0, 255, 1]) # for green with ColorClip((800, 600), color=(255, 255, 255)) as some_background_clip: with CompositeVideoClip([some_background_clip, masked_clip], use_bgclip=True) as final_clip: final_clip.duration = 5 final_clip.write_videofile(os.path.join( TMP_DIR, "afterimage.mp4"), fps=30)
def _render_clip(self, frames): logger = logging.getLogger('logger') logger.info("Rendering video...") clips = [] clip_duration = 1 / self.frame_rate for frame in frames: clip = ImageClip(frame.img) clip = clip.set_duration(clip_duration) clips.append(clip) final_clip = concatenate_videoclips(clips, method="chain") final_clip = final_clip.set_audio(AudioFileClip(self.audio.path)) final_clip = final_clip.set_fps(self.frame_rate) return final_clip
def test_issue_354(): with ImageClip("media/python_logo.png") as clip: clip.duration = 10 crosstime = 1 # TODO: Should this be removed? # caption = editor.TextClip("test text", font="Liberation-Sans-Bold", # color='white', stroke_color='gray', # stroke_width=2, method='caption', # size=(1280, 720), font_size=60, # align='South-East') # caption.duration = clip.duration fadecaption = clip.fx(crossfadein, crosstime).fx(crossfadeout, crosstime) CompositeVideoClip([clip, fadecaption]).close()
def freeze_at_end(clip, freeze_duration=None, total_duration=None): """ Makes the clip freeze on its last frame. With ``duration`` you can specify the duration of the freeze. With ``total_duration`` you can specify the total duration of the clip and the freeze (i.e. the duration of the freeze is automatically calculated). If neither is provided, the freeze will have an infinite length. """ freezed_clip = ImageClip(clip.get_frame(clip.end)) if total_duration: freeze_duration = total_duration - clip.duration if freeze_duration: freezed_clip = freezed_clip.set_duration(freeze_duration) return CompositeVideoClip([clip,freezed_clip.set_start(clip.end)])