Create your own basic video editing software in Python using MoviePy

Great library to create your own video editing software

Hemang Vyas
Analytics Vidhya

--

Table of content

  1. Introduction
  2. Installation
  3. Things you can do
  4. Create videos from the directory of pictures
  5. Add(or change) audio of the video
  6. Add watermark and intro
  7. Conclusion

Introduction

Sometimes we want to edit the videos for basic tasks like adding intro or outro, concatenate different videos, add watermark, etc. for your project report video or any personal projects. For that either you have to use the online tools that are available or you have to use the paid software. For that, you need to have some sort of experience with it but if you know how to code in python then this library would be really helpful.

So, recently I came across the great library called MoviePy which is recently released. So, I thought it would be great to share.

Installation

  1. Pip Method:
(sudo) pip install moviepy

2. Installing manually:

Download the zip file from this link. Then run the following code:

(sudo) python setup.py install

Things that you can do with this library:

Basically you can perform all the basic and some advanced effects on your video file. Here are some of the examples of it.

  • Non-linear video editing
  • Create GIFs from the video
  • Add the audio to your video
  • Vector Animations
  • 3D animations
  • Data animation
  • Concatenate different videos

And many more. In the following sections, I have shown some of the coding examples that you can do using the MoviePy. You can check other examples here.

Create videos from the directory of pictures:

When we return from holiday we have so many pictures and videos with us and we permanently save these moments for the rest of our lives. So, what we can do is that we can make a small video of those pictures and add some suitable music. So, whenever we watch it reminds that place.

Now if you want to do that then you have to have any of the heavy video editing software and some skills to work with that. But with this library, you can do this without any of that. Let’s jump to the coding section.

First of all import the essential things which we require.

from moviepy.editor import ImageSequenceClipfrom PIL import Image

Now, specify the input directory which contains all the images and output video file name.

thumbnail_dir = os.path.join(SAMPLE_OUTPUTS, "thumbnails")output_video = os.path.join(SAMPLE_OUTPUTS, 'final_div_to_vid.mp4')

Here, SAMPLE_OUTPUT is the predefined path of my output folder.

Now, add the path of all the image files which are in the directory to the list.

this_dir = os.listdir(thumbnail_dir)filepaths = [os.path.join(thumbnail_dir, fname) for fname in this_dir if fname.endswith("jpg")]

Since I want the images to be in a specific order I have renamed them to the numbers so it will be easier for me to sort them using a dictionary.

directory = {}for root, dirs, files in os.walk(thumbnail_dir):    for fname in files:        filepath = os.path.join(root, fname)        try:            key = float(fname.replace(".jpg", ""))        except:            key = None        if key != None:            directory[key] = filepath
new_path = []for k in sorted(directory.keys()): filepath = directory[k] new_path.append(filepath)

Here, I have created the dictionary to save the order and path. Then I have sorted them based on the key. Now, new_path is the list that contains the paths of all the images in order.

Now finally we will create a video of all the images using ImageSequenceClip by specifying either fps or the duration of the video.

clip = ImageSequenceClip(new_path, fps=5)
clip.write_videofile(output_video)

The whole code to create the video from the pictures is as follows.

Add(or change) audio of the video:

Sometimes while recording the video we have noise or we want to add voice over to the video after recording. Then we can add the audio using this library.

Import the required module. Here, AudioFileClip and VideoFileClip.

AudioFileClip class provides methods to manipulate the audio files and the VideoFileClip has methods to deal with the video file.

import os
from moviepy.editor import AudioFileClip, VideoFileClip

Now, here user needs to enter:

  • Video path
  • Audio path
  • Final video output directory
  • Final video name
  • Starting and ending time of the audio file
org_video_path = input("Enter the video path: ")audio_path = input("Enter the audio path: ")final_video_path = input("Enter the output folder path: ")final_video_name = input("Enter the final video name: ")start_dur = int(input("Enter the starting duration in seconds: "))end_dur = int(input("Enter the ending duration in seconds: "))final_video_path = os.path.join(final_video_path, final_video_name)

Create an object of the class VideoFileClip.

video_clip = VideoFileClip(org_video_path)

If you want to use the original audio of the video then you can extract it as follows:

original_audio = video_clip.audiooriginal_audio.write_audiofile(og_audio_path)

Now, create the object of the audio file and then select the part of the audio specified by the user.

background_audio_clip = AudioFileClip(audio_path)bg_music = background_audio_clip.subclip(start_dur, end_dur)

Finally, set audio to video.

final_clip = video_clip.set_audio(bg_music)final_clip.write_videofile(final_video_path, codec='libx264', audio_codec="aac")

Whole code to perform the task is as follows:

Add watermark and intro:

With this library, you can also add watermark and intro by using the class TextClip. Let’s add basic intro and watermark to the video.

import osfrom moviepy.editor import VideoFileClip, AudioFileClip, TextClip, CompositeVideoClip, concatenate_videoclips

Now, you are familiar with VideoFileClip and AudioFileClip classes. So, here I’ll explain a bit about TextClip and CompositeVideoClip classes in brief.

TextClip class is used to create a video clip that contains the text by specifying the parameters. This class provides lots of parameters and methods to set font style, font size, font color, alignment of text, duration of the clip, position, fps, etc.

CompositeVideoClip can be used to concatenate two different videos. Which takes the list of videoes as a parameter. This class also provides methods and lots of parameters and methods to set audio, fps, duration, etc.

Now, here I am asking the user to insert the video path, output folder, final video name, audio path and the watermark that they want to have on video.

org_video_path = input("Enter the video path: ")final_video_path = input("Enter the output folder path: ")final_video_name = input("Enter the final video name: ")audio_path = input("Enter the final video name: ")watermark = input("Enter the watermark: ")final_video_path = os.path.join(final_video_path, final_video_name)

Now, we will create the object of the video and audio file and trim the audio according to the video duration.

video_clip = VideoFileClip(org_video_path)audio_clip = AudioFileClip(audio_path)final_audio = audio_clip.subclip(25, 40)
w, h = video_clip.sizefps = video_clip.fps

Video size helps while creating the clip of the text like intro or watermark.

Now, let's design the intro that we want to have.

intro_duration = 5intro_text = TextClip("Hello world!", fontsize=70, color='white', size=video_clip.size)intro_text = intro_text.set_duration(intro_duration)intro_text = intro_text.set_fps(fps)intro_text = intro_text.set_pos("center")intro_music = audio_clip.subclip(25, 30)intro_text = intro_text.set_audio(intro_music)

Here I have created the object of the TextClip class with the text, font size, color and size of the clip. After that, I have set the duration of intro for 5 seconds then fps the same as the fps of the video and then the position of the text. At last, I added audio to the intro.

To create the watermark we are almost going to do the same thing as above.

watermark_size = 50watermark_text = TextClip(watermark, fontsize=watermark_size, color='black', align='East', size=(w, watermark_size))watermark_text = watermark_text.set_fps(fps)watermark_text = watermark_text.set_duration(video_clip.reader.duration)watermark_text = watermark_text.margin(left=10, right=10, bottom=2, opacity=0)watermark_text = watermark_text.set_position(("bottom"))

So, the only difference is that I have set the margin, alignment and reduced the size of the characters. Here, the alignment is either “East” for right and “West” for left.

watermarked_clip = CompositeVideoClip([video_clip, watermark_text], size=video_clip.size)watermarked_clip = watermarked_clip.set_duration(video_clip.reader.duration)watermarked_clip = watermarked_clip.set_fps(fps)watermarked_clip = watermarked_clip.set_audio(final_audio)

In the above section, I combined the original video and watermark clip and then set the duration as the video, fps again the same as video and set the audio.

Finally, we concatenate the videos and save them.

final_clip = concatenate_videoclips([intro_text, watermarked_clip])final_clip.write_videofile(final_video_path, codec='libx264', audio_codec="aac")

Whole code to add intro and watermark is as follows:

Conclusion

So, here I just showed the basic example of the things that you can do without installing any heavy software or using any online tool. Of course, you can do a lot more than I just showed here with MoviePy.

You can find my Github repository here.

Don’t hesitate to flow your ideas in the comment section below.

Thank you for reading this article.

Also, check out my other articles about Recommendation System and deploying machine learning models.

References:

MoviePy

Coding for entrepreneurs

--

--