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

Mat*_*ias 2 python numpy image matplotlib python-imaging-library

我的问题与Kaggle 数据科学竞赛有关。我正在尝试从包含28x28 图像的1 位灰度像素信息(0 到 255)的一维数组中读取图像。因此数组从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
Run Code Online (Sandbox Code Playgroud)

出于图像处理(调整大小、倾斜)的原因,我想将该数组读入内存中的 PIL 图像。我对Matplotlib 图像函数做了一些研究,我认为这是最有前途的。另一个想法是Numpy 图像函数

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

unu*_*tbu 5

您可以使用以下方法将 NumPy 数组转换为 PIL 图像Image.fromarray

import numpy as np
from PIL import Image 

arr = np.random.randint(255, size=(28*28))
img = Image.fromarray(arr.reshape(28,28), 'L')
Run Code Online (Sandbox Code Playgroud)

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

  • @Santhosh:要转换 BGR --> RGB,您可以使用 [`img = img[..., ::-1]`](/sf/ask/326309021/ -bgr-rgb#comment76959337_9641163)。 (2认同)