Hal T
Hal T

Reputation: 547

Run Tensorflow classify_image on numpy array

I have a realtime application where I'm trying to classify images that come from a feed as they arrive. The classify_images example has:

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

Where image is the path to the image file. However, I'm not reading images from a file, I'm receiving them as numpy arrays. What's the best way to run a Tensorflow session on a previously-acquired image? Also, 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?

Edit:

I tried:

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

and it worked! Thanks sygi!

Edit 2:

This crashes after a while with no error message, and also every frame has the same labels predicted. I even create a new images_place object at each frame, yet I still get the same label.

Upvotes: 2

Views: 701

Answers (1)

sygi
sygi

Reputation: 4647

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

I think the best way is to create a tf.placeholder, use it in your model and at the end pass the numpy array in a feed dict.

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?

It is better to reuse one graph and one session. When you create a graph, it is "compiled" to change the code you write to an efficient, GPU implementation. You create many graphs -- you lose a lot of time doing the same "compilation". Furthermore, when you reuse one session, it is possible for you to reuse variables, preventing from passing them from RAM to GPU memory back-and-forth.

Upvotes: 1

Related Questions