我正在使用本教程来开始使用 TensorFlow - TensorFlow for poets .
使用 retrain.py 脚本训练模型后,我想使用 retrained_graph.pb 用于对视频进行分类并在视频运行时实时查看结果。
我所做的是使用opencv读取我想要逐帧分类的视频。即读取一帧,保存它,打开它,对其进行分类并使用 cv2.imshow() 将其与分类结果一起显示在屏幕上。
它可以工作,但由于从磁盘读取帧或将帧写入磁盘,生成的视频有延迟。
我可以使用训练过程中获得的图表对视频进行分类,而无需逐帧读取和保存吗?
这是我正在使用的代码 -
with tf.Session(graph=graph) as sess:
video_capture = cv2.VideoCapture(video_path)
i = 0
while True:
frame = video_capture.read()[1] # get current frame
frameId = video_capture.get(1) #current frame number
i = i + 1
cv2.imwrite(filename="C:\\video_images\\"+ str(i) +".jpg", img=frame) # write frame image to file
image_data = "C:\\video_images\\" + str(i) + ".jpg"
t = read_tensor_from_image_file(image_data,
input_height=input_height,
input_width=input_width,
input_mean=input_mean,
input_std=input_std)
predictions = sess.run(output_operation.outputs[0], {input_operation.outputs[0]: t})
top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]
scores = []
for node_id in top_k:
human_string = label_lines[node_id]
score = predictions[0][node_id]
scores.append([score, human_string])
#print('%s (score = %.5f)' % (human_string, score))
#print("\n\n")
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame, scores[0][1] + " - " + repr(round(scores[0][0], 2)), (10, 50), font, 1, (0, 0, 255), 2, cv2.LINE_AA)
cv2.putText(frame, scores[1][1] + " - " + repr(round(scores[1][0], 2)), (10, 100), font, 1, (0, 0, 255), 2, cv2.LINE_AA)
cv2.imshow("image", frame)
cv2.waitKey(1)
os.remove("C:\\video_images\\" + str(i) + ".jpg")
video_capture.release()
cv2.destroyAllWindows()
谢谢。
最佳答案
frame = video_capture.read()[1] # get current frame
float_caster = frame.astype(np.float32)
dims_expander = np.expand_dims(float_caster, axis=0)
resized = cv2.resize(dims_expander,(int(input_width),int(input_height)))
normalized = (resized - input_mean) / input_std
predictions = sess.run(output_operation.outputs[0], {input_operation.outputs[0]: normalized})
不要使用imwrite
来调用read_tensor_from_image_file
,而是获取帧本身。调整其大小并使其标准化。然后,将标准化
传递到 session 中。通过这种方式摆脱磁盘不必要的写/读操作。
关于python - 使用 TensorFlow 对实时视频进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56894356/