How to flip an mp4 video horizontally in python?

Question:

I have looked into this in moviepy and ffmpeg but could only find how to rotate a video, and not flip it horizontally.

Asked By: John Locke

||

Answers:

In ffmpeg, its easy to flip a video horizontally:

import ffmpeg
stream = ffmpeg.input('input.mp4')
stream = ffmpeg.hflip(stream)
stream = ffmpeg.output(stream, 'output.mp4')
ffmpeg.run(stream)

Reference: ffmpeg-python Github

Well, you haven’t mentioned that you need to preserve the audio as well.
But, if you want to preserve audio in your clip you can do the following. Note, I have used moviepy library.

from moviepy.editor import VideoFileClip, vfx
video = VideoFileClip('sample.mp4')
out = video.fx(vfx.mirror_x)
out.write_videofile('out.mp4')
Answered By: Aditya

Since the question is tagged moviepy:

from moviepy.editor import VideoFileClip, vfx
clip = VideoFileClip('video.mp4')
reversed_clip = clip.fx(vfx.mirror_x)
reversed_clip.write_videofile('new_video.mp4')

See this page for a general list of predefined effects.

Answered By: Zulko

To complement the accepted answer, the code below preserves the audio when flipping with ffmpeg-python:

input_video = ffmpeg.input('input.mp4')
flipped_video = input_video.hflip()
audio = input_video.audio
out = ffmpeg.output(flipped_video, audio, 'output.mp4')
out.run()

If the video has no audio, you’ll need to catch the exception.

Ref: https://github.com/kkroening/ffmpeg-python/tree/master/examples#audiovideo-pipeline

Answered By: juanjo12x
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.