python庫skimage 對圖像進行gamma校正和log校正

Gamma校正

Gamma校正是對輸入圖像灰度值進行的非線性操作,使輸出圖像灰度值與輸入圖像灰度值呈指數關係:
這個指數即爲Gamma。
Gamma校正的原理很簡單,就一個很簡單的表達式,如下圖所示:
伽馬校正公式
其中V_in的取值範圍是0~1,最重要的參數就是公式中的γ參數!
γ的值決定了輸入圖像和輸出圖像之間的灰度映射方式,即決定了是增強低灰度值區域還是增高灰度值區域。
γ>1時,圖像的高灰度區域對比度得到增強。
γ<1時,圖像的低灰度區域對比度得到增強。
γ=1時,不改變原圖像。
伽馬變換對於圖像對比度偏低,並且整體亮度值偏高(對於於相機過曝)情況下的圖像增強效果明顯。

對數log變換

log 函數的表達式:
y=alog(1+x), a 是一個放大係數,x 同樣是輸入的像素值,取值範圍爲 [0−1], y 是輸出的像素值。
對數變換對於整體對比度偏低並且灰度值偏低的圖像增強效果較好。

skimage庫實現gamam校正和log校正

函數:
Gamma:
gamma_corrected = exposure.adjust_gamma(img, 2)
Logarithmic:
logarithmic_corrected = exposure.adjust_log(img, 1)

"""
=================================
Gamma and log contrast adjustment
=================================

This example adjusts image contrast by performing a Gamma and a Logarithmic
correction on the input image.

"""
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

from skimage import data, img_as_float
from skimage import exposure

matplotlib.rcParams['font.size'] = 8


def plot_img_and_hist(image, axes, bins=256):
    """Plot an image along with its histogram and cumulative histogram.

    """
    image = img_as_float(image)
    ax_img, ax_hist = axes
    ax_cdf = ax_hist.twinx()

    # Display image
    ax_img.imshow(image, cmap=plt.cm.gray)
    ax_img.set_axis_off()

    # Display histogram
    ax_hist.hist(image.ravel(), bins=bins, histtype='step', color='black')
    ax_hist.ticklabel_format(axis='y', style='scientific', scilimits=(0, 0))
    ax_hist.set_xlabel('Pixel intensity')
    ax_hist.set_xlim(0, 1)
    ax_hist.set_yticks([])

    # Display cumulative distribution
    img_cdf, bins = exposure.cumulative_distribution(image, bins)
    ax_cdf.plot(bins, img_cdf, 'r')
    ax_cdf.set_yticks([])

    return ax_img, ax_hist, ax_cdf


# Load an example image
img = data.moon()

# Gamma
gamma_corrected = exposure.adjust_gamma(img, 2)

# Logarithmic
logarithmic_corrected = exposure.adjust_log(img, 1)

# Display results
fig = plt.figure(figsize=(8, 5))
axes = np.zeros((2, 3), dtype=np.object)
axes[0, 0] = plt.subplot(2, 3, 1)
axes[0, 1] = plt.subplot(2, 3, 2, sharex=axes[0, 0], sharey=axes[0, 0])
axes[0, 2] = plt.subplot(2, 3, 3, sharex=axes[0, 0], sharey=axes[0, 0])
axes[1, 0] = plt.subplot(2, 3, 4)
axes[1, 1] = plt.subplot(2, 3, 5)
axes[1, 2] = plt.subplot(2, 3, 6)

ax_img, ax_hist, ax_cdf = plot_img_and_hist(img, axes[:, 0])
ax_img.set_title('Low contrast image')

y_min, y_max = ax_hist.get_ylim()
ax_hist.set_ylabel('Number of pixels')
ax_hist.set_yticks(np.linspace(0, y_max, 5))

ax_img, ax_hist, ax_cdf = plot_img_and_hist(gamma_corrected, axes[:, 1])
ax_img.set_title('Gamma correction')

ax_img, ax_hist, ax_cdf = plot_img_and_hist(logarithmic_corrected, axes[:, 2])
ax_img.set_title('Logarithmic correction')

ax_cdf.set_ylabel('Fraction of total intensity')
ax_cdf.set_yticks(np.linspace(0, 1, 5))

# prevent overlap of y-axis labels
fig.tight_layout()
plt.show()

實驗結果

實驗結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章