如何计算一个视频中的总帧数呢,最简单的还是用 FFmpeg,命令如下:
$ffmpeg -i test.avi -vcodec copy -f rawvideo -y /dev/null 2>&1 | tr ^M '\n' | awk '/^frame=/ {print $2}'|tail -n 1
这个命令也是粘贴的 stackoverflow 上的(很奇怪的一行命令),结果如下:
或者,我更偏向于第二种方法,用 opencv 来做。
import os
import cv2
video_cap = cv2.VideoCapture('ffmpeg_test.avi')
frame_count = 0
all_frames = []
while(True):
ret, frame = video_cap.read()
if ret is False:
break
all_frames.append(frame)
frame_count = frame_count + 1
# The value below are both the number of frames
print frame_count
print len(all_frames)
下面一个问题,如何知道一个视频中的 FPS,即:每秒传输帧数(Frames Per Second))。还是用 cv2
来解决:
import cv2
if __name__ == '__main__' :
video = cv2.VideoCapture("video.mp4");
# Find OpenCV version
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
if int(major_ver) < 3 :
fps = video.get(cv2.cv.CV_CAP_PROP_FPS)
print "Frames per second using video.get(cv2.cv.CV_CAP_PROP_FPS): {0}".format(fps)
else :
fps = video.get(cv2.CAP_PROP_FPS)
print "Frames per second using video.get(cv2.CAP_PROP_FPS) : {0}".format(fps)
video.release();
结果如下: