---
# System prepended metadata

title: image process HW1

---

# image process HW1
## 題目
準備兩張圖片，一張是英文字母或數字，一張是風景照。(512*512)
![](https://i.imgur.com/s1jsFhB.jpg =200x)  ![](https://i.imgur.com/2T22d9F.png =200x)
將兩張圖順時針旋轉30度，並利用nearest neighbor interpolation和 bilinear interpolation 兩種插值法完成圖片的空缺。

## 方法
### rotation
首先要先設定背景，因為圖片旋轉後同樣的像素無法包含全部的圖片，根據兩邊和 = 斜邊*(cos+sin)推得

```=python
new_w = np.around(np.abs(w*sin - h*cos)).astype(int)
new_h = np.around(np.abs(w*cos - h*sin)).astype(int)
```
旋轉公式
![](https://i.imgur.com/S0A3OHy.png)
用三層for迴圈依序找出座標和channel，並套入公式找出旋轉後座標
```=python
for i in range(0, new_img.shape[0]):
            for j in range(-256, new_img.shape[1]-256):
                for k in range(0, new_img.shape[2]):
                    x = i*cos + j*sin
                    y = j*cos - i*sin
                    z = k
                    new_img[i][j+256][k]=img[x][y][z]
```
### nearest neighbor interpolation
旋轉後得出的座標是小數，將座標取四捨五入得最近值
```=python
x = np.around(x).astype(int)
y = np.around(y).astype(int)
```
### bilinear interpolation
```
$x1 = (0，0) + d1 * ((1，0) – (0，0))$ $x2 = (0，1) + d1 * ((1，1) – (0，1))$ $(x，y)= x1+ d3 * (x1- x2)$
```
![](https://i.imgur.com/MQ0vpDn.png)
```=python
x = np.around(x).astype(int)
y = np.around(y).astype(int)
xa = np.floor(x).astype(int)
ya = np.floor(y).astype(int)
xb = np.ceil(x).astype(int)
yb = np.ceil(y).astype(int)
x1 = int(img[xa][ya][z]) + (y-ya)*int(img[xa][yb][z]-img[xa][ya][z])
x2 = int(img[xb][ya][z]) + (y-ya)*int(img[xb][yb][z]-img[xb][ya][z])
new_img[i][j+256][k] = x1 + (x-xa)*(x2-x1)
```
### 結果
![](https://i.imgur.com/AFrGbZI.png)