CoXier
CoXier

Reputation: 2663

How to make ffmpeg preserve transparency?

We know ffmpeg can help us with overlaying image on video. My target is to wrap a video with an image whose background is transparent.

ffmpeg -i device/nexus5_portrait.png -i device/input.mp4\
-filter_complex "overlay=(W-w)/2:(H-h)/2:enable='between(t,0,5)'"\
-b:v 16M -bufsize 16M device/output.mp4;

Output.mp4 has a black background. So is there any way to preserve the alpha channel?

Thanks in advance!

Upvotes: 5

Views: 7859

Answers (3)

Bruno ES
Bruno ES

Reputation: 11

ffv1 is a great format for video processing, it's lossless and preserves alpha channel. You can overlay to ffv1 and then convert to h264. It's a relatively fast codec, the only drawback is that temporary file will be very large. This format also gives you frame accuracy when cutting. More info here: lossless-video-codec-supporting-alpha-channels

Upvotes: 0

CoXier
CoXier

Reputation: 2663

A new idea saves me.

  • Use ffmpeg caonver input.mp4 to input.gif
  • Use ImageMagick to overlay input.gif on nexus5_portrait.png.

    ffmpeg -i input.mp4 -b:v 16M input.gif
    magick image.png null: \( input.gif -coalesce \) -gravity Center -layers composite des.gif
    

Upvotes: 1

Ronald S. Bultje
Ronald S. Bultje

Reputation: 11174

You need to use a video codec that supports transparency. By default, mp4 uses H.264 (using x264) which doesn't support alpha. You could look at VP8 or VP9, which do support alpha. You could also (if compression is less critical) use an image codec which supports alpha (e.g. PNG) instead of a video codec (-c:v png) for the output.

Upvotes: 2

Related Questions