如何使用 pylab 查看 RGB 图像

How to view an RGB image with pylab

我正在尝试查看 CIFAR-10 格式的 32x32 像素 RGB 图像。这是一个 numpy 数组,其中像素值 (uint8) 排列如下: "The first 1024 bytes are the red channel values, the next 1024 the green, and the final 1024 the blue. The values are stored in row-major order, so the first 32 bytes are the red channel values of the first row of the image."

因此,原图的形状为:

numpy.shape(image)
(3072L,)

我这样重塑它:

im = numpy.reshape(image, (32,32,3))

然而,当我尝试

imshow(im)

在 iPython 控制台中,我看到原始图像的 3 x 3 块:

我原以为会看到一张汽车图片。 我在这里看到了 this question,但我不确定他们在那里做什么,是否与我的情况相关。

尝试更改顺序。默认情况下,它是 C 连续的(实际上是 row-major),但是对于 matplotlib,您需要 [:,:,0] 中的红色通道值。这意味着您应该以 Fortran 顺序读取该数据,以便它首先填充 "columns"(在此 3D 上下文中)。

im = numpy.reshape(c, (32,32,3), order='F')

我知道问题发布已经有一段时间了,但我想更正 Oliver 的回答。如果您使用 Fortran 命令,则图像会反转并逆时针旋转 90 度。

当然,如果您以这种方式格式化所有图像,您仍然可以训练这些数据。但是为了防止你发疯,你应该做以下事情:

im = c.reshape(3,32,32).transpose(1,2,0)

您正在做的是首先使用默认格式重塑矩阵,该格式使您在第一维中获得 RGB,然后在其他两个维度中获得行和列。然后你正在打乱维度,使原始维度(RGB,索引为 0)中的第一个维度切换到第三个维度,第二个和第三个维度分别向上移动 1。

希望这对您有所帮助。