用前面编写的函数,分别对图像进行压缩并比较。具体要求如下: (1)利用PIL库或其他库读入图像example.jgp,并转化为ndarray格式。,。 (2)利用前面编写的函数,对图像进行矩阵分解。 (3)取其TOP-K(K分别为10,50,100)个特征值/奇异值,和对应的特征向量/奇异向量,重建图
时间: 2024-02-18 18:02:39 浏览: 97
好的,让我来回答你的问题。
首先,让我们先回顾一下前面编写的对矩阵进行压缩和重构的函数:
```python
def compress(matrix, k):
"""
Compresses a matrix by keeping only the top-k singular values/vectors
"""
U, s, V = np.linalg.svd(matrix)
return np.dot(U[:, :k], np.dot(np.diag(s[:k]), V[:k, :]))
def reconstruct(matrix, k):
"""
Reconstructs a matrix using the top-k singular values/vectors
"""
U, s, V = np.linalg.svd(matrix)
return np.dot(U[:, :k], np.dot(np.diag(s[:k]), V[:k, :]))
```
接下来,我们可以使用PIL库将图像加载并转换为ndarray格式。以下是示例代码:
```python
from PIL import Image
import numpy as np
# Load image
img = Image.open('example.jpg')
# Convert to numpy array
img_array = np.array(img)
```
接下来,我们可以使用前面编写的函数对图像进行矩阵分解和重构,并比较两种方法的压缩效果。以下是示例代码:
```python
# Perform SVD on image matrix
U, s, V = np.linalg.svd(img_array)
# Initialize lists to store MSE values
mse_svd_list = []
mse_reconstruct_list = []
# Loop over different values of k
for k in [10, 50, 100]:
# Compress image using SVD
img_compressed_svd = compress(img_array, k)
# Reconstruct image using SVD
img_reconstructed_svd = reconstruct(img_array, k)
# Compute mean squared error (MSE) between original and compressed image
mse_svd = np.mean((img_array - img_compressed_svd)**2)
mse_svd_list.append(mse_svd)
# Compute mean squared error (MSE) between original and reconstructed image
mse_reconstruct = np.mean((img_array - img_reconstructed_svd)**2)
mse_reconstruct_list.append(mse_reconstruct)
# Save compressed and reconstructed images
Image.fromarray(np.uint8(img_compressed_svd)).save('compressed_svd_k{}.jpg'.format(k))
Image.fromarray(np.uint8(img_reconstructed_svd)).save('reconstructed_svd_k{}.jpg'.format(k))
# Print MSE values
print('MSE for compression using SVD:', mse_svd_list)
print('MSE for reconstruction using SVD:', mse_reconstruct_list)
```
以上就是回答你的问题的全部内容,希望能对你有所帮助。如果你还有其他问题,可以继续问我。
阅读全文
相关推荐
















