图像 pca matlab代码
时间: 2023-09-19 18:12:14 浏览: 37
以下是使用MATLAB实现图像PCA的示例代码:
```matlab
% 读取图像
img = imread('lena.png');
% 将图像转换为灰度图
gray_img = rgb2gray(img);
% 将图像转换为矩阵
img_matrix = double(gray_img);
% 计算均值
mean_img = mean(img_matrix);
% 将每个像素减去均值
centered_img = img_matrix - mean_img;
% 计算协方差矩阵
covariance_matrix = cov(centered_img);
% 计算特征向量和特征值
[eigenvectors, eigenvalues] = eig(covariance_matrix);
% 将特征向量按特征值从大到小排序
[~, order] = sort(diag(eigenvalues), 'descend');
eigenvectors = eigenvectors(:, order);
% 选择前10个特征向量
selected_eigenvectors = eigenvectors(:, 1:10);
% 计算新的特征空间
new_space = centered_img * selected_eigenvectors;
% 重建图像
reconstructed_img = new_space * selected_eigenvectors' + mean_img;
% 显示原始图像和重建图像
subplot(1, 2, 1), imshow(uint8(img_matrix));
title('Original Image');
subplot(1, 2, 2), imshow(uint8(reconstructed_img));
title('Reconstructed Image');
```
请注意,此代码仅演示如何使用PCA对图像进行降维和重建,实际应用中可能需要进行更多的处理,例如对降维后的特征向量进行压缩和存储。