Allyl Isocyanate
Allyl Isocyanate

Reputation: 13626

TypeError: Image data cannot be converted to float with plt.imshow after importing with tf.io.decode_jpeg

I'm trying to load a file with Tensorflow and visualize the result, but I'm getting TypeError: Image data cannot be converted to float

import tensorflow as tf
import matplotlib.pyplot as plt

image = tf.io.read_file('./my-image.jpg')
image = tf.io.decode_jpeg(image, channels=3)
print(image.shape)  # (?, ?, 3)
plt.imshow(image)

Upvotes: 1

Views: 1209

Answers (1)

giser_yugang
giser_yugang

Reputation: 6176

Not sure about your tensorflow version. TensorFlow uses static computational graphs by default in 1.x. The data type of image you get is Tensor so that show this error. First create a custom picture.

import numpy as np
from PIL import Image

np.random.seed(0)
image = np.random.random_sample(size=(256,256,3))
im = Image.fromarray(image, 'RGB')
im.save('my-image.jpg')

Then You need to use tf.Session() to start this session. This will show the image created above.

import tensorflow as tf
import matplotlib.pyplot as plt

image = tf.io.read_file('my-image.jpg')
image = tf.io.decode_jpeg(image, channels=3)
print(image)

with tf.Session() as sess:
    plt.imshow(sess.run(image))
    plt.show()

# print
Tensor("DecodeJpeg:0", shape=(?, ?, 3), dtype=uint8)

enter image description here

Or you can start dynamic computational graphs by tf.enable_eager_execution() in tensorflow. The same effect is achieved with the above code.

import tensorflow as tf
import matplotlib.pyplot as plt

tf.enable_eager_execution()

image = tf.io.read_file('my-image.jpg')
image = tf.io.decode_jpeg(image, channels=3)
plt.imshow(image)
plt.show()

The default in tensorflow2 is dynamic computational graphs. You don't need to use tf.enable_eager_execution().

Upvotes: 2

Related Questions