首页 > 解决方案 > 如何将 PCA 应用于图像

问题描述

我有一个灰度嘈杂的图像。我想应用 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)

[出去]:

pca_result
(来源:imggmi.com

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

标签: pythonpcanoise-reduction

解决方案


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

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

编辑:

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

  1. 53824的原始图像中有尺寸为 的补丁(25,25)。为了重塑您的数据并将其传递给 PCA,正如您从此处的文档中看到的那样,您需要传递一个 size 的数组(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 这里的函数获取图像是文档。所以你可以做类似的事情,
denoised_image = image.reconstruct_from_patches_2d(denoised_image.reshape(-1,25,25), grayscale_image.shape)

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


推荐阅读