我們將根據(jù)我們的選擇顯示視頻文件或網(wǎng)絡(luò)攝像頭的實(shí)時(shí)處理 FPS。
FPS或每秒幀數(shù)或幀速率可以定義為每秒顯示的幀數(shù)襟铭。視頻可以假設(shè)為圖像的集合贱鄙,或者我們可以說(shuō)以某種速率顯示以產(chǎn)生運(yùn)動(dòng)的幀。如果您想識(shí)別視頻中的物體潮罪,那么 15 fps 就足夠了康谆,但如果您希望識(shí)別在高速公路上以 40 公里/小時(shí)的速度行駛的車(chē)號(hào),那么您至少需要 30 fps 才能輕松識(shí)別嫉到。因此沃暗,如果我們知道如何在計(jì)算機(jī)視覺(jué)項(xiàng)目中計(jì)算 FPS,那就太好了何恶。
計(jì)算實(shí)時(shí) FPS 的步驟:
第一步是使用 cv2創(chuàng)建視頻捕獲對(duì)象孽锥。視頻捕獲().我們可以從網(wǎng)絡(luò)攝像頭或視頻文件中讀取視頻,具體取決于我們的選擇 .
現(xiàn)在我們將逐幀處理捕獲的素材细层,直到capture.read() 為 true(這里捕獲表示一個(gè)對(duì)象惜辑,此函數(shù)還與幀一起返回布爾值并提供幀是否已成功讀取的信息)。
為了計(jì)算 FPS今艺,我們將記錄處理最后一幀的時(shí)間和當(dāng)前幀處理的結(jié)束時(shí)間韵丑。因此,一幀的處理時(shí)間將是 當(dāng)前時(shí)間和前一幀時(shí)間之間的時(shí)間差 .
Processing time for this frame = Current time – time when previous frame processed
所以目前 fps 將是 :?
FPS = 1/ (Processing time for this frame)
由于 FPS 將始終是整數(shù)虚缎,我們將 FPS 轉(zhuǎn)換為整數(shù)撵彻,然后將其類(lèi)型轉(zhuǎn)換為字符串,因?yàn)槭褂胏v2.putText() 在幀上顯示字符串將很容易实牡、更快捷∧敖現(xiàn)在借助cv2.putText() 方法,我們將在此幀上打印 FPS创坞,然后在cv2.imshow()function 的幫助下顯示此幀碗短。
代碼:上述方法的Python代碼實(shí)現(xiàn)?
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()
轉(zhuǎn)自:https://www.shengbios.com