fpsを知りたいことが多々ある。以下は、fpsを1秒ごとに計算してコンソールに表示していくプログラム。
[q] で終了。
import cv2
import numpy as np
import time
cap = cv2.VideoCapture(0)
prev_t = 0
current_t = 0
cnt = 0
while True:
# fps の計算
current_t = time.perf_counter()
cnt += 1
if current_t - prev_t > 1.0:
dt = current_t - prev_t
prev_t = current_t
fps = cnt / dt
cnt = 0
print('fps = %.2f' % fps)
# カメラ画像表示
ret, img = cap.read()
cv2.imshow('img', img)
# ’q’ で終了
INPUT = cv2.waitKey(10) & 0xFF
if INPUT == ord('q'):
cv2.destroyAllWindows()
break
時間を計るのにtime.time() をよく使っていたが、どうやらtime.perf_counter() の方が精度が高いらしい。
Qiita: time.time()は精度があまりよくない?
普通のweb camera や内臓カメラだと だいたい30fps くらいになる。