Crop video with 3 lines of code

Posted by Afsal on 20-Jan-2023

Hi Pythonistas!

In the previous post, we said that cropping is not available in pytube. Today we are learning a package that can crop videos quickly with 3 lines of code.  We are using a python package called moviepy for this. 

Installation

pip install moviepy

Code

from moviepy.editor import VideoFileClip
video = VideoFileClip("strell_cbr_650.mp4").subclip(180, 200)
video.write_videofile("cropped.mp4")

The argument for the VideoFileClip is the actual video. 

The argument for the subclip is starting time, and ending time respectively in seconds

The argument for the write_videofile is the name of the edited file

Output

Moviepy - Building video cropped.mp4.
MoviePy - Writing audio in croppedTEMP_MPY_wvf_snd.mp3
MoviePy - Done.                                                                                                                                                                                                
Moviepy - Writing video cropped.mp4
Moviepy - Done !                                                                                                                                                                                               
Moviepy - video ready cropped.mp4

Once the script is executed the cropped file is generated in the path specified in the code.

We can do many things with moviepy. You can visit the official documentation for more details.

Hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in