這里寫目錄標題
- 本節的目標
- 背景
- 灰度變換和空間濾波基礎
本節的目標
- 了解空間域圖像處理的意義,以及它與變換域圖像處理的區別
- 熟悉灰度變換所有的主要技術
- 了解直方圖的意義以及如何操作直方圖來增強圖像
- 了解空間濾波的原理
import sys
import numpy as np
import cv2
import matplotlib
import matplotlib.pyplot as plt
import PIL
from PIL import Imageprint(f"Python version: {sys.version}")
print(f"Numpy version: {np.__version__}")
print(f"Opencv version: {cv2.__version__}")
print(f"Matplotlib version: {matplotlib.__version__}")
print(f"Pillow version: {PIL.__version__}")
Python version: 3.6.12 |Anaconda, Inc.| (default, Sep 9 2020, 00:29:25) [MSC v.1916 64 bit (AMD64)]
Numpy version: 1.16.6
Opencv version: 3.4.1
Matplotlib version: 3.3.2
Pillow version: 8.0.1
def normalize(mask):return (mask - mask.min()) / (mask.max() - mask.min() + 1e-5)
背景
灰度變換和空間濾波基礎
g(x,y)=T[f(x,y)](3.1)g(x, y) = T[f(x, y)] \tag{3.1} g(x,y)=T[f(x,y)](3.1)
式中f(x,y)f(x, y)f(x,y)是輸入圖像, g(x,y)g(x, y)g(x,y)是輸出圖像,TTT是在點(x,y)(x, y)(x,y)的一個鄰域上定義的針對f的算子。
最小的鄰域大小為1×11\times 11×1
則式(3.1)中的TTT稱為灰度(也稱灰度級或映射)變換函數,簡寫為如下:
s=T(r)(3.2)s=T(r) \tag{3.2}s=T(r)(3.2)
對比度拉伸
- 通過將kkk以下的灰度級變暗,并將高于kkk的灰度級變亮,產生比原圖像對比度更高的一幅圖像
閾值處理函數
- 小于kkk的處理為0,大于kkk的設置為1,產生一幅二級(二值)圖像
# 顯示一個圖像的3x3鄰域
height, width = 18, 18
img_ori = np.ones([height, width], dtype=np.float)# 圖像3x3=9個像素賦了不同的值,以便更好的顯示
kernel_h, kernel_w = 3, 3
img_kernel = np.zeros([kernel_h, kernel_w], dtype=np.float)
for i in range(img_kernel.shape[0]):for j in range(img_kernel.shape[1]):img_kernel[i, j] = 0.3 + 0.1 * i + 0.1 * j
img_kernel[kernel_h//2, kernel_w//2] = 0.9img_ori[5:5+kernel_h, 12:12+kernel_w] = img_kernelfig = plt.figure(figsize=(7, 7), num='a')
plt.matshow(img_ori, fignum='a', cmap='gray', vmin=0, vmax=1)
plt.show()
為什么會把Sigmoid函數寫在這里
從Sigmoid函數的圖像曲線來看,與分段線性函數的曲線類似,所以在一定程度上可以用來代替對比度拉伸,這樣就不需要輸入太多的參數。當然,有時可能也得不到想要的結果,需要自己多做實驗。
sigmoid函數也是神經網絡用得比較多的一個激活函數。
def sigmoid(x, scale):"""simgoid fuction, return ndarray value [0, 1]param: input x: array like param: input scale: scale of the sigmoid fuction, if 1, then is original sigmoid fuction, if < 1, then the values between 0, 1will be less, if scale very low, then become a binary fuction; if > 1, then the values between 0, 1 will be more, if scalevery high then become a y = x"""y = 1 / (1 + np.exp(-x / scale))return y
# sigmoid fuction plot
x = np.linspace(0, 10, 100)
x1 = x - x.max() / 2 # Here shift the 0 to the x center, here is 5, so x1 = [-5, 5]
t_stretch = sigmoid(x1, 1)
t_binary = sigmoid(x1, 0.001)plt.figure(figsize=(10, 5))
plt.subplot(121), plt.plot(x, t_stretch), plt.title('s=T(r)'), plt.ylabel('$s_0 = T(r_0)$', rotation=0)
plt.xlabel('r'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.plot(x, t_binary), plt.title('s=T(r)'), plt.ylabel('$s_0 = T(r_0)$', rotation=0)
plt.xlabel('r'), plt.xticks([]), plt.yticks([])
plt.tight_layout
plt.show()