我正在使用 ffmpeg 提取帧并将其保存到 jpg 文件中,如下所示。
ffmpeg -i video.avi -r 1 -f image2 -q 1 %05d.jpg
但是,我如何才能获取每个提取帧的时间戳信息。例如,我想将 jpg 文件保存为文件名为 hh_mm_ss.jpg?
答案1
好吧,ffmpeg 似乎无法处理这个问题(其他流行的解决方案,如 VLC 媒体播放器,也无法处理这个问题)。我使用的一个解决方法是从中获取视频的持续时间ffmpeg -i video_file.mp4
,然后将其除以帧数。
作为参考和示例,这里有一个我编写的 bash 脚本,该脚本批量处理一组视频,将它们分成帧(@ 30 fps)并重命名文件,以便它们同时具有视频时间戳(以视频开始后的毫秒为单位)和原始帧号。
我确信该脚本可以更高效,但是对于我的目的来说它已经足够好了,所以希望它能有用(因为这个问题出现在谷歌搜索中):
# Regular expression definitions to get frame number, and to get video duration from ffmpeg -i
FRAME_REGEX="frame-([0-9]*)\.jpeg"
LEN_REGEX="Duration: ([0-9]*):([0-9]*):([0-9]*)\.([0-9]*), start"
# Loops through the files passed in command line arguments,
# example: videotoframes video-*.mp4
# or: videotoframes file1.mp4 file2.mp4 file3.mp4
for vf in "$@"; do
video_info=$(ffmpeg -i $vf 2>&1) # Get the video info as a string from ffmpeg -i
[[ $video_info =~ $LEN_REGEX ]] # Extract length using reges; Groups 1=hr; 2=min; 3=sec; 4=sec(decimal fraction)
LENGTH_MS=$(bc <<< "scale=2; ${BASH_REMATCH[1]} * 3600000 + ${BASH_REMATCH[2]} * 60000 + ${BASH_REMATCH[3]} * 1000 + ${BASH_REMATCH[4]} * 10") # Calculate length of video in MS from above regex extraction
mkdir frames-$vf # Make a directory for the frames (same as the video file prefixed with "frames-"
ffmpeg -i $vf -r 30 -f image2 frames-$vf/frame-%05d.jpeg # Convert the video file to frames using ffmpeg, -r = 30 fps
FRAMES=$(ls -1 frames-$vf | wc -l) # Get the total number of frames produced by the video (used to extrapolate the timestamp of the frame in a few lines)
# Loop through the frames, generate a timestamp in milliseconds, and rename the files
for f in frames-$vf/frame-*; do
[[ $f =~ $FRAME_REGEX ]] # Regex to grab the frame number for each file
timestamp=$(bc <<< "scale=0; $LENGTH_MS/$FRAMES*${BASH_REMATCH[1]}") # Calculate the timestamp (length_of_video / total_frames_generated * files_frame_number)
`printf "mv $f frames-$vf/time-%07d-%s" $timestamp $(basename $f)` # Execute a mv (move) command, uses the `printf ...` (execute command returned by printf) syntax to zero-pad the timestamp in the file name
done;
done;