Mahotas 简明教程

Mahotas - Otsu’s Method

大津法是用于图像分割以将前景与背景分开的技术。它的工作方式是找到最大化类间方差的阈值。

类间方差是对前景区域和背景区域之间分离程度的度量。

最大化类间方差的阈值被认为是图像分割的最佳阈值。

Otsu’s Method in Mahotas

在 Mahotas 中,我们可以利用 thresholding.otsu() 函数使用大津法计算阈值。该函数以下列方式运行−

  1. 首先,它找到图像的直方图。直方图是图像中每个灰度级别的像素数量的图表。

  2. 接下来,阈值设置为图像的平均灰度值。

  3. 随后,为当前阈值计算类间方差。

  4. 然后增加阈值,并重新计算类间方差。

重复步骤 2 到 4,直到达到最佳阈值。

The mahotas.thresholding.otsu() function

mahotas.thresholding.otsu() 函数接受灰度图像作为输入,并返回使用大津方法计算出的阈值。然后将灰度图像的像素与阈值进行比较,以创建分段图像。

以下是 mahotas 中 otsu() 函数的基本语法:

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

其中,

  1. img − 它是输入的灰度图像。

  2. ignore_zeros (optional) - 它是一个标志,指定是否忽略值为零的像素(默认值为 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()

以下是上面代码的输出: -

otsus method

Ignoring the Zero Valued Pixels

我们还可以通过忽略值为零的像素来查找大津阈值。值为零的像素是强度值为 0 的像素。

它们通常表示图像的背景像素,但在某些图像中,它们也可能表示噪声。

在灰度图像中,零值像素是表示为颜色“黑色”的像素。

若要排除 mahotas 中的值为零的像素,可以将 ignore_zeros 参数设置为布尔值“True”。

Example

在以下提到的示例中,在使用大津方法计算阈值时,我们忽略值为零的像素。

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