如何将 PCA 应用于图像

How to apply PCA to an image

我有一张灰度噪点图像。我想申请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

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

为了查看去噪后的图像,您需要将使用主成分以低维表示的数据转换回原始数据 space。为此,您可以使用 inverse_transform() 函数。正如您从文档 here 中看到的那样,此函数将接受投影数据和 return 类似于原始图像的数组。所以你可以做类似的事情,

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