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

通过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
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值