python - 为 PCA 准备图像数据

标签 python scikit-learn pca

嗨,我尝试对一个包含许多图片的文件夹 (.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/

相关文章:

python - SciKit Learn - SGDClassifier 准确性不佳

python - 同时调用SKLearn的cross_val_score和cross_val_predict?

r - biplot R 中特定点的文本标签

python - 对包含元组的元组进行排序

Python 池 生成池

python - 检查列表中是否有三个数字加起来等于目标

python - Pandas数据布局问题

python - 使用 xlsxwriter python 进行字符串验证

python - 使用 Python 进行多元多项式回归

python - 如何获取 PCA 的权重