簡體   English   中英

TypeError:tf.image.per_image_standardization(x)之后無法將圖像數據轉換為float

[英]TypeError: Image data cannot be converted to float after tf.image.per_image_standardization(x)

我在plt.imshow遇到以下錯誤

TypeError: Image data cannot be converted to float

對於此代碼:

import keras
import tensorflow as tf
import matplotlib.pyplot as plt
mnist = keras.datasets.mnist

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

def preprocess(x):
    x = tf.image.per_image_standardization(x)
    return x

train_images = preprocess(train_images)
test_images = preprocess(test_images)

plt.figure()
plt.imshow(train_images[1])
plt.colorbar()
plt.grid(False)
plt.show()

任何想法為什么會這樣? 謝謝!

在您的腳本中, train_images不包含實際數據,而只是占位符張量:

train_images[1]
<tf.Tensor 'strided_slice_2:0' shape=(28, 28) dtype=float32>

最簡單的解決方案是在腳本頂部啟用急切執行:

tf.enable_eager_execution()

這意味着在運行時,張量實際上將包含您嘗試繪制的數據:

train_images[1]
<tf.Tensor: id=95, shape=(28, 28), dtype=float32, numpy=
array([[-0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 ,
        -0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 ,
        -0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 ,
        -0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 ,
        -0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 , -0.4250042 ,
        -0.4250042 , -0.4250042 , -0.4250042 ], # etc

哪個應該解決您的錯誤。 您可以在TF的網站上了解有關急切執行的更多信息。

或者,您也可以通過在會話中實際評估圖像張量來繪制圖:

with tf.Session() as sess:
    img = sess.run(train_images[1])
    plt.figure()
    plt.imshow(img)
    plt.colorbar()
    plt.grid(False)
    plt.show()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM