首页 > 解决方案 > 如何在二维数组中表示一组图像?

问题描述

我正在尝试从本地计算机上的路径读取图像文件,并且我想生成一个数组来表示这些图像。如何在维度为 2 的数组中表示它们。

images = [imageio.imread(path) for path in glob.glob([pathtoimages])]
images = np.asarray(images)
print(images.shape)
scaler = StandardScaler()

# Fit on training set only.
scaler.fit(images)
#
## Apply transform to both the training set and the test set.
#train_img = scaler.transform(images)

我正在按照本指南对一组全部为 257x257 的图像进行 PCA。当我打印(images.shape)时,我得到 (130, 257, 257, 3) 因为有 130 张 257x257 的图像和 3 个通道。当我尝试执行 StandardScaler 时,出现以下错误。

ValueError:找到暗淡为 4 的数组。StandardScaler 预期 <= 2。

我的主要问题是如何将大小为 4 的数组压缩为只有 2 维的数组?我已经有这篇文章这篇文章,但我仍然不确定。

此外,请确保在运行代码时替换 glob.glob() 函数中的 [pathtoimages]。

标签: pythonpython-3.ximageimage-processingpca

解决方案


您需要先将图像展平,然后再将其添加到列表中。所以你的大小 (257,257,3) 的图像将变成大小为 257*257*3 的一维数组

images = [np.array(imageio.imread(path)).flatten()  for path in glob.glob(pathtoimages)]
images = np.array(images)
print(images.shape)

推荐阅读