Mahotas - 大津法



大津法是一種用於影像分割的技術,用於將前景與背景分離。它透過找到最大化類間方差的閾值來工作。

類間方差是衡量前景和背景區域之間分離程度的指標。

最大化類間方差的閾值被認為是影像分割的最佳閾值。

Mahotas 中的大津法

在 Mahotas 中,我們可以利用 **thresholding.otsu()** 函式使用大津法計算閾值。該函式以以下方式執行 -

  • 首先它找到影像的直方圖。直方圖是影像中每個灰度級畫素數量的圖。

  • 接下來,閾值設定為影像的平均灰度值。

  • 然後,計算當前閾值的類間方差。

  • 然後增加閾值,並重新計算類間方差。

重複步驟 2 到 4,直到達到最佳閾值。

mahotas.thresholding.otsu() 函式

mahotas.thresholding.otsu() 函式以灰度影像作為輸入,並返回使用大津法計算的閾值。然後將灰度影像的畫素與閾值進行比較以建立分割影像。

語法

以下是 mahotas 中 otsu() 函式的基本語法 -

mahotas.thresholding.otsu(img, ignore_zeros=False)

其中,

  • **img** - 輸入灰度影像。

  • **ignore_zeros(可選)** - 一個標誌,指定是否忽略零值畫素(預設為 false)。

示例

在下面的示例中,我們使用 mh.thresholding.otsu() 函式查詢閾值。

import mahotas as mh
import numpy as np
import matplotlib.pyplot as mtplt
# Loading the image
image = mh.imread('sea.bmp')
# Converting it to grayscale
image = mh.colors.rgb2gray(image).astype(np.uint8)
# Calculating threshold value using Otsu method
otsu_threshold = mh.thresholding.otsu(image)
# Creating image from the threshold value
final_image = image > otsu_threshold
# Creating a figure and axes for subplots
fig, axes = mtplt.subplots(1, 2)
# Displaying the original image
axes[0].imshow(image, cmap='gray')
axes[0].set_title('Original Image')
axes[0].set_axis_off()
# Displaying the threshold image
axes[1].imshow(final_image, cmap='gray')
axes[1].set_title('Otsu Threshold Image')
axes[1].set_axis_off()
# Adjusting spacing between subplots
mtplt.tight_layout()
# Showing the figures
mtplt.show()
輸出

以下是上述程式碼的輸出 -

Otsu's method

忽略零值畫素

我們還可以透過忽略零值畫素來找到大津閾值。零值畫素是指強度值為 0 的畫素。

它們通常表示影像的背景畫素,但在某些影像中,它們也可能表示噪聲。

在灰度影像中,零值畫素由顏色“黑色”表示。

要排除 mahotas 中的零值畫素,我們可以將 **ignore_zeros** 引數設定為布林值“True”。

示例

在下面提到的示例中,我們在使用大津法計算閾值時忽略了值為零的畫素。

import mahotas as mh
import numpy as np
import matplotlib.pyplot as mtplt
# Loading the image
image = mh.imread('tree.tiff')
# Converting it to grayscale
image = mh.colors.rgb2gray(image).astype(np.uint8)
# Calculating threshold value using Otsu method
otsu_threshold = mh.thresholding.otsu(image, ignore_zeros=True)
# Creating image from the threshold value
final_image = image > otsu_threshold
# Creating a figure and axes for subplots
fig, axes = mtplt.subplots(1, 2)
# Displaying the original image
axes[0].imshow(image, cmap='gray')
axes[0].set_title('Original Image')
axes[0].set_axis_off()
# Displaying the threshold image
axes[1].imshow(final_image, cmap='gray')
axes[1].set_title('Otsu Threshold Image')
axes[1].set_axis_off()
# Adjusting spacing between subplots
mtplt.tight_layout()
# Showing the figures
mtplt.show()

輸出

執行上述程式碼後,我們得到以下輸出 -

Zero Valued Pixels
廣告