嗨,我尝试对一个包含许多图片的文件夹 (.jpg) 应用 PCA。但是,我坚持将其转换为 scikit-learn PCA 接受的格式。看来PCA采用数组数据格式。我读过类似PCA for image data的文章但对我来说看起来很复杂。我只想将图像转换为可接受的格式,然后使用 pca.fit
之前我使用 os.walk 将图像更改为灰度并调整其大小(如下所示)。我想知道我是否也可以在 PCA 上使用它。
from sklearn.decomposition import PCA
from PIL import Image
import os
import numpy as np
WORK_DIR = 'D:/folder/' #working folder
source = os.path.join(WORK_DIR, 'train')
target = os.path.join(WORK_DIR, 'gray')
for root, dirpath, filenames in os.walk(source):
for file in filenames:
image_file = Image.open(os.path.join(root, file))
image_file.draft('L', (256, 128))
image_file.save(os.path.join(target, file))
任何其他更简单的方法也很棒。
最佳答案
读取图像数据后,它是一个二维数组。您必须将其展平,.flatten()
可以做到这一点。现在您可以将此数据用于 pca.fit()
。
from sklearn.decomposition import PCA
from PIL import Image
import os
import numpy as np
WORK_DIR = 'D:/folder/' #working folder
source = os.path.join(WORK_DIR, 'train')
target = os.path.join(WORK_DIR, 'gray')
train_data=[]
for root, dirpath, filenames in os.walk(source):
for file in filenames:
image_file = os.path.join(root, file)
print(image_file)
train_data.append(np.array(Image.open(image_file,'r')).flatten())
pca=PCA()
pca.fit(train_data)
关于python - 为 PCA 准备图像数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53974427/