如何在 Python 中将一维图像数组转换为 PIL 图像

how to convert a 1-dimensional image array to PIL image in Python

我的问题与 Kaggle data science competition 有关。我正在尝试从包含 1 位灰度 像素信息(0 到 255) 的一维数组中读取图像 28x28 图像。所以数组是从 0 到 783,其中每个像素被编码为 x = i * 28 + j.

转换成二维28x28矩阵这样:

000 001 002 003 ... 026 027
028 029 030 031 ... 054 055
056 057 058 059 ... 082 083
 |   |   |   |  ...  |   |
728 729 730 731 ... 754 755
756 757 758 759 ... 782 783

出于图像处理(调整大小、倾斜)的原因,我想将该数组读入内存中的 PIL 图像。我对 Matplotlib image function, which I think is most promising. Another idea is the Numpy image functions.

做了一些研究

我正在寻找的 是一个代码示例,它向我展示了如何通过 Numpy 或 Matplotlib 或其他任何方式加载一维数组。或者如何使用 Numpy.vstack 将该数组转换为二维图像,然后将其作为图像读取。

您可以使用 Image.fromarray:

将 NumPy 数组转换为 PIL 图像
import numpy as np
from PIL import Image 

arr = np.random.randint(255, size=(28*28))
img = Image.fromarray(arr.reshape(28,28), 'L')

L模式表示数组值代表亮度。结果将是灰度图像。