矩阵变成图片,这个问题使用(python , matplotlib ) 可以轻松实现。

import matplotlib.pyplot as plt
#使用格式
plt.imshow(x)#其中x为图片的像素矩阵。

其中的x为:

array-like or PIL image
Supported array shapes are:
(M, N): an image with scalar data. The values are mapped to colors using normalization and a colormap. See parameters norm, cmap, vmin, vmax.
(M, N, 3): an image with RGB values (0-1 float or 0-255 int).
(M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency.
The first two dimensions (M, N) define the rows and columns of the image.
Out-of-range RGB(A) values are clipped.

从上面我们可以看到,其只支持的矩阵形式为:

(M, N)
(M, N, 3)
(M, N, 4)

所以如果我们要把手写数字识别中的图片(1,28,28)矩阵绘制成图片,需要把其压缩一个维度(28,28)

否则报错:

TypeError: Invalid shape (1, 28, 28) for image data

在这里插入图片描述

正确的应该如下:

print(img.shape)
plt.imshow(img.squeeze(0))#把0维度去掉。

在这里插入图片描述

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐