我在使用TensorFlow时遇到了一个问题。我按照这个教程[https://www.tensorflow.org/hub/tutorials/image_retraining][1]重新训练了Inception模型,并且我想实时对摄像头捕获的图像进行分类。问题出在将图像转换为张量上。我修改了教程中的一个函数,使其不从文件加载图像,而是直接从摄像头获取。随着代码的每次迭代,session.run()方法的执行时间越来越长,我不知道这是为什么。以下是我的代码:
def read_tensor_from_camera(image, input_height=299, input_width=299, input_mean=0, input_std=255):
float_caster = tf.cast(image, tf.float32)
dims_expander = tf.expand_dims(float_caster, 0)
resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
start = time.time()
sess = tf.compat.v1.Session()
result = sess.run(normalized)
stop = time.time()
print(stop - start)
return result
cap = cv2.VideoCapture(0)
while (True):
ret, frame = cap.read()
image = cv2.resize(frame, (input_height, input_width))
t = read_tensor_from_camera(image)
cv2.imshow('frame', image)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
0.024958372116088867 0.021515846252441406 0.024405956268310547 0.024140119552612305 0.02186441421508789 0.023257970809936523 0.02323007583618164 0.024866819381713867 0.030565977096557617 0.025953292846679688 0.025441408157348633 0.026473522186279297 0.023244380950927734 0.025677204132080078 0.024083375930786133 0.024756908416748047 0.024300098419189453 0.023919343948364258 0.026715993881225586 0.02456498146057129 0.027322769165039062 0.02640247344970703 0.02555561065673828 0.0270078182220459 0.0286102294921875 0.02633523941040039 0.02658367156982422 0.02969074249267578 0.026103973388671875 0.02613973617553711 0.02724480628967285 0.026676654815673828 0.02712845802307129 0.02947235107421875 0.030956745147705078 0.03170061111450195 0.027563095092773438 0.03021693229675293 0.028293848037719727 0.03078293800354004 0.02852654457092285 0.03080129623413086 0.032123565673828125 0.03287243843078613
回答:
我找到了解决方案,我编写了自己的函数来从OpenCV图像创建归一化的张量:
def convert_tensor_from_camera(image):
image = image / 255
return [image]
图像已由OpenCV调整大小,我只需通过将图像除以像素的最大值(255)来进行归一化处理,这样就有效了 🙂