def create_video(self, effect): image = ImageClip(self.files['png_' + effect]) if effect == 'nightcore': sound = AudioFileClip(self.files['wav_speed']) if effect == 'chipmunks': sound = AudioFileClip(self.files['wav_pitch_up']) if effect == 'male': sound = AudioFileClip(self.files['wav_pitch_down']) if sound.duration > 600 or sound.duration < 60: return 'audio too short or too long' if effect == 'nightcore': image_pub = ImageClip('resources/backgrounds/nightcorizer.png') image_pub = image_pub.set_duration(20) image = image.set_duration(sound.duration - 20) final_video = concatenate_videoclips([image, image_pub], method="compose") else: image = image.set_duration(sound.duration) final_video = concatenate_videoclips([image], method="compose") final_video = final_video.set_audio(sound) final_video.write_videofile(self.create_file('_' + effect + '.mp4'), fps=20, preset='ultrafast', threads=4, progress_bar=False, verbose=False) self.files['mp4_' + effect] = self.create_file('_' + effect + '.mp4')
def create_photo_quality_video(request): #load images image1 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))) image2 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))) image3 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))) image4 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))) image5 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))) image6 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))) image7 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))) image8 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))) image9 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))) image10 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))) #concatenate clips, play one clip after the other image_clips = concatenate_videoclips([image3.set_duration(2.5), image4.set_duration(2.5), image5.set_duration(2.5), image6.set_duration(2.5), image7.set_duration(2.5), image8.set_duration(2.5)]) title_image_clips = concatenate_videoclips([image1.set_duration(2.5), image2.set_duration(2.5)]) txt_title = (TextClip("Just Back From...Santiago, Chile", fontsize=80, font="Century-Schoolbook-Roman", color="white") .margin(top=5, opacity=0) .set_duration(5) .set_position(("center", "top"))) title_clip = (CompositeVideoClip([title_image_clips, txt_title]) .fadein(0.5).fadeout(0.5)) stats_image_clips = concatenate_videoclips([image9.set_duration(2.5), image10.set_duration(2.5)]) txt_stats = (TextClip("See Santi's recent trip of 1,836 round trip miles, \n with stops..", fontsize=80, font="Century-Schoolbook-Roman", color="white") .margin(top=5, opacity=0) .set_duration(5) .set_position(("center", "top"))) stats_clip = (CompositeVideoClip([stats_image_clips, txt_stats]) .fadein(.5).fadeout(.5)) final_clip = concatenate_videoclips([title_clip, image_clips, stats_clip], method="compose") audio_clip = AudioFileClip("media/music.aac").subclip(0, final_clip.duration) final_clip = final_clip.set_audio(audio_clip).afx(afx.audio_fadeout, 1.0) final_clip.write_videofile('videos/randomBoastablepicsVideo.mp4', fps=23, codec='libx264', audio_bitrate='1000k', bitrate='4000k') html = "<html><body><div>Video successfully created<div><a href='http://localhost:8000'><button>Back</button></a></body></html>" return HttpResponse(html)
def composite_clips(self, clips: dict): try: watermark = ImageClip(self.overlay).set_position((0.7, 0.1), relative=True) except FileNotFoundError: logging.warning( "No watermark found -> video will be created without watermark" ) watermark = None # Requires metadata about the clip txts = self.generate_clip_text(self.metadata) composite_clips = {} for clip_id, clip in clips.items(): composition = [] duration = clip.duration composition.append(clip) if watermark: composition.append(watermark.set_duration(duration)) composition.append(txts[clip_id].set_duration(duration)) composite_clips[clip_id] = CompositeVideoClip(composition, size=self.target_res) return composite_clips
def create_thumbnail(self, clip: Clip): logging.info("Creating yt thumbnail") thumbnail_base = self.get_thumbnail_base(clip) emoji = self.get_emoji() overlay = ImageClip(os.path.join(self.asset_path, "overlay_thumbnail.png")).set_opacity(0.8) number = self.get_number_textclip() try: logo = ( ImageClip(os.path.join(self.asset_path, utils.get_valid_game_name(self.game), "game_logo.png")) .fx(resize, 1.3) .set_position((0.04, 0.6), relative=True) ) except FileNotFoundError: logging.warning("No game_logo in associated asset folder -> thumbnail will be created without logo") logo = None thumbnail = [ thumbnail_base.set_duration(None), emoji.set_duration(None), overlay.set_duration(None), number.set_duration(None), ] if logo: thumbnail.append(logo.set_duration(None)) thumbnail_result = CompositeVideoClip(thumbnail, size=[1280, 720]) thumbnail_result.save_frame(os.path.join(self.compilation_dir, "thumbnail.png"), t=0, withmask=True)
def outro(): outroimg = pathlib.Path(RESOURCES + "/images/outputMoment.jpg") audio = AudioFileClip(pathlib.Path(RESOURCES + "/sounds/outroaud.wav")) music = AudioFileClip(pathlib.Path(RESOURCES + "/sounds/jazz_lounge.mp3")) final_audio = CompositeAudioClip([audio, music]) outro = ImageClip(outroimg) outro = outro.set_fps(24) outro = outro.set_audio(final_audio) outro = outro.set_duration(30) outro.write_videofile(pathlib.Path(RESOURCES + "/vids/outro.mp4"))
def water_mark(request): files = request.FILES vdo = VideoFileClip(files.get('vdo').temporary_file_path()) logo = ImageClip(files.get('logo').temporary_file_path()) wm = (logo.set_duration(vdo.duration) .resize(height=50) # if you need to resize... .margin(right=8, bottom=8, opacity=0) # (optional) logo-border padding .set_pos(("right","bottom"))) CompositeVideoClip([vdo, wm]).write_videofile('media/res.mp4') return JsonResponse({'video':'http://127.0.0.1:8000/media/res.mp4'})
def main(argv): inputFolder = None outputFolder = None videoFile = None videoEndFile = None imageFile = None imageEndFile = None imageTime = 3 cutFromBegining = 0 cutFromEnd = 0 codec = None fixedLength = None watermarkImage = None watermarkWidth = 100 watermarkDuration = None fadeDuration = 1 blackTop = 0 blackBottom = 0 cutUnitsPx = True cutUnitsStartPx = True cutUnitsEndPx = True watermarkX = "right" watermarkY = "top" watermarkStarts = None codecSuffix = None params = None resizeWithIntro = False resizeWithOutro = False mirrorVideo = False rotateVideo = None print_short_licence() try: opts, args = getopt.getopt(argv, "humf:v:i:t:s:e:o:c:l:w:r:", [ "help", "folder=", "output=", "video=", "video-end=", "image=", "image-end=", "image-time=", "cut-start=", "cut-end=", "licence", "watermark=", "black-top=", "black-bottom=", "cut-percent", "watermark-width=", "cut-percent-start", "cut-percent-end", "watermark-to-left", "watermark-to-bottom", "watermark-to-center", "watermark-duration=", "watermark-fade-duration=", "watermark-show-at=", "copy-codec=", "ffmpeg=", "suffix=", "resize-by-intro", "resize-by-outro", "mirror", "rotate=" ]) except getopt.GetoptError: print_help() sys.exit(2) for opt, arg in opts: if opt == '-h': print_help() sys.exit() if opt == '--licence': print_licence() sys.exit() elif opt in ("-f", "--folder"): inputFolder = arg elif opt in ("-o", "--output"): outputFolder = arg elif opt in ("-v", "--video"): videoFile = arg elif opt in ("-s", "--cut-start"): cutFromBegining = max(0, int(arg)) elif opt in ("-e", "--cut-end"): cutFromEnd = max(0, int(arg)) elif opt in ("-t", "--image-time"): imageTime = max(1, int(arg)) elif opt in ("-i", "--image"): imageFile = arg elif opt in ("--image-end"): imageEndFile = arg elif opt in ("--video-end"): videoEndFile = arg elif opt in ("-c"): codec = arg elif opt in ("-l"): fixedLength = int(arg) elif opt in ("-w", "--watermark"): watermarkImage = arg elif opt in ("--watermark-to-left"): watermarkX = "left" elif opt in ("--watermark-to-center"): watermarkX = "center" watermarkY = "center" elif opt in ("--watermark-to-bottom"): watermarkY = "bottom" elif opt in ("--watermark-duration"): watermarkDuration = int(arg) elif opt in ("--watermark-fade-duration"): fadeDuration = int(arg) elif opt in ("--watermark-show-at"): watermarkStarts = [int(a) for a in arg.split(',')] elif opt in ("--black-top"): blackTop = int(arg) elif opt in ("--black-bottom"): blackBottom = int(arg) elif opt in ("-u", "--cut-percent"): cutUnitsPx = False elif opt in ("--watermark-width"): watermarkWidth = max(0, int(arg)) elif opt in ("--cut-percent-start"): cutUnitsStartPx = False elif opt in ("--cut-percent-end"): cutUnitsEndPx = False elif opt in ("--copy-codec"): codec = 'copy' codecSuffix = arg elif opt in ("--suffix"): codecSuffix = arg elif opt in ("--ffmpeg"): params = arg.split(' ') elif opt in ("--resize-by-intro"): resizeWithIntro = True elif opt in ("--resize-by-outro"): resizeWithOutro = True elif opt in ("-m", "--mirror"): mirrorVideo = True elif opt in ("-r", "--rotate"): rotateVideo = int(arg) fileList = [] ffvideoFile = None ffvideoEndFile = None ffimageFile = None ffimageEndFile = None ffwatermark = None if not outputFolder: print( 'Output folder is not found, use -h or --help to show help message.' ) sys.exit(2) if not os.path.isdir(outputFolder): os.makedirs(outputFolder) if (videoFile and not os.path.isfile(videoFile)) or ( videoEndFile and not os.path.isfile(videoEndFile)): print( 'Input video file does not exists, use -h or --help to show help message.' ) sys.exit(2) if (imageFile and not os.path.isfile(imageFile)) or ( imageEndFile and not os.path.isfile(imageEndFile)): print( 'Input image file does not exists, use -h or --help to show help message.' ) sys.exit(2) if (watermarkImage and not os.path.isfile(watermarkImage)): print( 'Input watermark image does not exists, use -h or --help to show help message.' ) sys.exit(2) if codec is not None and not codecs.has_key(codec): print('Unknown codec, use -h or --help to show help message.') sys.exit(2) elif codec is not None and codecSuffix is None: codecSuffix = codecs[codec] if resizeWithIntro and not videoFile: print( 'No intro for resize found, use -h or --help to show help message.' ) sys.exit(2) if resizeWithIntro and not videoEndFile: print( 'No outro for resize found, use -h or --help to show help message.' ) sys.exit(2) if (videoFile): ffvideoFile = VideoFileClip(videoFile) if (videoEndFile): ffvideoEndFile = VideoFileClip(videoEndFile) if (imageFile): ffimageFile = ImageClip(imageFile, duration=imageTime) if (imageEndFile): ffimageEndFile = ImageClip(imageEndFile, duration=imageTime) if (watermarkImage): ffwatermark = ImageClip(watermarkImage) try: fileList = os.listdir(inputFolder) except: print('Input folder not found, use -h or --help to show help message.') sys.exit(2) for filename in fileList: try: if (os.path.isfile(os.path.join(inputFolder, filename))): video = VideoFileClip(os.path.join(inputFolder, filename)) if (resizeWithIntro and ffvideoFile): video = video.resize(ffvideoFile.size) if (resizeWithOutro and ffvideoEndFile): video = video.resize(ffvideoEndFile.size) beginingCut = cutFromBegining endingCut = -cutFromEnd if cutFromEnd > 0 else None if (not cutUnitsPx or not cutUnitsStartPx): beginingCut = (cutFromBegining * video.duration) / 100 if (not cutUnitsPx or not cutUnitsEndPx): endingCut = -(cutFromEnd * video.duration ) / 100 if cutFromEnd > 0 else None video = video.subclip(beginingCut, endingCut) width, height = video.size if (mirrorVideo): video = video.fx(vfx.mirror_x) if (rotateVideo is not None): video = video.rotate(rotateVideo) # video = (video # # .fx(vfx.mirror_x) # # .rotate(1) # # .fx(vfx.colorx, factor=1.4) # # .fx(vfx.painting, saturation=1.6, black=0.01) # ) if (fixedLength is not None): video = video.subclip(0, fixedLength) if (blackTop > 0): blackHeight = (blackTop * height) / 100 def top_filter(frame): frame[0:blackHeight, 0:width] = 0 return frame video = video.fl_image(top_filter) if (blackBottom > 0): blackHeight = (blackBottom * height) / 100 def bottom_filter(frame): frame[(height - blackHeight):height, 0:width] = 0 return frame video = video.fl_image(bottom_filter) if (ffwatermark is not None): wWidth = (watermarkWidth * width) / 100 duration = (watermarkDuration if watermarkDuration is not None else video.duration) logo = (ffwatermark.set_duration(duration).margin( left=0, right=0, bottom=0, top=0, opacity=0.6).resize(width=wWidth).set_pos( (watermarkX, watermarkY)).crossfadein( fadeDuration).crossfadeout(fadeDuration)) if (watermarkStarts is None): video = CompositeVideoClip([video, logo]) else: logos = [] for w in watermarkStarts: w_start = int(w * video.duration / 100) logos.append( logo.set_start(w_start).set_duration( min(video.duration - w_start, duration))) video = CompositeVideoClip([video] + logos) videos = [] if (ffvideoFile): videos.append(ffvideoFile.resize(video.size)) if (ffimageFile): videos.append(ffimageFile.resize(video.size)) videos.append(video) if (ffvideoEndFile): videos.append(ffvideoEndFile.resize(video.size)) if (ffimageEndFile): videos.append(ffimageEndFile.resize(video.size)) result = concatenate_videoclips(videos) translated_filename = filename if codecSuffix is None else os.path.splitext( filename)[0] + "." + codecSuffix result.write_videofile(os.path.join(outputFolder, translated_filename), codec=codec, ffmpeg_params=params) except Exception as e: print('Error while transfering file: ', filename) print('Original Error: ', str(e))
def create_overall_quality_video(request): trip_stats = process_user_stats() #load images image1 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image2 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image3 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image4 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image5 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image6 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image7 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image8 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image9 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') image10 = ImageClip("media/real pics/"+random.choice(os.listdir("media/real pics/"))).set_pos('center') #calculate max width and height images = [] images.extend([image1, image2, image3, image4, image5, image6, image7, image8, image9, image10]) max_width = 0 max_height = 0 for img in images: if img.size[0] > max_width: max_width = img.size[0] if img.size[1] > max_height: max_height = img.size[1] #create blurred images image1 = CompositeVideoClip([image1.resize((max_width, max_height)).fl_image(blur), image1.resize(.95)]) image2 = CompositeVideoClip([image2.resize((max_width, max_height)).fl_image(blur), image2.resize(.95)]) image3 = CompositeVideoClip([image3.resize((max_width, max_height)).fl_image(blur), image3.resize(.95)]) image4 = CompositeVideoClip([image4.resize((max_width, max_height)).fl_image(blur), image4.resize(.95)]) image5 = CompositeVideoClip([image5.resize((max_width, max_height)).fl_image(blur), image5.resize(.95)]) image6 = CompositeVideoClip([image6.resize((max_width, max_height)).fl_image(blur), image6.resize(.95)]) image7 = CompositeVideoClip([image7.resize((max_width, max_height)).fl_image(blur), image7.resize(.95)]) image8 = CompositeVideoClip([image8.resize((max_width, max_height)).fl_image(blur), image8.resize(.95)]) image9 = CompositeVideoClip([image9.resize((max_width, max_height)).fl_image(blur), image9.resize(.95)]) image10 = CompositeVideoClip([image10.resize((max_width, max_height)).fl_image(blur), image10.resize(.95)]) #concatenate clips, play one clip after the other image_clips = concatenate_videoclips([image1.set_duration(2).fadein(.5).fadeout(.5), image2.set_duration(2).fadein(.5).fadeout(.5), image3.set_duration(2).fadein(.5).fadeout(.5), image4.set_duration(2).fadein(.5).fadeout(.5), image5.set_duration(2).fadein(.5).fadeout(.5), image6.set_duration(2).fadein(.5).fadeout(.5), image7.set_duration(2).fadein(.5).fadeout(.5), image8.set_duration(2).fadein(.5).fadeout(.5), image9.set_duration(2).fadein(.5).fadeout(.5), image10.set_duration(2).fadein(.5).fadeout(.5)]) title_clip = (TextClip("Just Back From...", fontsize=35, font="Century-Schoolbook-Roman", color="white", kerning=-2, interline=-1, bg_color='#e04400', method='caption', align='center', size=(max_width, max_height)) .margin(top=5, opacity=0) .set_duration(3).fadein(.5).fadeout(.5) .set_position(("center", "top"))) stats_clip = (TextClip("See Santi's recent trip of 1,836 round trip miles, with stops..", fontsize=35, font="Century-Schoolbook-Roman", color="white", kerning=-2, interline=-1, bg_color='#e04400', method='caption', align='center', size=(max_width, max_height)) .margin(top=5, opacity=0) .set_duration(4).fadein(.5).fadeout(.5) .set_position(("center", "top"))) final_clip = concatenate_videoclips([title_clip, image_clips, stats_clip], method="compose", padding=-1) audio_clip = AudioFileClip("media/music.aac").subclip(0, final_clip.duration) final_clip = final_clip.set_audio(audio_clip).afx(afx.audio_fadeout, 1.5) #write_videofile -> preset : #Sets the time that FFMPEG will spend optimizing the compression. # Choices are: ultrafast, superfast, fast, medium, slow, superslow. # Note that this does not impact the quality of the video, only the size of the video file. # So choose ultrafast when you are in a hurry and file size does not matter. final_clip.write_videofile('videos/overallQualityVideo.mp4', fps=23, codec='libx264', audio_bitrate='1000k', bitrate='4000k') #final_clip.write_gif('videos/overallQuality.gif', fps=23) html = "<html><body><div>Video successfully created<div><a href='http://localhost:8000'><button>Back</button></a></body></html>" return HttpResponse(html)
variations = OrderedDict() for p in permutations((0, 1, 2, 3, 4)): out = [] for elem in p: if len(out) == 0: out = chunks[elem].copy() else: out = concatenate((out, chunks[elem].copy())) variations[str(p)] = out.copy() cnt = 0 for p in variations.keys()[:]: cnt += 1 print cnt, p = str(p) # title clip title_clip = TextClip(p, color='white', fontsize=30).set_pos('center').set_duration(2) clips.append(CompositeVideoClip([title_clip], size=screensize)) # generate output files display_audio_clip(variations[p], sample_freq, p) wavfile.write('sound.wav', sample_freq, variations[p].astype(int16)) # load them with MoviePy aud_clip = AudioFileClip('sound.wav', fps=sample_freq) im_clip = ImageClip("tmp.png") im_clip = im_clip.set_audio(aud_clip) im_clip = im_clip.set_duration(aud_clip.duration) clips.append(CompositeVideoClip([im_clip], size=screensize)) video = concat_clips(clips) video.to_videofile("SamsungVariations.avi", codec='mpeg4')
fntbd = ImageFont.truetype("calibrib.ttf", 40) y = videoHeight*(0.6) lines = textwrap.wrap(videoAuthor,width=25) authorspace=0 for line in lines: lw, lh = fntbd.getsize(line) x = (videoWidth)/25 + (videoWidth - lw)/2 - 7*(videoWidth)/25 drawHandler.text( (x ,y) , line, fill="white", font=fntbd,anchor=None,spacing=4, align="center") y += (1.05)*lh authorspace += lh # setting video Affiliation to it's place fntbd = ImageFont.truetype("calibrib.ttf", 35) y = videoHeight*(0.6) + (1.5)*authorspace lines = textwrap.wrap(videoAffiliation,width=35) for line in lines: lw, lh = fntbd.getsize(line) x = (videoWidth)/25 + (videoWidth - lw)/2 - 7*(videoWidth)/25 drawHandler.text( (x ,y) , line, fill="white", font=fntbd,anchor=None,spacing=4, align="center") y += (1.05)*lh coverImage.save(COVER_SLIDE_FOLDER + "coverSlide" + str(videoID) + ".png", "PNG") # Video Concatenation with formed slide compositeVideo = CompositeVideoClip([mainVideo]) coverSlide = ImageClip(COVER_SLIDE_FOLDER + "coverSlide" + str(videoID) + ".png") coverSlide = coverSlide.set_duration(COVER_DURATION) finalVideo = concatenate_videoclips([coverSlide, compositeVideo, coverSlide]) finalVideo.write_videofile(PROCESSED_VIDEO_FOLDER + str(videoID) + ".mp4")