'Counting elapsed time of prediction in real time OpenCV Python
I am trying to get the elapsed time of a neural network prediction in TensorFlow running real-time inference in OpenCV w/ Python. Whenever a classification is true, I display a text label in the window and I pretty much want to measure how many seconds it is true for.
My thinking was to get the start time at the beginning of the stream and then getting the start time of the prediction and subtracting those two to get the elapsed time.
This is getting me different values than expected though. What is the best way to go about this?
Here is my code:
import time
import cv2
cap_device = args.device
cap_width = args.width
cap_height = args.height
cap = cv2.VideoCapture(cap_device, cv2.CAP_DSHOW)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, cap_width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, cap_height)
start_time = time.time() #get start time
class_time = 0 #initialize class time
with mp_pose.Pose(model_complexity = 2) as pose_tracker: #load model
while cap.isOpened(): #while camera is running
ret, frame = cap.read() #read frames in
...
...
...
with open("labels.txt") as file: #gets labels to show pose class
lines = file.readlines()
lines = [line.rstrip() for line in lines]
#classification confidence
for i in range(0, len(prediction[0])):
if prediction[0][0] > 0.50 and prediction[0][0]<=1.00:
draw_info_text(image, lines[0],cap_width,cap_height)
class_time = time.time()
elif prediction[0][1] > 0.50 and prediction[0][1]<=1.00: =
draw_info_text(image,lines[1],cap_width,cap_height)
elif prediction[0][2] > 0.50 and prediction[0][2]<= 1.00:
draw_info_text(image,lines[2],cap_width,cap_height)
elif prediction[0][3] > 0.50 and prediction[0][3] <= 1.00:
draw_info_text(image,lines[3],cap_width,cap_height)
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
#show video
cv2.imshow('webcam', image)
if cv2.waitKey(1) == ord('q'):
break
total_prediction_time = start_time - class_time # calculate the total time pred was true
print(total_prediction_time)
cap.release()
cv2.destroyAllWindows()
Solution 1:[1]
I think you could make use of python decorators, here is an example:
# Timer decorator
def timer(fn):
from time import perf_counter
def inner(*args, **kwargs):
start_time = perf_counter()
to_execute = fn(*args, **kwargs)
end_time = perf_counter()
execution_time = end_time - start_time
print('{0} took {1:.8f}s to execute'.format(fn.__name__, execution_time))
return to_execute
return inner
@timer
def function_1():
for i in range(100000):
pass
@timer
def function_2():
for i in range(10000000):
pass
@timer
def function_3():
for i in range(10000):
pass
@timer
def function_4():
for i in range(100000000):
pass
function_1()
function_2()
function_3()
function_4()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Omar Zaidi |
