问题描述
想要通过ffmpeg命令将目录下的所有图片合并成1个视频,就像下面链接中的这样:
但文件夹内的图片名称并没有特别的规律,例如是4234.png~4400.png, 这样-i 后面的参数无论是%d, %4d还是%d%d%d%d都会报错。
解决方案
经过查找,发现下面网站上的一个回答已经给出了解决方案
https://stackoverrun.com/cn/q/2737982
回答如下:
Here is a script along Kevin's idea which works for me. You might want to replace the file name pattern (shot*.png) and the output filename movie.mp4. All frame_ ... files are removed by the script when finished.
# script to create movie from multiple png files # taken in choronoligcal order # start at 0 count=0 # take all files named shot - something ordered by date for f in `ls -rt shot*.png` do # get the index in 0000 format printf -v counts "%04d" $count # link file to a frame_0000 named symbolic link ln -s $f frame_$counts.png # increment counter count=`expr $count + 1` done # create movie # slowed down by factor 5 # ffmpeg -f image2 -i frame_%04d.png -vcodec mpeg4 -vf "setpts=5*PTS" movie.mp4 ffmpeg -i frame_%04d.png movie.mp4 # remove the links rm frame_*.png
其思路是先找到目录下的所有符合要求的png图片(ls -rt shot*.png)
之后遍历这些图片(for f in `ls -rt shot*.png`)
对每一张图片,都建立一个名字为frame_$counts.png,如对图片341.png就链接到0341.png上,从而使得文件名变得规律。
接下来再使用ffmpeg -i frame_%04d.png movie.mp4命令合成视频。
最后,通过rm命令删除所有链接目标。
例如,我的图片为:
只需要将代码改为
# script to create movie from multiple png files
# taken in choronoligcal order
# start at 0
count=0
# take all files named shot - something ordered by date
for f in `ls -rt *.png`
do
# get the index in 0000 format
printf $count
printf -v counts "%04d" $count
# link file to a frame_0000 named symbolic link
ln -s $f frame_$counts.png
# increment counter
count=`expr $count + 1`
done
# create movie
# slowed down by factor 5
ffmpeg -f image2 -i frame_%04d.png -vcodec mpeg4 -vf "setpts=5*PTS" movie.mp4
# ffmpeg -i frame_%04d.png movie.mp4
# remove the links
rm frame_*.png
然后将其以脚本的形式保存到linux下的与图片相同的目录中,通过chmod命令使脚本可执行(参考https://billie66.github.io/TLCL/book/chap25.html);
就可以合成视频movie.mp4.
参考
本文很大程度上参考了
https://stackoverrun.com/cn/q/2737982