Python Pillow 简明教程

Python Pillow - Edge Detection

Edge detection 是使用数学算法识别图像中这些边界或轮廓的过程。边缘检测的目的是在图像中找到强度发生突然变化的点,这通常对应于两个区域之间的边缘或边界。通常,边缘被定义为图像中两个不同区域之间的边界或轮廓。这些区域在强度、颜色、纹理或任何其他视觉特征上可能不同。边缘可以在图像中表示重要的特征,例如对象边界、形状和纹理。

边缘检测是许多图像处理应用程序中至关重要的一步,例如对象识别、分割、跟踪和增强。在本教程中,我们将看到使用 Python pillow 库在图像中检测边缘的不同方法。

Applying Edge Detection Filter to an Image

可以通过使用 ImageFilter.FIND_EDGES 滤镜在图像中检测边缘,它是 Pillow 库当前版本中可用的内置滤镜选项之一,用于检测图像中的边缘。

以下是检测图像中边缘的步骤 −

  1. 使用 Image.open() 函数加载输入图像。

  2. 将 filter() 函数应用于加载的图片对象并将 ImageFilter.FIND_EDGES 作为参数提供给该函数。该函数将图像.Image 对象中的输出检测边缘作为 PIL.Image.返回。

Example

以下示例演示了如何使用 ImageFilter.FIND_EDGES 滤镜内核和 filter() 方法检测图像中的边缘。

from PIL import Image, ImageFilter

# Open the image
image = Image.open('Images/compass.jpg')

# Apply edge detection filter
edges = image.filter(ImageFilter.FIND_EDGES)

# Display the original image
image.show()

# Display the edges-detected image
edges.show()
compass

输出检测到的边缘 −

imagefilter find edges

Example

这里提供一个使用 ImageFilter.FIND_EDGES 滤波器核来检测图像中的边缘的例子。然后它利用 ImageFilter.MaxFilter() 类来平滑检测到的边缘。

import matplotlib.pyplot as plt
from PIL import Image, ImageFilter

# Open the image and convert it to grayscale
im = Image.open('Images/compass.jpg').convert('L')

# Detect edges
edges = im.filter(ImageFilter.FIND_EDGES)

# Make fatter edges
fatEdges = edges.filter(ImageFilter.MaxFilter)

# Make very fat edges
veryFatEdges = edges.filter(ImageFilter.MaxFilter(7))

# Create subplots for displaying the images
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
ax = axes.ravel()

# Original image
ax[0].imshow(im, cmap='gray')
ax[0].set_title('Original')

# Detected edges
ax[1].imshow(edges, cmap='gray')
ax[1].set_title('Edges')

# Fatter edges
ax[2].imshow(fatEdges, cmap='gray')
ax[2].set_title('Fatter Edges')

# Very fat edges
ax[3].imshow(veryFatEdges, cmap='gray')
ax[3].set_title('Very Fat Edges')

for ax in axes.flatten():
   ax.axis('off')

# Display the images
plt.tight_layout()
plt.show()
imagefilter maxfilter

Detecting Edges using the ImageFilter.Kernel() Class

这个类用于创建一个卷积核。

在这种方法中,我们将使用一些指定的核值(-1、-1、-1、-1、8、-1、-1、-1、-1)定义一个 3X3 卷积核。我们将对一张图像进行边缘检测。

Example

以下示例说明了如何使用卷积矩阵和 ImageFilter.kernel() 类对图像进行边缘检测。

from PIL import Image, ImageFilter

# Open the image and convert it to grayscale
image = Image.open('Images/compass.jpg').convert('L')

# Calculate edges using a convolution matrix
kernel = ImageFilter.Kernel((3, 3), (-1, -1, -1, -1, 8, -1, -1, -1, -1), scale=1, offset=0)
edges = image.filter(kernel)

# Display the original image
image.show()

# Display the edges
edges.show()
image convert to grayscale

输出检测到的边缘 −

detected edges