Crop a video in Python, centered on a 16×9 video, cropped to 9×16, moviepy?

Question:

I want to crop a video that is 16×9 resolution to 9×16. This can be done by cropping a centered 607px wide rectangle on the 16×9 video. Can this be done? EDIT: I do not care to stay within moviepy. I want to use something with speed. Currently, writing a 5 min video file with moviepy is taking 10+ minutes.

cropping video from 16x9 to 9x16

from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
import moviepy.editor as mpy

origVideo = 'video.mp4'
video = mpy.VideoFileClip(origVideo)

#Crop 'video' here and output 'cropped-video.mp4'

video.write_videofile('video-cropped.mp4')

Currently only getting a black screen with no audio. The video won’t play, but it has a time code.

Asked By: Levfo

||

Answers:

You can use moviepy.video.fx.all.crop. Documentation are here. For example,

import moviepy.editor as mpy
from moviepy.video.fx.all import crop

clip = mpy.VideoFileClip("path/to/video.mp4")
(w, h) = clip.size

crop_width = h * 9/16
# x1,y1 is the top left corner, and x2, y2 is the lower right corner of the cropped area.

x1, x2 = (w - crop_width)//2, (w+crop_width)//2
y1, y2 = 0, h
cropped_clip = crop(clip, x1=x1, y1=y1, x2=x2, y2=y2)
# or you can specify center point and cropped width/height
# cropped_clip = crop(clip, width=crop_width, height=h, x_center=w/2, y_center=h/2)
cropped_clip.write_videofile('path/to/cropped/video.mp4')

The code is not tested. If there is any further question, please let me know.

Answered By: jiayu

Do:

import os
from moviepy.editor import VideoFileClip,concatenate_videoclips
import moviepy.editor as mpy
from moviepy.video.fx.all import crop

# path of the video file to be cropped
path = '/home/lenovo/Videos/Youtube/ToCrop/'

# path of the video file to be saved after cropping
output_video = '/home/lenovo/Videos/Youtube/sample/'

for filename in os.listdir(path):
    clip = mpy.VideoFileClip(path+filename)
    (w, h) = clip.size
    cropped_clip = crop(clip, width=600, height=5000, x_center=w/2, y_center=h/2)
    cropped_clip.write_videofile(output_video+filename)

Source: https://github.com/JerlinJR/Crop-a-Video/blob/main/crop.py


This answer was posted as an edit to the question Crop a video in Python, centered on a 16×9 video, cropped to 9×16, moviepy? by the OP Levfo under CC BY-SA 4.0.

Answered By: vvvvv
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.