使用matplotlib显示MNIST图像

Bol*_*boa 6 python numpy matplotlib mnist tensorflow

我使用tensorflow导入一些MNIST输入数据.我按照本教程... https://www.tensorflow.org/get_started/mnist/beginners

我正在导入它们......

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
Run Code Online (Sandbox Code Playgroud)

我希望能够显示训练集中的任何图像.我知道图像的位置是mnist.train.images,所以我尝试访问第一个图像并显示它...

with tf.Session() as sess:
    #access first image
    first_image = mnist.train.images[0]

    first_image = np.array(first_image, dtype='uint8')
    pixels = first_image.reshape((28, 28))
    plt.imshow(pixels, cmap='gray')
Run Code Online (Sandbox Code Playgroud)

我试图将图像转换为28乘28的numpy数组,因为我知道每个图像是28 x 28像素.

但是,当我运行代码时,我得到的是以下内容......

在此输入图像描述

显然我做错了什么.当我打印出矩阵时,一切看起来都很好,但我认为我错误地重塑了它.

Vin*_*ieu 12

这是使用matplotlib显示图像的完整代码

first_image = mnist.test.images[0]
first_image = np.array(first_image, dtype='float')
pixels = first_image.reshape((28, 28))
plt.imshow(pixels, cmap='gray')
plt.show()
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用,谢谢.. 请编辑包含定义了 `np`、`mnist`、`plt` 等的几行导入行,以便搜索快速答案的人可以快速复制和粘贴你所拥有的内容。谢谢 (3认同)

小智 10

以下代码显示了用于训练神经网络的MNIST数字数据库显示的示例图像.它使用来自堆栈流的各种代码,避免了pil.

# Tested with Python 3.5.2 with tensorflow and matplotlib installed.
from matplotlib import pyplot as plt
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot = True)
def gen_image(arr):
    two_d = (np.reshape(arr, (28, 28)) * 255).astype(np.uint8)
    plt.imshow(two_d, interpolation='nearest')
    return plt

# Get a batch of two random images and show in a pop-up window.
batch_xs, batch_ys = mnist.test.next_batch(2)
gen_image(batch_xs[0]).show()
gen_image(batch_xs[1]).show()
Run Code Online (Sandbox Code Playgroud)

mnist的定义位于:https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/datasets/mnist.py

使我需要显示MNINST图像的张量流神经网络位于:https://github.com/tensorflow/tensorflow/blob/r1.2/tensorflow/examples/tutorials/mnist/mnist_deep.py

由于我只编写了两个小时的Python编程,我可能会犯一些新的错误.请随意纠正.


all*_*llo 4

您正在将浮点数数组(如文档中所述)转换为uint8,如果不是,则将它们截断为 0 1.0。您应该对它们进行舍入或将它们用作浮点数或乘以 255。

我不确定为什么你看不到白色背景,但我建议无论如何使用明确定义的灰度。