Mahotas 简明教程

Mahotas - Histogram of Image

图像的直方图是指显示图像中像素强度分布的图形表示形式。它提供了有关图像中不同强度值出现频率的信息。

直方图的水平轴(X 轴)表示图像中可能强度值的范围,而垂直轴(Y 轴)表示具有特定强度值像素的频率或数量。

Histogram of Image in Mahotas

要在 Mahotas 中计算图像的直方图,我们可以使用该库提供的 fullhistogram() 函数。此函数将返回一个表示直方图值的数组。

直方图数组包含代表图像中可能像素值的 bin。每个 bin 都对应于一个特定的强度级,指示具有该特定值的像素的频率或计数。

例如,在 8 位灰度图像中,直方图数组有 256 个 bin,表示 0 到 255 的强度级。

The mahotas.fullhistogram() function

Mahotas 中的 mahotas.fullhistogram() 函数以图像作为输入,并返回一个表示直方图的数组。此函数通过计算每个强度级或 bin 中的像素数来计算直方图。

Syntax

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

mahotas.fullhistogram(image)

其中, 'image' 是无符号类型的输入图像。

Mahotas 只能处理此函数中的无符号整数数组

Example

在以下示例中,我们尝试使用 fullhistogram() 函数显示彩色图像的直方图:

import mahotas as mh
import numpy as np
from pylab import imshow, show
import matplotlib.pyplot as plt
image = mh.imread('sun.png')
hist = mh.fullhistogram(image)
plt.hist(hist)
plt.show()

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

histogram image

Grayscale Image Histogram

mahotas 中的灰度图像直方图是指灰度图像中像素强度分布的表示形式。

灰度图像通常具有从 0(黑色)到 255(白色)的像素强度。默认情况下,Mahotas 在计算直方图时会考虑像素强度的整个范围。

这意味着从 0 到 255 的所有强度都包含在直方图计算中。

通过考虑 256 个 bin 和像素强度的整个范围,Mahotas 提供了灰度图像中像素强度分布的全面表示。

Example

在这里,我们尝试使用 mahotas 显示灰度图像直方图:

import mahotas as mh
import numpy as np
import matplotlib.pyplot as plt
# Convert image array to uint8 type
image = mh.imread('sun.png', as_grey=True).astype(np.uint8)
hist = mh.fullhistogram(image)
plt.hist(hist)
plt.show()

下面显示了产生的输出:

grayscale histogram image

Blue Channel RGB Image Histogram

蓝色通道包含每个像素的蓝色颜色分量的信息。

我们将 mahotas 库与 numpy 和 matplotlib 结合使用,从 RGB 图像中提取蓝色通道。

我们可以通过使用数组切片选择第三个(索引 2)通道来从 RGB 图像中提取蓝色通道。这为我们提供了一个代表蓝色分量强度的灰度图像。

然后,使用 numpy,我们计算蓝色通道的直方图。我们将蓝色通道数组展平以创建一个 1D 数组,确保在图像中的所有像素上计算直方图。

最后,我们使用 matplotlib 可视化直方图。

Example

现在,我们尝试显示蓝色通道的 RGB 图像直方图 -

import mahotas as mh
import numpy as np
import matplotlib.pyplot as plt
# Loading RGB image
image = mh.imread('sea.bmp')
# Extracting the blue channel
blue_channel = image[:, :, 2]
# Calculating the histogram using numpy
hist, bins = np.histogram(blue_channel.flatten(), bins=256, range=[0, 256])
# Plot histogram
plt.bar(range(len(hist)), hist)
plt.xlabel('Pixel Value')
plt.ylabel('Frequency')
plt.title('Histogram of Blue Channel')
plt.show()

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

blue channel rgb image