Mahotas 简明教程

Mahotas - Riddler-Calvard Method

Riddler-Calvard 方法是一种用于将图像分割为前景和背景区域的技术。它将图像的像素分组以最大程度地减少计算阈值时的类内方差。

类内方差衡量像素值在组内的分散程度。较低的类内方差表明像素值彼此接近,而较高的类内方差表明像素值分散。

Riddler-Calvard Method in Mahotas

在 Mahotas 中,我们使用 thresholding.rc() 函数使用 Riddler-Calvard 技术计算图像的阈值。该函数按以下方式运行 -

  1. 它计算两个群集(前景和背景)的平均值和方差。平均值是所有像素的平均值,方差是像素分散的一个衡量标准。

  2. 接下来,它选择一个最小化类内方差的阈值。

  3. 然后它将每个像素分配给具有较低方差的群集。

步骤 2 和 3 重复进行,直到计算出阈值。然后使用此值将图像分割为前景和背景。

The mahotas.thresholding.rc() function

mahotas.thresholding.rc() 函数以灰度图像作为输入,并使用 Riddler-Calvard 技术返回其计算出的阈值。

然后将灰度图像的像素与阈值进行比较以创建二进制图像。

以下为 mahotas 中 rc() 函数的基本语法:

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

其中,

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

  2. ignore_zeros (optional) − 它是指定是否忽略零值像素的标志(默认为 false)。

在以下示例中,我们使用 mh.thresholding.rc() 函数查找阈值。

import mahotas as mh
import numpy as np
import matplotlib.pyplot as mtplt
# Loading the image
image = mh.imread('sun.png')
# Converting it to grayscale
image = mh.colors.rgb2gray(image).astype(np.uint8)
# Calculating threshold value using Riddler-Calvard method
rc_threshold = mh.thresholding.rc(image)
# Creating image from the threshold value
final_image = image > rc_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('Riddler-Calvard Threshold Image')
axes[1].set_axis_off()
# Adjusting spacing between subplots
mtplt.tight_layout()
# Showing the figures
mtplt.show()

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

riddler calvard

Ignoring the Zero Valued Pixels

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

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

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

要在 mahotas 中计算阈值时排除零值像素,我们可以将 ignore_zeros 参数设置为布尔值“True”。

Example

在下面提到的示例中,我们计算阈值时忽略值等于零的像素,所用的是 Riddler-Calvard 方法。

import mahotas as mh
import numpy as np
import matplotlib.pyplot as mtplt
# Loading the image
image = mh.imread('nature.jpeg')
# Converting it to grayscale
image = mh.colors.rgb2gray(image).astype(np.uint8)
# Calculating threshold value using Riddler-Calvard method
rc_threshold = mh.thresholding.rc(image, ignore_zeros=True)
# Creating image from the threshold value
final_image = image > rc_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('Riddler-Calvard Threshold Image')
axes[1].set_axis_off()
# Adjusting spacing between subplots
mtplt.tight_layout()
# Showing the figures
mtplt.show()

执行上面的代码后,我们得到以下输出: -

ignore zero valued pixels