图像矩阵M的大小为4096 * 1200,一共400张图像,首先将400图像存为三个大小为4096 * 400的矩阵,再将三个矩阵拼接成4096*1200的矩阵MTry to apply the SVD method to factorize the matrix M,矩阵大小为KN into two low-rank matrices, namely matrix U,矩阵大小为Kd and matrix I,矩阵大小为dN, where d is an empirical parameter in practice which is set as 16 in this experiment. Please complete the following tasks. You can directly apply existing API in this quiz. (Please provide the code and results) Provide the singular values of the data . Provide the images by reshaping each column in the low-rank matrix U,矩阵大小为Kd of the data. Provide the first 20 reconstructed RGB face images corresponding to the reconstructed matrix UI,矩阵大小为K*N,in the report. python代码,中文注释。(不输出结果,只解释代码是如何实现的)
时间: 2024-03-11 14:48:59 浏览: 24
首先,将400张图像存为三个大小为4096 * 400的矩阵,代码如下:
```python
import numpy as np
import os
from PIL import Image
# 图像路径
img_path = "path/to/images"
# 图像大小
img_size = (4096, 1200)
# 一共有400张图像
img_num = 400
# 读取图像,并存储为三个大小为4096 * 400的矩阵
img_matrix_1 = np.zeros((img_size[0], img_num // 3))
img_matrix_2 = np.zeros((img_size[0], img_num // 3))
img_matrix_3 = np.zeros((img_size[0], img_num - 2 * (img_num // 3)))
for i in range(img_num):
img = Image.open(os.path.join(img_path, f"{i+1}.jpg"))
img = img.resize((img_size[1], img_size[0]))
img = np.array(img.convert("L"))
if i < img_num // 3:
img_matrix_1[:, i] = img
elif i < 2 * (img_num // 3):
img_matrix_2[:, i - img_num // 3] = img
else:
img_matrix_3[:, i - 2 * (img_num // 3)] = img
# 将三个矩阵拼接成4096*1200的矩阵
M = np.concatenate((img_matrix_1, img_matrix_2, img_matrix_3), axis=1)
```
接下来,对矩阵M进行SVD分解并获取奇异值、左奇异向量和右奇异向量,代码如下:
```python
# 对矩阵M进行SVD分解
K = 16
U, s, V = np.linalg.svd(M, full_matrices=False)
# 获取前K个奇异值
s_k = s[:K]
# 获取左奇异向量
U_k = U[:, :K]
# 对左奇异向量进行归一化处理
for i in range(K):
U_k[:, i] = U_k[:, i] * s_k[i]
# 获取右奇异向量
V_k = V[:K, :]
```
然后,将左奇异向量U_k的每一列视为一张图像,并将其reshape为原始图像的大小,代码如下:
```python
# 将左奇异向量U_k的每一列视为一张图像,并将其reshape为原始图像的大小
for i in range(K):
img = U_k[:, i]
img = np.reshape(img, img_size)
img = Image.fromarray(img.astype(np.uint8))
img.save(os.path.join(save_path, f"U_{i+1}.jpg"))
```
最后,使用左奇异向量U_k和右奇异向量V_k重构原始矩阵,并获取前20个重构后的RGB图像,代码如下:
```python
# 使用左奇异向量U_k和右奇异向量V_k重构原始矩阵
M_reconstruct = np.dot(U_k, V_k)
# 获取前20个重构后的RGB图像
for i in range(20):
img = M_reconstruct[:, i]
img = np.reshape(img, img_size)
img = Image.fromarray(img.astype(np.uint8))
img.save(os.path.join(save_path, f"reconstruct_{i+1}.jpg"))
```
其中,重构后的图像为灰度图像,如果需要显示为RGB图像,可以将灰度图像复制三份作为RGB三个通道的像素值。