利用python-opencv读取视频,计算视频总帧数以及FPS

参考:https://blog.csdn.net/qq_37902216/article/details/84987894

1、计算总帧数

import os
import cv2
 
video_cap = cv2.VideoCapture('test0116.mp4')
 
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))

2、计算视频中的FPS(Frames per second)

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();

3、函数调用

###### 视频读取,获取帧数、FPS ######
import cv2
def read_video(file_path):
	video_cap = cv2.VideoCapture(file_path)

	### 获取视频的帧数 ###
	video_frameNum = 0
	# all_frames = []
	while(True):
		ret, frame = video_cap.read()
		if ret is False:
			break
		# all_frames.append(frame)
		video_frameNum = video_frameNum + 1

	### 获取视频的FPS ###
	(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.') # Find OpenCV version

	if int(major_ver)  < 3 :
		video_FPS = video_cap.get(cv2.cv.CV_CAP_PROP_FPS)
		# print("Frames per second using video_cap.get(cv2.cv.CV_CAP_PROP_FPS): {0}".format(fps))
	else:
		video_FPS = video_cap.get(cv2.CAP_PROP_FPS)
		# print("Frames per second using video_cap.get(cv2.CAP_PROP_FPS) : {0}".format(fps))
 
	video_cap.release()

	return video_frameNum,video_FPS

video_path = 'test.mp4'
video_frameNum,video_FPS = read_video(video_path) # 获取视频帧数
print(video_frameNum)
print(video_FPS)

 

你可能感兴趣的:(Python,Computer,vision)