Python中的SVD图像重建

2024-05-23 17:02:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图对这幅图像进行奇异值分解:

enter image description here

取前10个值。我有以下代码:

from PIL import Image
import numpy as np

img = Image.open('bee.jpg')
img = np.mean(img, 2)
U,s,V = np.linalg.svd(img)
recon_img = U @ s[1:10] @ V

但当我运行它时,它会抛出以下错误:

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 9 is different from 819)

所以我觉得我在重建的时候做错了什么。我不确定np.linalg.svd(img)创建的矩阵的维度。 我怎样才能解决这个问题

对不起,我说的是英语


Tags: 代码from图像imageimportnumpyimgpil
1条回答
网友
1楼 · 发布于 2024-05-23 17:02:18

问题是s的维度,如果打印UsV维度,我会得到:

print(np.shape(U))
print(np.shape(s))
print(np.shape(V))

(819, 819)
(819,)
(1024, 1024)

所以UV是方矩阵,s是一个数组。您必须创建一个矩阵,其尺寸与图像相同(819 x 1024),主对角线上有s,如下所示:

n = 10
S = np.zeros(np.shape(img))
for i in range(0, n):
    S[i,i] = s[i]
print(np.shape(S))

输出:

(819, 1024)

然后你可以继续你的阐述。要进行比较,请检查以下代码:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

img = Image.open('bee.jpg')
img = np.mean(img, 2)

U,s,V = np.linalg.svd(img)

n = 10
S = np.zeros(np.shape(img))
for i in range(0, n):
    S[i,i] = s[i]

recon_img = U @ S @ V

fig, ax = plt.subplots(1, 2)

ax[0].imshow(img)
ax[0].axis('off')
ax[0].set_title('Original')

ax[1].imshow(recon_img)
ax[1].axis('off')
ax[1].set_title(f'Reconstructed n = {n}')

plt.show()

这给了我:

enter image description here

相关问题 更多 >