[英]plt.imshow() giving TypeError(“Image data cannot be converted to float”)
[英]TypeError: Image data cannot be converted to float with plt.imshow after importing with tf.io.decode_jpeg
我正在嘗試使用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)
不確定您的tensorflow版本。 TensorFlow默認在1.x
使用靜態計算圖。 您獲得的image
的數據類型為Tensor
從而顯示此錯誤。 首先創建自定義圖片。
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')
然后,您需要使用tf.Session()
啟動此會話。 這將顯示上面創建的圖像。
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)
或者您可以通過tf.enable_eager_execution()
啟動動態計算圖。 上面的代碼可以達到相同的效果。
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()
tensorflow2中的默認值是動態計算圖。 您不需要使用tf.enable_eager_execution()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.