門檻化入門

Python 影像處理

Rebeca Gonzalez

Data Engineer

門檻化

將影像分成前景與背景

把它變成黑白

作法是將每個像素設為:

  • 若像素 $\gt$ 門檻值,設為 255(白)
  • 若像素 $\lt$ 門檻值,設為 0(黑)

拿相機男子的門檻化影像

Python 影像處理

門檻化

最簡單的影像分割方法

  • 擷取物體
    • 物體偵測
    • 人臉偵測
    • 等等

骨牌棋子的門檻化影像

Python 影像處理

門檻化

僅適用於灰階影像

門檻化步驟示意:骨牌影像,依序為原始 RGB 三色、灰階、門檻化結果

Python 影像處理

實作看看

# Obtain the optimal threshold value
thresh = 127

# Apply thresholding to the image binary = image > thresh
# Show the original and thresholded show_image(image, 'Original') show_image(binary, 'Thresholded')

拿相機男子的門檻化影像

Python 影像處理

反向門檻化

# Obtain the optimal threshold value
thresh = 127

# Apply thresholding to the image inverted_binary = image <= thresh
# Show the original and thresholded show_image(image, 'Original') show_image(inverted_binary, 'Inverted thresholded')

拿相機男子的反向門檻化影像

Python 影像處理

分類

  • 全域或直方圖式:適合背景均勻

  • 區域或自適應:適合背景光照不均

全域與區域門檻化的比較

Python 影像處理

嘗試更多門檻化演算法

from skimage.filters import try_all_threshold

# Obtain all the resulting images fig, ax = try_all_threshold(image, verbose=False)
# Showing resulting plots show_plot(fig, ax)
Python 影像處理

嘗試更多門檻化演算法

在灰階文字頁面上測試所有全域門檻化方法的結果

Python 影像處理

最佳門檻值

全域

背景均勻
# Import the otsu threshold function
from skimage.filters import threshold_otsu

# Obtain the optimal threshold value thresh = threshold_otsu(image)
# Apply thresholding to the image binary_global = image > thresh
Python 影像處理

最佳門檻值

全域

# Show the original and binarized image
show_image(image, 'Original')
show_image(binary_global, 'Global thresholding')

拿相機男子的原圖、門檻化結果與直方圖(紅線標示最佳門檻值)

Python 影像處理

最佳門檻值

區域

背景不均
# Import the local threshold function
from skimage.filters import threshold_local

# Set the block size to 35 block_size = 35
# Obtain the optimal local thresholding local_thresh = threshold_local(text_image, block_size, offset=10)
# Apply local thresholding and obtain the binary image binary_local = text_image > local_thresh
Python 影像處理

最佳門檻值

區域

# Show the original and binarized image
show_image(text_image, 'Original')
show_image(binary_local, 'Local thresholding')

文字頁面的區域門檻化結果

Python 影像處理

一起來練習吧!

Python 影像處理

Preparing Video For Download...