# NumPy实现多维数组中的线性代数

• 简介

• 图形加载和说明

• 图形的灰度

• 灰度图像的压缩

• 原始图像的压缩

• 总结

## 图形加载和说明

```import imageio
print(type(img))
```

`class 'imageio.core.util.Array'`

```import matplotlib.pyplot as plt
plt.imshow(img)
```

## 图形的灰度

```red_array = img_array[:, :, 0]
green_array = img_array[:, :, 1]
blue_array = img_array[:, :, 2]
```

```Y=0.2126R + 0.7152G + 0.0722B
```

``` img_gray = img_array @ [0.2126, 0.7152, 0.0722]
```

`plt.imshow(img_gray, cmap="gray")`

## 灰度图像的压缩

www.cppcns.com

A=UVT

`U, s, Vt = linalg.svd(img_gray)`

```# 重建
import numpy as np
Sigma = np.zeros((80, 170))
for i in range(80):
Sigma[i, i] = s[i]
```

```linalg.norm(img_gray - U @ Sigma @ Vt)
```

```np.allclose(img_gray, U @ Sigma @ Vt)
```

```k = 10
approx = U @ Sigma[:, :k] @ Vt[:k, :]
plt.imshow(approx, cmap="gray")
```

## 原始图像的压缩

```img_array_transposed = np.transpose(img_array, (2, 0, 1))
print(img_array_transposed.shape)

U, s, Vt = linalg.svd(img_array_transposed)
print(U.shape, s.shape, Vt.shape)```

```Sigma = np.zeros((3, 80, 170))

for j in range(3):
np.fill_diagonal(Sigma[j, :, :], s[j, :])

reconstructed = U @ Sigma @ Vt
print(reconstructed.shape)

plt.imshow(np.transpose(reconstructed, (1, 2, 0)))```

```approx_img = U @ Sigma[..., :k] @ Vt[..., :k, :]
print(approx_img.shape)
plt.imshow(np.transpose(approx_img, (1, 2, 0)))```