灰度變換¶
1. 灰度變換概述¶
灰度變換是指根據某種目標條件按一定變換關系逐點改變源圖像中每一個像素灰度值的方法。目的是為了改善畫質,使圖像的顯示效果更加清晰。 圖像的灰度變換處理是圖像增強處理技術中的一種非常基礎、直接的空間域圖像處理方法,也是圖像數字化軟件和圖像顯示軟件的一個重要組成部分。
常用的灰度變換有:
- 反色變化
- 對數變換
- 伽馬變換
2. 反色變換¶
圖像的反色變換,即圖像反轉,將黑色像素點變白色,白色像素點變黑色。廣義的反色變換也可以應用於彩色圖像,即對所有像素點取補。圖像的反轉處理可以增強暗色區域中的白色或灰色細節。
變換公式:
output = max(input) - input
2.1. 環境准備¶
In [1]:
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
2.2. 矩陣變換¶
定義一個矩陣:
In [2]:
mat = np.asarray([[160,0,120],
[20,60,150],
[10,90,160]])
In [3]:
mat
Out[3]:
array([[160, 0, 120],
[ 20, 60, 150],
[ 10, 90, 160]])
反色變換:
In [4]:
outmat = np.max(mat) - mat
解釋:
- np.max()會求出矩陣中的最大數
- 一個數去減去一個矩陣時,numpy的廣播機制會將將這個數轉變為這個數對應的矩陣(詳見廣播機制)
In [5]:
outmat
Out[5]:
array([[ 0, 160, 40],
[140, 100, 10],
[150, 70, 0]])
2.3.圖像變換¶
這個一張X光照片:
In [6]:
img = Image.open('./image/X.jpg')
img.show()
轉換為Numpy數組:
In [7]:
img_mat = np.asarray(img)
In [8]:
img_mat
Out[8]:
array([[ 26, 27, 32, ..., 239, 238, 238],
[ 34, 30, 40, ..., 239, 238, 238],
[ 33, 26, 39, ..., 238, 238, 238],
...,
[ 31, 30, 30, ..., 30, 30, 30],
[ 31, 30, 30, ..., 30, 30, 30],
[ 31, 30, 30, ..., 30, 30, 30]], dtype=uint8)
反色變換:
In [9]:
out_img = np.max(img_mat) - img_mat
In [10]:
out_img
Out[10]:
array([[229, 228, 223, ..., 16, 17, 17],
[221, 225, 215, ..., 16, 17, 17],
[222, 229, 216, ..., 17, 17, 17],
...,
[224, 225, 225, ..., 225, 225, 225],
[224, 225, 225, ..., 225, 225, 225],
[224, 225, 225, ..., 225, 225, 225]], dtype=uint8)
使用pyplot繪制:
In [11]:
fig, ax = plt.subplots()
im = ax.imshow(out_img, cmap="gray")
plt.show()
對比顯示:
In [12]:
fig, axs = plt.subplots(ncols=2, sharex=True)
axs[0].set_title('origin')
axs[0].imshow(img_mat, cmap="gray")
axs[1].set_title('reverse')
axs[1].imshow(out_img, cmap="gray")
plt.show()
注意:
- pyplot的具體使用參考官網示例
- set_title()中盡量使用英文,如需使用中文,請確保你的OS中有相應字體並設置
具體可參考Python 之 plt.rcParams[]
plt.rcParams['font.sans-serif'] = 'SimHei' plt.rcParams['axes.unicode_minus'] = False
- set_title()中盡量使用英文,如需使用中文,請確保你的OS中有相應字體並設置
2.4.opencv中的反色變換¶
In [13]:
import cv2 as cv
In [14]:
fig, axs = plt.subplots(ncols=2, sharex=True)
axs[0].set_title('origin')
axs[0].imshow(cv.imread("./image/X.jpg"), cmap="gray")
axs[1].set_title('reverse')
axs[1].imshow(cv.bitwise_not(cv.imread("./image/X.jpg")), cmap="gray")
plt.show()
3. 對數變換¶
對數變換將輸入中范圍較窄的低灰度值映射為輸出中范圍較寬的灰度值,或將輸入中范圍較寬的高灰度值映射為輸出中范圍較窄的灰度值,如圖所示:
(圖像來源)
對數變換公式:
output = log(1 + input)
注意:1是為了保證真數不為0
3.1.環境准備¶
In [15]:
import numpy as np
import matplotlib.pyplot as plt
3.2.矩陣變換¶
定義一個矩陣:
In [16]:
mat = np.asarray([[10,200],
[300,25500]])
In [17]:
mat
Out[17]:
array([[ 10, 200],
[ 300, 25500]])
對數變換:
In [18]:
out_mat = np.log(mat)
In [19]:
out_mat
Out[19]:
array([[ 2.30258509, 5.29831737],
[ 5.70378247, 10.14643373]])
3.3.圖像顯示¶
In [20]:
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax1.set_title('origin')
ax1.imshow(mat, cmap='gray')
ax2 = fig.add_subplot(122)
ax2.set_title('log')
ax2.imshow(out_mat, cmap='gray')
plt.show()
可以看到:對數變換,將邊緣的差距擴大了,但是將中間的差距壓縮了
