Python中的SVD图像重建

4

我正在尝试对这张图片进行奇异值分解:

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)创建的矩阵的维度是什么。 该如何解决?

对于英语我很抱歉。

1个回答

1
问题在于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()

which give me this:

enter image description here


2
你也可以使用 np.diag(s) 来跨越对角线,这可能更快且更易于阅读。 - code-lukas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接