我们将根据我们的选择显示视频文件或网络摄像头的实时处理 FPS。
FPS或每秒帧数或帧速率可以定义为每秒显示的帧数。视频可以假设为图像的集合,或者我们可以说以某种速率显示以产生运动的帧。如果您想识别视频中的物体,那么 15 fps 就足够了,但如果您希望识别在高速公路上以 40 公里/小时的速度行驶的车号,那么您至少需要 30 fps 才能轻松识别。因此,如果我们知道如何在计算机视觉项目中计算 FPS,那就太好了。
计算实时 FPS 的步骤:
第一步是使用 cv2创建视频捕获对象。视频捕获().我们可以从网络摄像头或视频文件中读取视频,具体取决于我们的选择 .
现在我们将逐帧处理捕获的素材,直到capture.read() 为 true(这里捕获表示一个对象,此函数还与帧一起返回布尔值并提供帧是否已成功读取的信息)。
为了计算 FPS,我们将记录处理最后一帧的时间和当前帧处理的结束时间。因此,一帧的处理时间将是 当前时间和前一帧时间之间的时间差 .
Processing time for this frame = Current time – time when previous frame processed
所以目前 fps 将是 :
FPS = 1/ (Processing time for this frame)
由于 FPS 将始终是整数,我们将 FPS 转换为整数,然后将其类型转换为字符串,因为使用cv2.putText() 在帧上显示字符串将很容易、更快捷。现在借助cv2.putText() 方法,我们将在此帧上打印 FPS,然后在cv2.imshow()function 的帮助下显示此帧。
代码:上述方法的Python代码实现
import numpy as np
import cv2
import time
# creating the videocapture object
# and reading from the input file
# Change it to 0 if reading from webcam
cap = cv2.VideoCapture('vid.mp4')
# used to record the time when we processed last frame
prev_frame_time = 0
# used to record the time at which we processed current frame
new_frame_time = 0
# Reading the video file until finished
while(cap.isOpened()):
# Capture frame-by-frame
ret, frame = cap.read()
# if video finished or no Video Input
if not ret:
break
# Our operations on the frame come here
gray = frame
# resizing the frame size according to our need
gray = cv2.resize(gray, (500, 300))
# font which we will be using to display FPS
font = cv2.FONT_HERSHEY_SIMPLEX
# time when we finish processing for this frame
new_frame_time = time.time()
# Calculating the fps
# fps will be number of frame processed in given time frame
# since their will be most of time error of 0.001 second
# we will be subtracting it to get more accurate result
fps = 1/(new_frame_time-prev_frame_time)
prev_frame_time = new_frame_time
# converting the fps into integer
fps = int(fps)
# converting the fps to string so that we can display it on frame
# by using putText function
fps = str(fps)
# putting the FPS count on the frame
cv2.putText(gray, fps, (7, 70), font, 3, (100, 255, 0), 3, cv2.LINE_AA)
# displaying the frame with fps
cv2.imshow('frame', gray)
# press 'Q' if you want to exit
if cv2.waitKey(1) & 0xFF == ord('q'):