图片压缩:SVD和PCA提取主成分使图片降维

3 篇文章 0 订阅

通过SVD降维,提取主成分并重构图片

大概思路:图片是长宽为 H,W的矩阵Mat, 那么Mat的特征数量为Max(H,W).

对Mat进行SVD分解: U, s, v = SVD(Mat). 即图中的 M = U.s.v。

在这里插入图片描述

然后提取U,diag(s)以及vt的前30个特征, 重构后图片如下(灰度图,若RGB则选择B通道):

在这里插入图片描述
代码如下:

import numpy as np
import matplotlib.pyplot as plt

mat = plt.imread("bird-7.jpg") # [660, 670, 3]
mat = mat[:,:,2]
print(mat.shape)

# SVD 
U, s, VT = np.linalg.svd(mat)
print(U.shape) #[660,660]
print(s.shape) #[660]
print(VT.shape) #[670,670]

Sigma = np.zeros((mat.shape[0], mat.shape[1]))
Sigma[:min(mat.shape[0], mat.shape[1]), :min(mat.shape[0], mat.shape[1])] = np.diag(s)

# Reconstruction of the matrix using the first 30 singular values
k = 30
mat_approx = U[:, :k] @ Sigma[:k, :k] @ VT[:k, :] #[660,670]

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,8))
plt.subplots_adjust(wspace=0.3, hspace=0.2)

ax1.imshow(mat, cmap='gray')
ax1.set_title("Original image")

ax2.imshow(mat_approx, cmap='gray')
ax2.set_title("Reconstructed image using the \n first {} singular values".format(k))
plt.show()

原图如下:
请添加图片描述

Reference

1.https://towardsdatascience.com/understanding-singular-value-decomposition-and-its-application-in-data-science-388a54be95d
2.https://en.wikipedia.org/wiki/Singular_value_decomposition

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PCA人脸图片降维及展示的步骤如下: 1. 读取人脸图片数据集,将图片转为灰度图并转换为二维矩阵。 2. 对矩阵进行均值中心化处理,即每个像素减去所有图片对应像素的平均值。 3. 计算协方差矩阵。 4. 对协方差矩阵进行特征值分解,得到特征向量和特征值。 5. 选择前k个特征向量,将原始图片矩阵投影到这k个特征向量上,得到新的降维后的矩阵。 6. 将降维后的矩阵反投影到原始空间,得到新的降维后的人脸图片。 7. 展示原始图片降维后的图片进行比较,观察是否丢失了重要信息。 下面是Python代码示例: ``` python import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import fetch_olivetti_faces from sklearn.decomposition import PCA # 读取人脸数据集 data = fetch_olivetti_faces() faces = data.images n_samples, h, w = faces.shape # 将图片转为二维矩阵 X = faces.reshape((n_samples, h * w)) # PCA降维 n_components = 100 pca = PCA(n_components=n_components, svd_solver='randomized', whiten=True) X_pca = pca.fit_transform(X) # 将降维后的矩阵反投影到原始空间 X_new = pca.inverse_transform(X_pca) # 将降维前后的图片进行比较 n_row, n_col = 2, 5 fig, axes = plt.subplots(n_row, n_col, figsize=(10, 4), sharex=True, sharey=True) for i in range(n_row): for j in range(n_col): k = i * n_col + j ax = axes[i, j] if i == 0: ax.imshow(faces[k], cmap='gray') ax.set_title("Original") else: ax.imshow(X_new[k].reshape(h, w), cmap='gray') ax.set_title("PCA") ax.axis('off') plt.tight_layout() plt.show() ``` 运行代码后,可以看到原始图片PCA降维后的图片进行了对比展示,观察是否丢失了重要信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值