跳转到内容

蒲瑞维特算子

维基百科,自由的百科全书

蒲瑞维特算子(英语:Prewitt Operator)是一种在影像处理中,用于边缘检测离散微分运算子。此算子由Judith M. S. Prewitt发明,并以她的名字命名[1]。蒲瑞维特算子通过在水平方向和垂直方向上对影像进行卷积,使用一个小型的整数值滤波器来完成运算,因此在计算成本方面相对较低,类似于索伯算子。蒲瑞维特算子的优点在于其计算简单且效率高,适合于需要快速边缘检测的应用场景。

然而,其粗糙的梯度近似使得它在处理细节丰富或高频率变化较多的影像时效果不佳。为了更准确地检测边缘,通常需要使用如坎尼算子等更先进的方法。

公式[编辑]

蒲瑞维特算子包含两个3x3的矩阵,分别为水平方向以及垂直方向,表示为

利用上述两矩阵与影像做2d卷积运算,即可达到水平向与垂直向差分的效果,得到其对应亮度梯度向量,公式如下:

在这里运算子'*'代表的2d卷积运算,A代表的是原影像。

对于影像中每个点的梯度值,透过以下公式得到:

运用,可以计算其梯度向量:

实作[编辑]

在实作上,因为只有该点的周围八个点需要被计算,同时在梯度向量的计算上也都只牵涉到整数的加法计算,而且上述的两个离散滤波器是可分解的:

范例[编辑]

水果影像
水平向的边缘
垂直向的边缘
水果影像的边缘侦测(蒲瑞维特算子)

程式范例[编辑]

# Read image and convert it into grayscale
img_file = '<name of input image file>.<file format>'
img = np.array(Image.open(img_file).convert('L'))

# Prepare edge, horizontal edge and vertical edge image arrays
edge_img = np.zeros_like(img)
horizontal_edge_img = np.zeros_like(img)
vertical_edge_img = np.zeros_like(img)

# Prewitt operator matrices
Mx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])
My = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])

# Perform 2d convolution
for i in range(1, img.shape[0]-1):
    for j in range(1, img.shape[1]-1):
        A = img[i-1:i+2, j-1:j+2]
        Gx = np.sum(Mx * A)
        Gy = np.sum(My * A)

        horizontal_edge_img[i][j] = abs(Gx)
        vertical_edge_img[i][j] = abs(Gy)
        edge_img[i][j] = np.sqrt(Gx ** 2 + Gy ** 2)

# Define a threshold value
thresholdValue = 80
edge_img = np.where(edge_img < thresholdValue, 0, edge_img)
horizontal_edge_img = np.where(horizontal_edge_img < thresholdValue, 0, horizontal_edge_img)
vertical_edge_img = np.where(vertical_edge_img < thresholdValue, 0, vertical_edge_img)

plt.figure()
plt.subplot(221)
plt.axis('off'); plt.title('Grayscale image of fruits'); plt.imshow(img, cmap='gray', vmin=0, vmax=255)

plt.subplot(222)
plt.axis('off')  
plt.title('Horizontal edge')  
plt.imshow(horizontal_edge_img, cmap='gray', vmin=0, vmax=255)

plt.subplot(223)
plt.axis('off')  
plt.title('Vertical edge')  
plt.imshow(vertical_edge_img, cmap='gray', vmin=0, vmax=255)

plt.subplot(224)
plt.axis('off')  
plt.title('Edge image')  
plt.imshow(edge_img, cmap='gray', vmin=0, vmax=255)
plt.show()

参见[编辑]

References[编辑]

  1. ^ Prewitt, J.M.S. Object Enhancement and Extraction. Picture processing and Psychopictorics. Academic Press. 1970.