[英]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 我正在尝试使用Tensorflow加载文件并使结果可视化,但是我遇到TypeError:图像数据无法转换为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版本。 TensorFlow uses static computational graphs by default in
1.x
. TensorFlow默认在
1.x
使用静态计算图。 The data type of image
you get is Tensor
so that show this error. 您获得的
image
的数据类型为Tensor
从而显示此错误。 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. 然后,您需要使用
tf.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. 或者您可以通过
tf.enable_eager_execution()
启动动态计算图。 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. tensorflow2中的默认值是动态计算图。 You don't need to use
tf.enable_eager_execution()
. 您不需要使用
tf.enable_eager_execution()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.