Mahotas 简明教程

Mahotas - Finding Image Mean

当我们讨论查找图像均值时,我们指的就是计算图像中所有像素的平均强度值。

数字图像中的每个像素均由一个数值表示,该数值对应于其强度或颜色信息。

强度值范围取决于图像的色彩深度,例如,灰度图像为 8 位(0-255),彩色图像为 24 位(每个颜色通道为 0-255)。

查找图像均值涉及将图像中所有像素的强度值求和并将其除以像素总数。

此过程提供了一个表示图像平均强度的单一值。这可以解释为图像的整体亮度或强度级别。

Finding Image Mean in Mahotas

我们可以在 Mahotas 中使用 mahotas.mean() 函数求图像均值。此函数接受一个图像数组并返回其均值。

正如我们所知,Mahotas 一次只能求出一个通道的均值,因此我们需要将彩色图像转换为单通道,才能找到该通道的均值。

mean 函数返回一个标量值,该值表示图像中所有像素的均值。

Syntax

以下是 mean 函数的基本语法 −

Image_name.mean()

Example

在以下示例中,我们将找到图像均值并显示具有平均强度的图像 −

import mahotas as mh
import numpy as np
from pylab import imshow, show
import matplotlib.pyplot as plt
image = mh.imread('nature.jpeg', as_grey = True)
find_mean = image.mean()
print("Mean of the image is:", find_mean)
imshow(image,cmap='gray')
show()
Mean of the image is: 134.99541438411237

显示的图像如下所示:

finding image mean

Image Mean of each Channel Individually

我们还可以使用 Mahotas 查找 RGB 图像中每个通道的均值。首先,计算整个图像的均值,然后使用数组切片计算每个通道的均值。

切片图像[:, :, 0] 对应于通道 0(红色),图像[:, :, 1] 对应于通道 1(绿色),图像[:, :, 2] 对应于通道 2(蓝色)。它使用 mean() 函数计算每个通道的均值并打印结果。

Example

在此示例中,我们尝试查找各个通道中图像的均值 −

import mahotas as mh
import numpy as np
image = mh.imread('sun.png')
# Calculating the mean of the entire image
print("Mean of the image: {0}".format(image.mean()))
# Calculating the mean of Channel 0 (Red)
img0 = image[:, :, 0]
print('Mean of channel 0: {0}'.format(img0.mean()))
# Calculating the mean of Channel 1 (Green)
img1 = image[:, :, 1]
print('Mean of channel 1: {0}'.format(img1.mean()))
# Calculating the mean of Channel 2 (Blue)
img2 = image[:, :, 2]
print('Mean of channel 2: {0}'.format(img2.mean()))

执行以上代码后,我们得到如下所示的输出 −

Mean of the image: 105.32921300415184
Mean of channel 0: 126.04734671559905
Mean of channel 1: 106.04269535883749
Mean of channel 2: 83.89759693801898

Finding the Mean of an ROI in an Image

我们可以使用图像数组上的切片操作在图像中找到感兴趣区域 (ROI) 的均值。然后,计算 ROI 内所有通道的均值(如果图像为彩色)或灰度值的均值(如果图像为灰度)。

以下是定义图像 ROI 的语法-

image[start_row:end_row, start_column:end_column]

其中, 'start_row''end_row' 表示行范围,而 'start_column''end_column' 表示定义 ROI 的列范围。

因此,要指定图像中的感兴趣区域,我们选择行和列的子集。

Example

在此处,我们正在优化图像感兴趣区域的平均值-

import mahotas as mh
import numpy as np
image = mh.imread('tree.tiff')
# Defining a specific region of interest
roi = image[100:300, 200:400]
roi_mean = np.mean(roi)
print("Mean of the image is:", roi_mean)

上述代码的输出如下:

Mean of the image is: 98.556925