Mahotas 简明教程

Mahotas - Convolution of Image

图像处理中的卷积用于对图像执行各种滤波操作。

以下是其中一些操作——

  1. Extract features − 通过应用特定滤波器,用于检测诸如边缘、角落、斑点等的特征。

  2. Filtering − 用于对图像执行平滑和锐化操作。

  3. Compression − 我们可以通过移除图像中的冗余信息来压缩图像。

Convolution of an Image in Mahotas

在 Mahotas 中,您可以使用 convolve() 功能对图像执行卷积。此函数采用两个参数——输入图像和内核;其中,内核是定义在卷积过程中要应用的操作的小矩阵,例如模糊、锐化、边缘检测或任何其他所需效果。

Using the convolve() Function

convolve() 函数用于对图像执行卷积。卷积是一种数学运算,它使用两个数组(图像和卷积核),并产生第三个数组(输出图像)。

卷积核是用于滤波图像的一个小数组。通过将图像和核心的相应元素相乘,然后将结果相加,执行卷积运算。卷积运算的输出是一个新图像,它已经通过内核进行了滤波。

在 mahotas 中执行卷积的语法如下:

convolve(image, kernel, mode='reflect', cval=0.0, out=None)

其中,

  1. image − 这是输入图像。

  2. kernel − 这是卷积核。

  3. mode − 它指定如何处理图像的边缘。它可以是反射、最近常量、忽略、环绕或镜像。默认选择反射。

  4. cval − 它指定用于图像之外像素的值。

  5. out − 它指定输出图像。如果未指定 out 参数,则将创建一个新图像。

在以下示例中,我们首先使用 mh.imresize() 函数将输入图像 'nature.jpeg' 调整为一个 '4×4' 的形状。然后,我们创建一个 '4×4' 的内核,其中所有值都设置为 1。最后,我们使用 mh.convolve() 函数来执行卷积:

import mahotas as mh
import numpy as np
# Load the image
image = mh.imread('nature.jpeg', as_grey=True)
# Resize the image to 4x4
image = mh.imresize(image, (4, 4))
# Create a 4x4 kernel
kernel = np.ones((4, 4))
# Perform convolution
result = mh.convolve(image, kernel)
print (result)

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

[[3155.28 3152.84 2383.42 1614. ]
[2695.96 2783.18 2088.38 1393.58]
[1888.48 1970.62 1469.53 968.44]
[1081. 1158.06 850.68 543.3 ]]

Convolution with a Gaussian Kernel

马氏核中的高斯核是一个小数字矩阵,用于模糊或平滑图像。

高斯核对每个像素应用加权平均,其中权重由一个钟形曲线(称为高斯分布)确定。内核为附近的像素赋予较高的权重,为远处的像素赋予较低的权重。此过程有助于减少噪声并增强图像中的特征,从而产生更平滑、更赏心悦目的输出。

以下是马氏核中高斯核的基本语法:

mahotas.gaussian_filter(array, sigma)

其中,

  1. array − 这是输入数组。

  2. sigma − 这是高斯核的标准差。

Example

以下是使用高斯滤波卷积图像的一个示例。在此,我们调整图像的大小,将其转换为灰度,应用高斯滤波模糊图像,然后并排显示原始图像和模糊图像:

import mahotas as mh
import matplotlib.pyplot as mtplt
# Load the image
image = mh.imread('sun.png')
# Convert to grayscale if needed
if len(image.shape) > 2:
   image = mh.colors.rgb2gray(image)
# Resize the image to 128x128
image = mh.imresize(image, (128, 128))
# Create the Gaussian kernel
kernel = mh.gaussian_filter(image, 1.0)
# Reduce the size of the kernel to 20x20
kernel = kernel[:20, :20]
# Blur the image
blurred_image = mh.convolve(image, kernel)
# Creating a figure and subplots
fig, axes = mtplt.subplots(1, 2)
# Displaying original image
axes[0].imshow(image)
axes[0].axis('off')
axes[0].set_title('Original Image')
# Displaying blurred image
axes[1].imshow(blurred_image)
axes[1].axis('off')
axes[1].set_title('Gaussian Filter Image')
# Adjusting the spacing and layout
mtplt.tight_layout()
# Showing the figure
mtplt.show()

上述代码的输出如下:

gaussian kernel

Convolution with Padding

在 Mahotas 中使用填充的卷积指的是在执行卷积运算之前在图像的边缘周围添加额外的像素或边框。填充的目的是创建一个具有更大尺寸的新图像,而不会丢失原始图像边缘的信息。

填充确保可以将内核应用于包括边缘在内的所有像素,从而产生与原始图像大小相同的卷积输出。

Example

在这里,我们定义了一个定制核,使其作为一个 NumPy 数组,以突出图像的边缘:

import numpy as np
import mahotas as mh
import matplotlib.pyplot as mtplt
# Create a custom kernel
kernel = np.array([[0, -1, 0],[-1, 5, -1],
[0, -1, 0]])
# Load the image
image = mh.imread('sea.bmp', as_grey=True)
# Add padding to the image
padding = np.pad(image, 150, mode='wrap')
# Perform convolution with padding
padded_image = mh.convolve(padding, kernel)
# Creating a figure and subplots
fig, axes = mtplt.subplots(1, 2)
# Displaying original image
axes[0].imshow(image)
axes[0].axis('off')
axes[0].set_title('Original Image')
# Displaying padded image
axes[1].imshow(padded_image)
axes[1].axis('off')
axes[1].set_title('Padded Image')
# Adjusting the spacing and layout
mtplt.tight_layout()
# Showing the figure
mtplt.show()

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

original padding image

Convolution with a Box Filter for Blurring

在 Mahotas 中使用盒式滤波器进行卷积是一种可以用于模糊图像的技术。盒式滤波器是一个简单的滤波器,其中滤波器内核中的每个元素都具有相同的值,从而产生均匀的权重分布。

使用盒式滤波进行卷积涉及将核滑动到图像上并获取核覆盖区域内像素值中的平均值。然后使用该平均值替换输出图像中的中心像素值。

该过程对图像中的所有像素进行重复,从而生成原始图像的模糊版本。模糊量通过核的大小决定,核越大则模糊越多。

Example

以下是用盒式滤波执行卷积以模糊图像的示例 −

import mahotas as mh
import numpy as np
import matplotlib.pyplot as plt
# Load the image
image = mh.imread('sun.png', as_grey=True)
# Define the size of the box filter
box_size = 25
# Create the box filter
box_filter = np.ones((box_size, box_size)) / (box_size * box_size)
# Perform convolution with the box filter
blurred_image = mh.convolve(image, box_filter)
# Display the original and blurred images
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(image, cmap='gray')
axes[0].set_title('Original Image')
axes[0].axis('off')
axes[1].imshow(blurred_image, cmap='gray')
axes[1].set_title('Blurred Image')
axes[1].axis('off')
plt.show()

我们得到了如下输出 −

original blurring

Convolution with a Sobel Filter for Edge Detection

Sobel 滤波器通常用于边缘检测。它由两个独立的滤波器组成 - 一个用于检测水平边缘,另一个用于垂直边缘。

通过用图像对 Sobel 滤波器进行卷积,我们获得了边缘被突出的新图像,图像的其余部分显得模糊。与周围区域的亮度值相比,凸显的边缘通常具有更高的亮度值。

Example

这里,我们通过用灰度图像卷积来使用 Sobel 滤波器执行边缘检测。然后,我们计算边缘的大小并应用阈值以获取所检测边缘的二进制图像 −

import mahotas as mh
import numpy as np
import matplotlib.pyplot as plt
image = mh.imread('nature.jpeg', as_grey=True)
# Apply Sobel filter for horizontal edges
sobel_horizontal = np.array([[1, 2, 1],
[0, 0, 0],[-1, -2, -1]])
# convolving the image with the filter kernels
edges_horizontal = mh.convolve(image, sobel_horizontal)
# Apply Sobel filter for vertical edges
sobel_vertical = np.array([[1, 0, -1],[2, 0, -2],[1, 0, -1]])
# convolving the image with the filter kernels
edges_vertical = mh.convolve(image, sobel_vertical)
# Compute the magnitude of the edges
edges_magnitude = np.sqrt(edges_horizontal**2 + edges_vertical**2)
# Threshold the edges
threshold = 50
thresholded_edges = edges_magnitude > threshold
# Display the original image and the detected edges
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
axes[0].imshow(image, cmap='gray')
axes[0].set_title('Original Image')
axes[0].axis('off')
axes[1].imshow(edges_magnitude, cmap='gray')
axes[1].set_title('Edges Magnitude')
axes[1].axis('off')
axes[2].imshow(thresholded_edges, cmap='gray')
axes[2].set_title('Thresholded Edges')
axes[2].axis('off')
plt.tight_layout()
plt.show()

获得的输出如下 −

sobel filter edge detection