Ayushi Dalmia
Ayushi Dalmia

Reputation: 305

Decoding image using tensorflow

I am trying to read an image in tf. Using the image file name I perform the following simple operations.

image_string = tf.read_file(imagefilename)
image = tf.image.decode_image(image_string)

Now, when I print image after sess.run, I get the values of all the indices in the tensor to be same and 254. Any guesses where I am wrong?

Pointers on debugging would also help.

The batch processing code:

def _parse_image(self,imagefile,text,label):
    image_string = tf.read_file(imagefile)
    image = tf.image.decode_image(image_string)    
    image = tf.cast(image, tf.float32)
    return image, text, label   


def get_batch(self,typefile="train",batch_size = 64, num_workers = 40):
     train_dataset = tf.contrib.data.Dataset.from_tensor_slices((images, text, labels)) // This works fine. the filename, text and labels are correctly loaded
     train_dataset = train_dataset.map(self._parse_image,num_threads=num_workers, output_buffer_size= batch_size)
     batched_train_dataset = train_dataset.batch(batch_size)
     return batched_train_dataset


batch_train_dataset = get_batch("train")
init_op = tf.global_variables_initializer()
iterator = batch_train_dataset.make_initializable_iterator()
next_element = iterator.get_next()
with tf.Session() as sess:
    sess.run(init_op)
    sess.run(iterator.initializer)
out = sess.run(next_element)
tf.Print(out)

When I print out, I get the text and label as fine but the images are all having the same value. Anything wrong I am doing?

Upvotes: 1

Views: 594

Answers (1)

Maxim
Maxim

Reputation: 53778

This code is correct. Try to read this image with this snippet:

image_string = tf.read_file('friday.jpg')
image = tf.image.decode_image(image_string)

with tf.Session() as session:
  img_value = session.run(image)
  print(np.min(img_value), np.max(img_value), np.mean(img_value))

.. and you should get:

0 255 93.6996542494

... which is a reasonable distribution of image pixels.

  • If you still see the array of 254, this would be very strange, you might need to reinstall tensorflow.
  • If the snippet above works for friday.jpg, but fails for your imagefilename, try to inspect the format of your image. Is it corrupted?
  • If both output reasonable pixel distributions, the image is read correctly, it's just a bug in your tensor evaluation.

Upvotes: 1

Related Questions