對數變換的通用形式爲:,其中c是一個常數,
由對數函數的性質可知,改變換將範圍較窄的低灰度值映射爲較寬範圍的灰度值,相反地,對高輸入灰度值也是如此。
我們使用這種類型的變換來擴展圖像中,暗像素的值,同時壓縮更高灰度級的值。反對數變換的作用與此相反。
下面用Python實現圖像的對數變換:
使用的圖片數據爲:
導入要使用的第三方庫:
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import math
讀取圖片並可視化:
img = Image.open('小亮點.jpg')
plt.axis('off')
plt.imshow(img)
plt.show()
將圖像數據轉換爲numpy數組:
img_data = np.array(img)
定義變換函數:
def logarithm_transformation(img, func):
img_data = np.array(img)
a = np.shape(img_data)
new_img = []
for i in range(a[0]):
new_row = []
for j in range(a[1]):
data = list(img_data[i][j])
new_data = func(data)
new_row.append(np.array(new_data))
new_img.append(np.array(new_row))
return new_img
def function(data):
new_data = []
for k in data:
a = int(1*math.log(1+k))
new_data.append(a)
return new_data
調用,並可視化結果:
new_img = logarithm_transformation(img, function)
new_img = np.array(new_img)
new_img = Image.fromarray(new_img.astype('uint8')).convert('RGB')
plt.figure(figsize=(72,128))
plt.subplot(121)
plt.axis('off')
gray1 = new_img.convert('L')
plt.imshow(gray1, cmap='gray')
plt.subplot(122)
plt.axis('off')
plt.imshow(img, cmap='gray')
plt.show()
該例子中使用的參數c=1:
左側爲目標結果圖像,右側爲原圖像