Python TensorFlow - 显示来自 MNIST 数据集的图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38308378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TensorFlow - Show image from MNIST DataSet
提问by JonyK
I'm trying to learn TensorFlow and I implemented the MNIST example from the the following link: http://openmachin.es/blog/tensorflow-mnistI want to be able to actually view the training/test images. So I'm trying to add code that will show the first train picture of the first batch:
我正在尝试学习 TensorFlow,我从以下链接实现了 MNIST 示例:http://openmachin.es/blog/tensorflow-mnist 我希望能够实际查看训练/测试图像。所以我试图添加代码来显示第一批的第一张火车图片:
x_i = batch_xs[0]
image = tf.reshape(x_i,[28,28])
Now, because the Data is in float32 type (with values in [0,1] range), I tried to convert it to uint16 and then to encode it to png in order to show the image.
I tried using tf.image.convert_image_dtype and tf.image.encode_png
, but with no success.
Can you guys please help me understand how can I convert the raw Data to an image and show the image?
现在,因为数据是 float32 类型(值在 [0,1] 范围内),我尝试将其转换为 uint16,然后将其编码为 png 以显示图像。我尝试使用tf.image.convert_image_dtype and tf.image.encode_png
,但没有成功。你们能帮我理解如何将原始数据转换为图像并显示图像吗?
回答by jean
After reading the tutorial you can do it all in numpy no need for TF:
阅读教程后,您可以在 numpy 中完成所有操作,无需 TF:
import matplotlib.pyplot as plt
first_array=batch_xs[0]
#Not sure you even have to do that if you just want to visualize it
#first_array=255*first_array
#first_array=first_array.astype("uint8")
plt.imshow(first_array)
#Actually displaying the plot if you are not in interactive mode
plt.show()
#Saving plot
plt.savefig("fig.png")
You can also use PIL or whatever visualization tool you are into.
您还可以使用 PIL 或任何您喜欢的可视化工具。
回答by user7848353
X = X.reshape([28, 28]);
plt.gray()
plt.imshow(X)
this works.
这有效。
回答by Xihao Li
On top of the codes in the tutorial MNIST for ML beginners, you can visualize the image in the mnist dataset:
除了面向机器学习初学者的教程 MNIST 中的代码之外,您还可以在 mnist 数据集中可视化图像:
import matplotlib.pyplot as plt
batch = mnist.train.next_batch(1)
plotData = batch[0]
plotData = plotData.reshape(28, 28)
plt.gray() # use this line if you don't want to see it in color
plt.imshow(plotData)
plt.show()
回答by PlsWork
Pass a numpy array representing an MNIST image to the function below and it will display a figure using matplotlib.
将一个表示 MNIST 图像的 numpy 数组传递给下面的函数,它将使用 matplotlib 显示一个图形。
def displayMNIST(imageAsArray):
imageAsArray = imageAsArray.reshape(28, 28);
plt.imshow(imageAsArray, cmap='gray')
plt.show()
回答by user650654
In tensorflow 2.0:
在张量流 2.0 中:
import matplotlib.pyplot as plt
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
plt.imshow(x_train[0], cmap='gray_r')