由於要進行多路視頻的處理,所以fps就很重要
模板:
1.獲取某一時刻的fps
import time while True: start_time = time.time() # start time of the loop ######################## # your fancy code here # ######################## print("FPS: ", 1.0 / (time.time() - start_time)) # FPS = 1 / time to process loop
2.每一秒獲取一次
import time start_time = time.time() x = 1 # displays the frame rate every 1 second counter = 0 while True: ######################## # your fancy code here # ######################## counter+=1 if (time.time() - start_time) > x : print("FPS: ", counter / (time.time() - start_time)) counter = 0 start_time = time.time()
3.實例
(1)讀取目錄中的某一個視頻
import time import cv2 cap = cv2.VideoCapture("../video/basketball1.mp4") start_time = time.time() x = 1 # displays the frame rate every 1 second counter = 0 while True: ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame', gray) if cv2.waitKey(1) & 0xFF == ord('q'): break counter += 1 if (time.time() - start_time) > x: print("FPS: ", counter / (time.time() - start_time)) counter = 0 start_time = time.time() cap.release() cv2.destroyAllWindows()
運行效果
其實把fps顯示到窗口上更人性化一點,於是我把原來的putTest()方法和這個結合了一下,中間format里面轉化了一下類型
import time import cv2 cap = cv2.VideoCapture("../video/basketball1.mp4") start_time = time.time() x = 1 # displays the frame rate every 1 second counter = 0 while True: ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if cv2.waitKey(1) & 0xFF == ord('q'): break counter += 1#記錄經過多少秒 if (time.time() - start_time) > x: cv2.putText(gray, "FPS {0}" .format(str(counter / (time.time() - start_time))), (10, 230), 6, 2, (255, 0, 255), 3) #cv2.putText(gray, "FPS %s" % str(counter / (time.time() - start_time)), (10, 130), 6, 5, (255, 0, 255), 5) #cv2.putText(gray, "Hello World!", (400, 50), cv2.FONT_HERSHEY_PLAIN, 2.0, (0, 0, 255), 2) cv2.imshow('frame', gray) print("FPS: ", counter / (time.time() - start_time)) #print(type(str(counter / (time.time() - start_time)))) #print(type(counter / (time.time() - start_time))) counter = 0 start_time = time.time() cap.release() cv2.destroyAllWindows()
運行結果,fps數據每一秒都會刷新一下