def video_render(txt_file,image_file,sound_file,save_file): from moviepy.editor import ImageClip from moviepy.editor import CompositeVideoClip from moviepy.editor import CompositeAudioClip from moviepy.editor import TextClip from moviepy.editor import AudioFileClip from moviepy.editor import concatenate from moviepy.config import change_settings change_settings({"IMAGEMAGICK_BINARY": "/usr/local/bin/convert"}) text=[] with open(txt_file,'r') as file: for lines in file: if lines!="\n": text.append(lines.rstrip('\n')) durs=[] for i in text: res = len(re.findall(r'\w+', i)) if res/2>3: durs.append(res/2) else: durs.append(3) total_duration=sum(durs) a_clip = AudioFileClip(sound_file) if a_clip.duration<total_duration: new_audioclip = CompositeAudioClip([a_clip, a_clip.set_start(a_clip.duration-1)]).set_duration(total_duration+3) else: new_audioclip=a_clip.set_duration(total_duration+3) screen=(1920,1080) clip_list = [] i=0 for string in text: duration=durs[i] i+=1 try: txt_clip = TextClip(string, fontsize = 70, color = 'white', method='caption',size=screen ).set_duration(duration).set_pos('center') clip_list.append(txt_clip) except UnicodeEncodeError: txt_clip = TextClip("Issue with text", fontsize = 70, color = 'white').set_duration(2) clip_list.append(txt_clip) final_text_clip = concatenate(clip_list, method = "compose").set_start(3) v_clip = ImageClip(image_file).set_duration(total_duration+3) video=CompositeVideoClip([v_clip, final_text_clip]) # video = video.set_audio(AudioFileClip('sound/Serenity (1).mp3')) video = video.set_audio(new_audioclip) video.write_videofile(save_file, codec='libx264', fps=10, threads=4, audio_codec='aac', temp_audiofile='temp-audio.m4a', remove_temp=True )
from moviepy.editor import * from .models import Size, Quality, CaptionPosition, LoopMode, Speed import string from moviepy.config import change_settings # TODO: fix paths change_settings({"IMAGEMAGICK_BINARY": r"D:\imagemagick\convert.exe"}) class VidConvertService: @staticmethod def time_symetrize(clip): """ Returns the clip played forwards then backwards. In case you are wondering, vfx (short for Video FX) is loaded by >>> from moviepy.editor import * """ return concatenate([clip, clip.fx(vfx.time_mirror)]) def get_size(self, size: int): switcher = { Size.original.value: 1, Size.smaller.value: 0.5, Size.bigger.value: 1.5 } return switcher.get(size, 1) def get_fps(self, quality: int): switcher = { Quality.regular.value: 15, Quality.high.value: 30, Quality.low.value: 60 } return switcher.get(quality, 30)
import os, glob, datetime, numpy as np from moviepy.editor import * from PIL import Image, ImageDraw, ImageFont import moviepy.config as mpcf mpcf.change_settings({"FFMPEG_BINARY": "/home/cc/cs198/sp15/staff/cs198-re/opt/local/bin/ffmpeg"}) date = datetime.datetime.now() date_now = date.strftime("%c")[:19] font = ImageFont.truetype('/System/Library/Fonts/Courier.dfont', 25) class AnimatedTextClip(VideoClip): def __init__(self, genfn, size=(0,0)): VideoClip.__init__(self) self.gentext = genfn self.size = size def get_frame(self, t): frame = Image.new('RGB', self.size, (0,0,0)) d = ImageDraw.Draw(frame) header, footer = self.gentext(t) x, y = self.size d.text((10,10), header, font=font, fill=(255,255,255)) d.text((10,y-35), footer, font=font, fill=(255,255,255)) return np.array(frame) def main(): OVERLAY = os.environ["OVERLAY_METADATA"] != "false" filename = os.environ["MAYA_FILE"] camera = os.environ["CAMERA"] shot_name = os.environ["SHOT_NAME"]
#for windows users: install ImageMagic & uncomment lines 2 & 3 from moviepy.config import change_settings change_settings({ "IMAGEMAGICK_BINARY": r"C:\\Program Files\\ImageMagick-7.0.10-Q16-HDRI\magick.exe" }) from moviepy.editor import VideoFileClip, AudioFileClip, concatenate_videoclips, TextClip, CompositeVideoClip, concatenate_audioclips, AudioClip, CompositeAudioClip import os fr = input( "Enter Desired Framerate, leave blank and hit enter for default(24): ") if fr == "": fr = 24 else: fr = int(fr) output_name = input( "Enter Desired Output Name, leave blank and hit enter for default(final_video.mp4): " ) if output_name == "": output_name = "final_video.mp4" video_files = [] #for each video in folder for i in os.listdir(): if i.endswith(".mp4"): video_files.append(i)
while x < img.shape[1]: cv2.line(img, (x, 0), (x, img.shape[0]), color=line_color, lineType=type_, thickness=thickness) x = x + pxstep while y < img.shape[0]: cv2.line(img, (0, y), (img.shape[1], y), color=line_color, lineType=type_, thickness=thickness) y += pxstep now = str(datetime.now()).replace(":","-") print (now) tqdm(disable=True, total=0) # initialise internal lock ####Added to solve %1 change_settings({"FFMPEG_BINARY":"ffmpeg.exe"}) white = "#ffffff" lightBlue2 = "#adc5ed" font = "Constantia" fontButtons = (font, 12) maxWidth = 800 maxHeight = 790 playpause = True file_name = 'None' grids = False s = '' cont = 0 subpathList = []
#!/usr/local/bin/python # depenedancies: # pip install pafy moviepy pyyaml import pafy import moviepy.editor as mp import os import yaml import hashlib import moviepy.config as cf cf.change_settings({"FFMPEG_BINARY": "/usr/local/bin/ffmpeg"}) try: # included in standard lib from Python 2.7 from collections import OrderedDict except ImportError: # try importing the backported drop-in replacement # it's available on PyPI from ordereddict import OrderedDict class OrderedDictYAMLLoader(yaml.Loader): """ A YAML loader that loads mappings into ordered dictionaries. """ def __init__(self, *args, **kwargs): yaml.Loader.__init__(self, *args, **kwargs) self.add_constructor(u'tag:yaml.org,2002:map', type(self).construct_yaml_map) self.add_constructor(u'tag:yaml.org,2002:omap', type(self).construct_yaml_map)
_cached_line_to_tts = None _last_frame_indices: Dict[str, int] = {} VOLUME_DIM = 0.15 FADE_DURATION = 0.2 VIDEO_CROSSFADE_DURATION = FADE_DURATION AUTO_GENERATE_TTS = False FPS = 30 IMAGE_SEQUENCE_FPS = FPS DEFAULT_AUDIO_FADING_DURATION = 0.25 DEFAULT_IMAGE_CLIP_DURATION = 2 ignore_undefined = False if 0: change_settings({"FFMPEG_BINARY": get_executable("ffmpeg")}) _pos_dict = {"c": 0, "a": 0, "as": 0, "ae": 0, "vs": 0, "ve": 0} _subtitle: List[str] = [] _srt_lines = [] _srt_index = 1 _last_subtitle_index = -1 _crossfade = 0 def _on_begin_api(func_name): print("%s()" % func_name) if func_name != "record": _try_generate_tts() else:
import moviepy.editor as mpe import os import sqlite3 import random import numpy as np from moviepy.config import change_settings if os.path.isdir("/home/vhb/Downloads/"): change_settings({"IMAGEMAGICK_BINARY": r"/home/vhb/Downloads/magick"}) elif os.path.isfile("/home/vuhaibangtk/Downloads/magick"): change_settings( {"IMAGEMAGICK_BINARY": r"/home/vuhaibangtk/Downloads/magick"}) elif os.path.isfile("/home/vuhaibangtk/youtube/magick"): change_settings( {"IMAGEMAGICK_BINARY": r"/home/vuhaibangtk/youtube/magick"}) def select_sqlite(table, value, conn): cur = conn.cursor() cur.execute(f"SELECT * FROM {table} WHERE id=(?)", ([value])) row = cur.fetchall() cur.close() return row[0] def cascade(screenpos, i): v = np.array([0, -1]) d = lambda t: 1 if t < 0 else abs(np.sinc(t) / (1 + t**4)) return lambda t: screenpos + v * 400 * d(t - 0.15 * i) def arrive(screenpos, i):
from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.chrome.options import Options import time import pathlib import os import youtube_dl from moviepy.editor import * from moviepy.video.fx.all import crop from moviepy.video.fx.all import resize import math from random import randrange from moviepy.config import change_settings from datetime import datetime, date, timedelta change_settings({ "IMAGEMAGICK_BINARY": "C:\Program Files\ImageMagick-6.9.11-Q8\convert.exe" }) def delete_file(path): try: os.remove(str(path)) except: print("Incorrect file name.") def add_desc(desc): try: with open('desc.txt', 'r+') as f: f.truncate(0) f.write(desc)
from moviepy.editor import * from moviepy.config import change_settings change_settings({ "IMAGEMAGICK_BINARY": "/usr/local/Cellar/imagemagick/7.0.10-25/bin/convert" }) def watermark(input_file_path, output_file_path, watermark_text): video = VideoFileClip(input_file_path, audio=True) txt_clip = (TextClip(watermark_text, fontsize=26, color='#a8a8a7').set_position('center').set_duration( video.duration)) result = CompositeVideoClip([video, txt_clip]) result.duration = video.duration result.write_videofile(output_file_path, audio=True, audio_codec="aac", fps=25) watermark(input_file_path='output_cut.mp4', output_file_path='output_cut_watermark_2.mp4', watermark_text='hello world')
lambda_tmp_dir = '/tmp' # Lambda fuction can use this directory. # ffmpeg is stored with this script. # When executing ffmpeg, execute permission is requierd. # But Lambda source directory do not have permission to change it. # So move ffmpeg binary to `/tmp` and add permission. print("Files before ", os.listdir(lambda_tmp_dir)) ffmpeg_bin = "{0}/ffmpeg.linux64".format(lambda_tmp_dir) shutil.copyfile('/var/task/ffmpeg.linux64', ffmpeg_bin) os.environ['IMAGEIO_FFMPEG_EXE'] = ffmpeg_bin os.chmod(ffmpeg_bin, os.stat(ffmpeg_bin).st_mode | stat.S_IEXEC) print("Files after ", os.listdir(lambda_tmp_dir)) from moviepy.config import change_settings change_settings({"FFMPEG_BINARY": ffmpeg_bin}) from moviepy.audio.io.AudioFileClip import AudioFileClip voiceid_list = { "en": "Aditi", "fr": "Mathieu", "es": "Miguel", "ru": "Maxim", "zh": "Zhiyu", "ja": "izuki", "pt": "Ricardo", "de": "Marlene", "it": "carla", "tr": "Filiz" }
# Attempt to execute ImageMagick on the path present in the env. info('Configuring ImageMagick install...') debug(f'Testing for existing ImageMagick installation on \'{OSNAME}\' OS...') try: Popen( get_setting(__IMENV := 'IMAGEMAGICK_BINARY'), **{ 'stdout': sp.PIPE, 'stderr': sp.PIPE, 'stdin': DEVNULL, 'creationflags': 0x08000000 if OSNAME == 'nt' else None }).communicate() except: # If executing on the existing path didn't work, update the moviepy setting. debug( f'ImageMagick path was invalid or does not exist. Setting {__IMENV} parameter of MoviePy to local installation...' ) change_settings({__IMENV: abspath('./bin/imagemagick/magick.exe')}) # Placing editor import in the finally block so it is only imported after the ImageMagick path has been set up. finally: info('ImageMagick configuration complete!') import moviepy.editor as MPE # .--. .--. .--. .--. .--. .-| _____ __ ______________ _____ |-. .--. .--. .--. .--. .--. # #::::.\::::::::.\::::::::.\::::::::.\::::::::.\::::::| |___| ||\ || | || ||\ |[__ |::.\::::::::.\::::::::.\::::::::.\::::::::.\::::::::.\:# # `--' `--' `--' `--' `--' | | |__|| \||___ | ||__|| \|___] | `--' `--' `--' `--' `--' `# """ Contains the main and utility functions of this file. """ # .-.-. .-.-. .-.-. .-.-. .-.-. .-.-. .-.-. .-.-. .-.-. .-.-. .-.- # [=== === === === === === === === === ===] UTIL [=== === === === === === === === === ===] #`-' `-`-' `-`-' `-`-' `-`-' `-`-' `-`-' `-`-' `-`-' `-`-' `-`-' `-`
video_name = "timelapse.mp4" # ffmpeg is stored with this script. # When executing ffmpeg, execute permission is requierd. # But Lambda source directory do not have permission to change it. # So move ffmpeg binary to `/tmp` and add permission. path1 = os.path.dirname(os.path.abspath('ffmpeg')) print(path1) ffmpeg_bin = "/tmp/ffmpeg" shutil.copyfile('/opt/bin/ffmpeg', ffmpeg_bin) os.environ['IMAGEIO_FFMPEG_EXE'] = ffmpeg_bin os.chmod(ffmpeg_bin, os.stat(ffmpeg_bin).st_mode | stat.S_IEXEC) print("OK 1") from moviepy.config import change_settings change_settings({"FFMPEG_BINARY": "/tmp/ffmpeg"}) from moviepy.editor import * #from moviepy.video.io.ImageSequenceClip import ImageSequenceClip print("OK 2") s3 = boto3.client('s3') print("OK 3") image_bucket = "smart-garden-images" video_bucket = "smart-garden-generated-timelapse" print("OK 4") def prepare_path(target): print("prepare path "+target) if os.path.exists(target): logger.info("{0} exists".format(target)) shutil.rmtree(target)
def get_codec_info(codec): if codec == 'libx264': return 'h.264' if codec == 'mpeg4': return 'MPEG4' if codec == 'libmp3lame': return 'MP3' if codec == 'libfdk_aac': return 'AAC' if codecs[args.codec]['audio_codec'] == 'libfdk_aac': if not isfile(FFMPEG_BINARY_AAC): raise Exception("libfdk_aac is required, please download " + FFMPEG_BINARY_AAC + '.') mpy_conf.change_settings({'FFMPEG_BINARY': FFMPEG_BINARY_AAC}) print("Generation Mode:", args.mode.capitalize()) print("Generation Video Codec:", get_codec_info(codecs[args.codec]['codec'])) print("Generation Audio Codec:", get_codec_info(codecs[args.codec]['audio_codec'])) if args.adaptive: options['adapt_movement_scale'] = True options['relative'] = False print("Generation Scale: Adaptive") else: options['adapt_movement_scale'] = False options['relative'] = True print("Generation Scale: Relative") print()
import pickle import numpy as np import cv2 import matplotlib.pyplot as plt import glob import marklane from moviepy.editor import VideoFileClip from moviepy.config import change_settings change_settings({'FFMPEG_BINARY': '/usr/bin/ffmpeg'}) logs = {'coeff': np.zeros(4), \ 'scores': [0., 0., 0.]} def process_image(img, dist_info, pp_mtx, pp_mtx_inv, logs, \ window_width=150, window_height=50, margin=80): img_ud = marklane.undistort(img, dist_info) binary = marklane.binary_lane_threshold(img_ud) warped = marklane.warp_img(binary, pp_mtx) centroids = marklane.find_window_centroids(warped, window_width, window_height, margin) lx, ly, rx, ry, flx, fly, frx, fry = \ marklane.fit_lane_centroids(warped, centroids, window_width, window_height) coeff, scores = marklane.fit_lane_poly(warped, window_width, window_height, \ flx, fly, frx, fry, logs['coeff'], logs['scores']) logs['coeff'] = coeff logs['scores'] = scores result = marklane.draw_lanes(img_ud, coeff, pp_mtx_inv) return result[0][:, :, ::-1] with open('distort_calibration.pickle', 'rb') as f:
# logging and debugging import logging from pprint import pprint # required for image manipulation and video creation from PIL import Image, ImageDraw, ImageFont # required for MoviePy Stuff import glob from natsort import natsorted from moviepy.editor import * from moviepy.video.tools.drawing import * from moviepy.config import change_settings change_settings({"IMAGEMAGICK_BINARY": "/opt/local/bin/convert"}) from templatedetails import TemplateDetails from datetime import datetime from config import Config cfg = Config() import webcolors import gizeh as gz def createintro(projectid): status = 0 starttime = datetime.now()
__author__ = 'mahy' from moviepy.config import change_settings change_settings( {"IMAGEMAGICK_BINARY": "E:\\ImageMagick-6.2.7-Q16\\convert.exe"}) import imageio from moviepy.editor import * import tensorflow as tf from PIL import Image from matplotlib import pyplot as plt import numpy as np import os from utils import label_map_util from utils import visualization_utils as vis_util IMAGE_SIZE = (12, 8) NUM_CLASSES = 90 #video_dir ="E:\\ctfo\\tensorflow\\palm\\data\\t.mp4" video_dir = "E:\\ctfo\\tensorflow\\palm\\data\\gaosu.mp4" model_dir = "E:\\ctfo\\tensorflow\\palm\\data\\frozen_inference_graph.pb" #out_video_dir="E:\\ctfo\\tensorflow\\palm\\data\\object.mp4" out_video_dir = "E:\\ctfo\\tensorflow\\palm\\data\\gs.mp4" data_dir = "E:\\ctfo\\tensorflow\\palm\\data\\" def invert_green_blue(image): return image[:, :, [0, 2, 1]] def scroll(get_frame, t): """ This function returns a 'region' of the current frame.