【问题标题】:How to apply PCA to an image如何将 PCA 应用于图像
【发布时间】:2019-10-23 20:53:01
【问题描述】:

我有一张灰度噪声图像。我想应用PCA降噪,应用后看看输出。

这是我尝试做的:

[输入]:


from sklearn.datasets import load_sample_image
from sklearn.feature_extraction import image
from sklearn.decomposition import PCA
# Create patches of size 25 by 25 and create a matrix from all patches
patches = image.extract_patches_2d(grayscale_image, (25, 25), random_state = 42)
print(patches.shape)
# reshape patches because I got an error when applying fit_transform(ValueError: FoundValueError: Found array with dim 3. Estimator expected <= 2.)
patches_reshaped = patches.reshape(2,-1)
#apply PCA
pca = PCA()
projected = pca.fit_transform(patches_reshaped.data)
denoised_image = pca.inverse_transform(projected)
imshow(denoised_image)

[出]:


(来源:imggmi.com

结果我得到了一个数组。如何查看去噪图像?

【问题讨论】:

    标签: python pca noise-reduction


    【解决方案1】:

    为了查看去噪图像,您需要将使用主成分以某种低维表示的数据转换回原始空间。为此,您可以使用inverse_transform() 函数。从文档here 中可以看到,该函数将接受投影数据并返回一个与原始图像类似的数组。所以你可以做类似的事情,

    denoised_image = pca.inverse_transform(projected)
    # then view denoised_image
    

    编辑:

    以下是一些需要研究的问题:

    1. 您有来自原始图像的53824 补丁,大小为(25,25)。为了重塑您的数据并将其传递给 PCA,正如您从文档 here 中看到的那样,您需要传递一个大小为 (n_samples, n_features) 的数组。您的样本数量为 53824。因此,重新整形的补丁应该是:
    patches_reshaped = patches.reshape(patches.shape[0],-1)
    # this should return a (53824, 625) shaped data
    
    1. 现在您可以使用此重新整形的数据并使用 PCA 和逆变换对其进行转换,以获取原始域中的数据。之后,您的denoised_image 是一组重建的补丁。您将需要组合这些补丁以使用函数image.reconstruct_from_patches_2d 获取图像here 是文档。所以你可以做类似的事情,
    denoised_image = image.reconstruct_from_patches_2d(denoised_image.reshape(-1,25,25), grayscale_image.shape)
    

    现在您可以查看denoised_image,它应该看起来像grayscale_image

    【讨论】:

    • 有没有办法在我的投影图像中查看特征向量?应该在做inverse_transform之前还是之后做?
    • 您可以将特征向量重塑为您的图像大小(h,w)并显示它们,在人脸检测的情况下称为特征脸。但这些图像看起来不像自然图像。您还可以做的另一件事是仅使用感兴趣的特征向量进行逆变换,并查看解释了多少方差或查看重构误差。
    • 我在执行 inverse_transform 时得到的是一条线而不是图像。我所做的是按照问题中的说明在我的末尾添加了您的代码行。然后使用 imshow(denoised_image) 显示图像
    • 当你显示patches_reshaped 时你会得到什么?您实际上是在重建这些数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 2019-09-19
    • 2017-11-02
    • 2019-10-04
    • 2020-03-25
    • 2012-02-18
    相关资源
    最近更新 更多