Perwitt鏈式 (Perwitt Chained)
基礎理論: Perwitt算子是一種簡單的邊緣檢測算子,用於計算圖像的空間梯度以識別邊緣。通常,Perwitt算子在水平和垂直方向上分別計算梯度。"鏈式"可能意味著將這些梯度結合成一個單一的梯度幅度。
Perwitt水平和垂直梯度核分別為:
梯度幅度和方向可以使用以下公式計算:
Python舉例: 使用Python和OpenCV,我們可以計算上傳圖像的Perwitt鏈式梯度。讓我們進行計算並顯示結果。
# Function to compute the Perwitt chained gradient of an image
def perwitt_chained_gradient(img):
# Define Perwitt kernels
kernel_x = np.array([[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1]])
kernel_y = np.array([[-1, -1, -1],
[0, 0, 0],
[1, 1, 1]])
# Compute gradients in x and y direction using Perwitt kernels
grad_x = cv2.filter2D(img, -1, kernel_x)
grad_y = cv2.filter2D(img, -1, kernel_y)
# Compute the magnitude and orientation of the gradient
magnitude = cv2.magnitude(grad_x.astype(float), grad_y.astype(float))
orientation = cv2.phase(grad_x.astype(float), grad_y.astype(float), angleInDegrees=True)
return magnitude, orientation
# Compute the Perwitt chained gradient for the uploaded image
perwitt_magnitude, perwitt_orientation = perwitt_chained_gradient(uploaded_image)
# Display the gradient magnitude and orientation
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
axes[0].imshow(uploaded_image, cmap='gray')
axes[0].axis('off')
axes[0].set_title('Original Image')
axes[1].imshow(perwitt_magnitude, cmap='hot')
axes[1].axis('off')
axes[1].set_title('Perwitt Gradient Magnitude')
axes[2].imshow(perwitt_orientation, cmap='hsv')
axes[2].axis('off')
axes[2].set_title('Perwitt Gradient Orientation')
plt.tight_layout()
plt.show()
以上是使用Perwitt鏈式梯度計算的結果。
- 原始圖像:這是您上傳的圖像。
- Perwitt梯度幅度:這表示圖像中各點的梯度強度。邊緣的地方梯度幅度較大,因此更亮。
- Perwitt梯度方向:這表示圖像中各點的梯度方向。使用不同的顏色代表不同的方向。
Perwitt鏈式梯度提供了一種有效的方式來識別和強化圖像中的邊緣。您可以看到圖像中明顯的邊緣特徵被強化了。