python - Python 中的 SVD 图像重建

标签 python python-3.x image numpy svd

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

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

对不起英语

最佳答案

问题是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

关于python - Python 中的 SVD 图像重建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62832360/

相关文章:

python - 当输入不分隔python时创建一个字符串列表

python - 打印除第一行以外的 csv 行

python-3.x - 如何在 async def 函数中正确使用 asyncio.create_subprocess_shell()?

image - 将 (SVG-) 图像添加到 R 中的现有图形

python - 如何在 matplotlib 的 map 中插入比例尺

python - 在 Python 中存储集合数据的最佳方式是什么?

python - 如何解决错误 FileNotFoundError : [WinError 2] The system cannot find the file specified when using ffmpeg-python?

python - 如何使用小的单个图像并在整个窗口中重复它以使用 tkinter GUI 使其成为背景图像?

Swift 图像名称比较

Java 从文件读取/写入 BufferedImage 性能与内存的比较