python - 如何将 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)
[出去]:
(来源:imggmi.com)
结果我得到了一个数组。如何查看去噪图像?
解决方案
为了看到您的去噪图像,您需要将使用主成分以某种低维表示的数据转换回原始空间。为此,您可以使用该inverse_transform()
功能。正如您从此处的文档中看到的那样,此函数将接受投影数据并返回一个与原始图像类似的数组。所以你可以做类似的事情,
denoised_image = pca.inverse_transform(projected)
# then view denoised_image
编辑:
以下是一些需要研究的问题:
- 您
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
- 现在,您使用此重构数据并使用 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
。
推荐阅读
- javascript - JavaScript 通过 jsname 获取 Input 中的元素值
- html - html中文本的位置
- javascript - 类型应该是 javascript 数组之一 - Typescript
- sql - 我需要一个查询,选择出生日期从两年前的 1 月 1 日到昨天的个人
- powershell - Powershell:根据日期范围获取事件日志
- jquery - jReject:jQuery 浏览器拒绝 - 未加载图像
- java - kubernetes: image can't be pulled
- electron - Getting Cypress to run Headless Electron with Chrome DevTools Protocol
- bolt-cms - 邮件选项的测试设置(用于 bolt_auth)
- java - 响应自定义 JSON 返回,该 JSON 返回经过验证的响应以在 BD Spring Boot 中执行存储过程