简体   繁体   中英

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)

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)

在此处输入图片说明

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM