这里写自定义目录标题
通过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