---
# System prepended metadata

title: '*2022/05/03 影像處理 HW08*'
tags: [影像處理]

---

###### tags: `影像處理`
# *2022/05/03 影像處理 HW08*
## Coding Part
### 實戰(1)
#### 題目：
![](https://i.imgur.com/HdbIxHb.png)

#### 程式碼：
```
#實戰(1)
import numpy as np
import cv2
import math
from numpy.random import *
from matplotlib import pyplot as plt
from google.colab import drive
from google.colab.patches import *

drive.mount('/content/drive')
image_1 = cv2.imread("/content/drive/My Drive/Colab Notebooks/imgs/Pattern.bmp",-1)

def gaussian_noise(f,scale):
    g = f.copy()
    nr,nc = f.shape[:2]
    for x in range(nr):
        for y in range(nc):
            value = f[x,y] + normal(0,scale)
            g[x,y] = np.uint8(np.clip(value,0,255))
    return g

def histogram(img):
    if img.ndim!=3:
        hist = cv2.calcHist([img],[0],None,[256],[0,256])
    else:
        gray_img = cv2.cvtColor(img,cv.COLOR_BGR2GRAY)
        hist = cv2.calHist([gray_img],[0],None,[256],[0,256])
    return hist

def std_dev(f1,f2):
    array_1 = f1.copy()
    array_2 = f2.copy()
    array_3 = array_2-array_1
    st_dev = np.std(array_3)
    return st_dev
    

image_G_1 = gaussian_noise(image_1,30)
avi_1 = cv2.blur(image_G_1,(5,5))

#顯示Picture_01
titles=['image_G_1','Histogram','Average Image','Average Image Histogram']
plt.figure(figsize=(25,5))
plt.subplot(141)
plt.title(titles[0],fontsize=15,color='r')
plt.imshow(image_G_1,'gray')
plt.subplot(142)
plt.title(titles[1],fontsize=15,color='r')
plt.hist(image_G_1.ravel(),256,[0,256])
plt.xlim([0,256])
plt.xlabel('Intensity')
plt.ylabel('#Intensities')
plt.subplot(143)
plt.title(titles[2],fontsize=15,color='r')
plt.imshow(avi_1,'gray')
plt.subplot(144)
plt.title(titles[3],fontsize=15,color='r')
plt.hist(avi_1.ravel(),256,[0,256])
plt.xlim([0,256])
plt.xlabel('Intensity')
plt.ylabel('#Intensities')

plt.tight_layout()
plt.show()

array = np.zeros((400,400))
std_dev_1 = std_dev(array,image_1)
print("The original std ",std_dev_1)
print("\n")
std_dev_3 = std_dev(image_G_1,avi_1)
print("Average Image Noise std",std_dev_3)
```
#### 輸出結果：
![](https://i.imgur.com/51Zlr2V.png)
The original std  76.729409900963
Average Image Noise std 106.72345016091532

### 實戰（2）
#### 題目：
![](https://i.imgur.com/TGEZdK7.jpg)
#### 程式碼：
```
#實戰(2)
import numpy as np
import cv2
import math
from numpy.random import *
from numpy.fft import*
from matplotlib import pyplot as plt
from google.colab import drive
from google.colab.patches import *

drive.mount('/content/drive')
image_1 = cv2.imread("/content/drive/My Drive/Colab Notebooks/imgs/IMG_0120.jpeg",0)

def fourier_spectrum(f):
    F = fft2(f)
    Fshift = fftshift(F)
    mag = np.abs(Fshift)
    mag = mag/mag.max()*255.0*100.0
    g = np.uint8(np.clip(mag,0,255))
    return g

def periodic_noise(f,scale,frequency,angle):
    g = f.copy()
    nr,nc = f.shape[:2]

    fp = np.zeros([nr,nc])
    for x in range(nr):
        for y in range(nc):
            fp[x,y] = pow(-1,x+y) * f[x,y]
    F = fft2(fp)
    G = F.copy()

    magnitude = np.sum(F)*scale
    for theta in range(0,360,angle):
        u = int(frequency*np.cos(theta*np.pi/180)+nr/2)
        v = int(frequency*np.sin(theta*np.pi/180)+nr/2)
        G[u,v]=magnitude
    
    gp = ifft2(G)

    gp2 = np.zeros([nr,nc])
    for x in range(nr):
        for y in range(nc):
            gp2[x,y]=round(pow(-1,x+y)*np.real(gp[x,y]),0)
    g = np.uint8(np.clip(gp2,0,255))

    return g

#Picture scale:0.05 frequency:100 angle:45
img_noise = periodic_noise(image_1, 0.05, 100, 45)
img_noise_spectrum = fourier_spectrum(image_1)
images = [image_1,img_noise,img_noise_spectrum]
titles = ['Original','scale:0.05 frequency:100 angle:45','Perodic Noise Spectrum']
plt.figure(figsize=(15,5))
for i in range(3):
    plt.subplot(1,3,i+1),plt.imshow(images[i],cmap='gray')
    plt.title(titles[i],fontsize=15,color='r')

#Picture scale:0.1 frequency:200 angle:45
img_noise = periodic_noise(image_1, 0.1, 200, 45)
img_noise_spectrum = fourier_spectrum(image_1)
images = [image_1,img_noise,img_noise_spectrum]
titles = ['Original','scale:0.1 frequency:200 angle:45','Perodic Noise Spectrum']
plt.figure(figsize=(15,5))
for i in range(3):
    plt.subplot(1,3,i+1),plt.imshow(images[i],cmap='gray')
    plt.title(titles[i],fontsize=15,color='r')
plt.tight_layout()
plt.show()
```
#### 輸出結果：
![](https://i.imgur.com/qKAbty8.png)
![](https://i.imgur.com/p2q4SRF.png)

## 簡答題：
![](https://i.imgur.com/4vpQjNe.png)

1. 第一題
* 均勻雜訊
* 高斯雜訊
* 指數雜訊
* 瑞雷雜訊
* 脈衝雜訊
* 白雜訊

2. 第二題
* g(x,y)=h(x,y)＊f(x,y)+n(x,y),h(x,y)表示失真函數，n(x,y)表示雜訊，為卷積

3. 第三題
* 雜訊是在每個像素生成隨機數，與原有的像素值做運算
* 在影像處理上，可以透過加入雜訊，分析圖片的組成，再透過分析出來的結果，將影像優化還原

4. 第四題
* 無法正確找到公式
