Skip to main content
 首页 » 编程设计

python之在 numpy 数组上运行 Tensorflow classify_image

2025年04月02日32birdshome

我有一个实时应用程序,我试图在来自提要的图像到达时对其进行分类。 classify_images 示例具有:

image_data = tf.gfile.FastGFile(image, 'rb').read() 
#... 
with tf.Session() as sess: 
    predictions = sess.run(softmax_tensor, 
        {'DecodeJpeg/contents:0': image_data}) 

其中 image 是图像文件的路径。但是,我不是从文件中读取图像,而是将它们作为 numpy 数组接收。在先前获取的图像上运行 Tensorflow session 的最佳方式是什么?此外,最好的做法是事先创建一个 session 和一个图形,并且每当获取新帧时,在新图像上运行现有 session ,而不是创建一个新图形和一个新 session ?

编辑:

我试过:

images_placeholder = tensorflow.placeholder(tensorflow.int32) 
predictions = sess.run(softmax_tensor, 
                       {images_placeholder: image}) 

成功了!谢谢 sygi!

编辑 2:

这会在没有错误消息的情况下在一段时间后崩溃,并且每一帧都具有相同的预测标签。我什至在每一帧都创建了一个新的 images_place 对象,但我仍然得到相同的标签。

请您参考如下方法:

What's the best way to run a Tensorflow session on a previously-acquired image?

我认为最好的方法是创建一个 tf.placeholder,在您的模型中使用它,最后在 feed dict 中传递 numpy 数组。

is the best practice to create one session and one graph beforehand, and whenever a new frame is acquired, run the existing session on the new image, instead of creating a new graph and a new session?

最好是复用一张图和一个session。当您创建图形时,它会被“编译”以将您编写的代码更改为高效的 GPU 实现。你创建了很多图表——你在做同样的“编译”时浪费了很多时间。此外,当您重用一个 session 时,您可以重用变量,从而防止将它们从 RAM 来回传递到 GPU 内存。