如何用-filter_complex解决FFmpeg分辨率非2倍数问题(无法用-vf)
-filter_complex in FFmpeg Got it, let's tackle this problem: you need to handle odd resolutions (like 401x480) when using -filter_complex (since you can't mix it with -vf). The core issue here is that most encoders (like libx264) require even-width/height resolutions, so we need to bake the "even resolution adjustment" directly into your filter chain.
Modified Command That Works
Here's how to adjust your existing command to fix the odd resolution problem:
os.system("/tmp/ffmpeg -f lavfi -i color=black -i /tmp/2.gif -filter_complex '[1]scale=iw-mod(iw,2):ih-mod(ih,2)[gif_scaled];[0][gif_scaled]scale2ref[bg][gif];[bg]setsar=1[bg];[bg][gif]overlay=shortest=1,format=yuv420p' /tmp/outBlack2.mp4")
Breakdown of Changes
Let's walk through what each part does:
- Fix the GIF's resolution first:
[1]scale=iw-mod(iw,2):ih-mod(ih,2)[gif_scaled]takes your input GIF (stream[1]) and scales it to the nearest even resolution. For 401x480, this becomes 400x480 (since401 - (401 % 2) = 400, and 480 is already even). - Match background to the fixed GIF size:
[0][gif_scaled]scale2ref[bg][gif]now uses the already even-sized GIF as the reference to scale your black background, ensuring the background also has even dimensions. - Add pixel format compatibility:
The finalformat=yuv420pensures the output uses a pixel format that's compatible with nearly all media players (this is a common gotcha when working with overlays and H.264).
Alternative: Integrate Scaling into scale2ref
You can also combine the scaling step directly into scale2ref to keep the chain more compact:
os.system("/tmp/ffmpeg -f lavfi -i color=black -i /tmp/2.gif -filter_complex '[0][1]scale2ref=iw-mod(iw,2):ih-mod(ih,2)[bg][gif_scaled];[bg]setsar=1[bg];[bg][gif_scaled]overlay=shortest=1,format=yuv420p' /tmp/outBlack2.mp4")
Here, scale2ref=iw-mod(iw,2):ih-mod(ih,2) tells FFmpeg to scale both the background ([0]) and the GIF ([1]) to the GIF's original size rounded to even values. This achieves the same result in one fewer filter step.
Key Notes
- Always verify your output resolution with
ffprobe /tmp/outBlack2.mp4to confirm it's even. - If you're using a different encoder, double-check its resolution requirements (most modern video encoders enforce even dimensions for compression efficiency).
内容的提问来源于stack exchange,提问作者azuldev

