简体   繁体   English

使用 OpenCV 计算视频文件中的帧数?

[英]Counting the Number of Frames in a Video file using OpenCV?

I am trying to count total number of Frames in my video file ('foo.h264').我正在尝试计算视频文件(“foo.h264”)中的总帧数。

>>> import numpy as nm
>>> import cv2
>>> cap = cv2.VideoCapture('foo.h264')
>>> cap.get(CV_CAP_PROP_FRAME_COUNT)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'CV_CAP_PROP_FRAME_COUNT' is not defined
>>> cap.get(5)
25.0
>>> cap.get(7)
-192153584101141.0

So I think get(5) is giving frame rate and get(7) gives total number of frames.所以我认为get(5)给出了帧速率,而get(7)给出了总帧数。 Obviously get(7) is incorrect in the above case.显然get(7)在上述情况下是不正确的。 So to verify I tried to find these values in an .avi file.因此,为了验证我试图在.avi文件中找到这些值。

>>> cap = cv2.VideoCapture('foo.avi')
>>> cap.get(5)
29.97002997002997
>>> cap.get(7)
256379.0

I can calculate the total number of frames by multiplying FPS by duration of the video, but I'm not sure if the FPS given for .h264 is right or not.我可以通过将FPS乘以视频的持续时间来计算总帧数,但我不确定为.h264给出的 FPS 是否正确。 Why does it give negative number of total frames?为什么它给出负数的总帧数? Is this a bug?这是一个错误吗?
PS: I recorded this video file ( .h264 ) using raspberry pi camera. PS:我用树莓派相机录制了这个视频文件( .h264 )。

Another solution is using imageio , which works for some videos. 另一种解决方案是使用imageio ,适用于某些视频。

import imageio
filename="person15_walking_d1_uncomp.avi"
vid = imageio.get_reader(filename,  'ffmpeg')
# number of frames in video
num_frames=vid._meta['nframes']

As it turns out OpenCV does not support h.264 format ( Link ). 事实证明,OpenCV不支持h.264格式( Link )。 However, the documentation on Video Capture at Python OpenCV documentation mentions an integer argument for the get command. 但是, Python OpenCV文档中的Video Capture 文档提到了get命令的整数参数。 So, you're right on that count on using 5 and 7 instead of 'CV_CAP_PROP_FRAME_COUNT'. 所以,你正确使用5和7代替'CV_CAP_PROP_FRAME_COUNT'。 You could try changing the capture format on the raspberry pi to avi. 您可以尝试将覆盆子pi上的捕获格式更改为avi。

This worked for me (no opencv used):这对我有用(没有使用 opencv):

import imageio

file="video.mp4" #the path of the video
vid=imageio.get_reader(file,  'ffmpeg')
totalframes = vid.count_frames()

print(totalframes)

It will return the total frames:)它将返回总帧数:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM