我正试图在TensorFlow中获取神经网络预测的运行时间,该预测在OpenCV w/Python中运行实时推理。每当分类为true时,我都会在窗口中显示一个文本标签,我非常想测量它为true的秒数。
我的想法是得到流开始时的开始时间,然后得到预测的开始时间并减去这两个时间,得到经过的时间。
不过,这让我获得了与预期不同的价值观。对此,最好的方法是什么?
这是我的代码:
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()
我认为您可以使用python装饰器,这里有一个例子:
# 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()