Python – 显示使用 OpenCV 处理网络摄像头/视频文件的实时 FPS
我们将根据我们的选择显示视频文件或网络摄像头的实时处理 FPS。
FPS或每秒帧数或帧率可以定义为每秒显示的帧数。可以将视频假定为图像的集合,或者我们可以说以某种速率显示以产生运动的帧。如果您希望识别视频中的对象,则 15 fps 就足够了,但如果您希望识别以 40 公里/小时的速度移动的车号。在高速公路上,您需要至少 30 fps 才能轻松识别。因此,如果我们知道如何在我们的计算机视觉项目中计算 FPS,那将是一件好事。
计算实时 FPS 的步骤:
- 第一步是使用 cv2.VideoCapture()创建一个 VideoCapture 对象。我们可以根据我们的选择从网络摄像头或视频文件中读取视频。
- 现在我们将逐帧处理捕获的素材,直到capture.read()为真(这里 capture 表示一个对象,此函数还带有 frame 它还返回 bool 并提供帧是否已成功读取的信息)。
- 为了计算 FPS,我们会记录上一帧处理的时间和当前帧处理的结束时间。因此,一帧的处理时间将是当前时间和上一帧时间之间的时间差。
Processing time for this frame = Current time – time when previous frame processed
所以当前的 fps 将是:
FPS = 1/ (Processing time for this frame)
- 由于 FPS 将始终为整数,我们将 FPS 转换为整数,然后将其类型转换为字符串,因为在 frame 上使用 cv2.putText() 显示字符串会更容易和更快。现在借助cv2.putText()方法,我们将在此帧上打印 FPS,然后借助cv2.imshow()函数显示此帧。
代码:上述方法的Python代码实现
Python3
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'):
break
# When everything done, release the capture
cap.release()
# Destroy the all windows now
cv2.destroyAllWindows()
输出:以绿色显示实时 FPS 的视频文件。