本文將簡單介紹用於邊緣偵測的 Laplacian 算子,並示範如何用 OpenCV 的 Laplacian 對灰階圖片進行邊緣偵測,如下圖所示。
Laplacian 概念:




(圖片由下方的 Python 程式碼產生)
import cv2
import numpy as np
import matplotlib.pyplot as plt
dog_pic = '../images/dog.png' # 圖片位址
dog_img = cv2.imread(dog_pic)
dog_img_gray = cv2.cvtColor(dog_img, cv2.COLOR_BGR2GRAY)
height, width = dog_img_gray.shape
X = np.arange(0, width, 1)
Y = np.arange(0, height, 1)
X, Y = np.meshgrid(X, Y)
# 繪製曲面
fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(projection='3d')
surf = ax.plot_surface(
X, Y, dog_img_gray, cmap='gray'
)
# 加入色彩條
fig.colorbar(surf, shrink=0.5, aspect=5)
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Brightness (Z Axis)')
plt.show()


底下為使用Laplacian Kernel 去對灰階圖片做捲積的程式碼:
程式碼(Python):
import cv2
import numpy as np
import matplotlib.pyplot as plt
dog_pic = '../images/dog.png' # 圖片位址
dog_img = cv2.imread(dog_pic)
dog_img_gray = cv2.cvtColor(dog_img, cv2.COLOR_BGR2GRAY)
laplacian_kernel = np.array([[0, 1, 0],
[1, -4, 1],
[0, 1, 0]])
# 也可將等號右邊替代成 cv2.Laplacian(dog_img_gray, -1, 3)
laplacian_img = cv2.filter2D(src=dog_img_gray, ddepth = -1, kernel = laplacian_kernel)
cv2.imshow('before vs after laplacian', np.hstack([dog_img_gray, laplacian_img]))
cv2.waitKey()
cv2.destroyAllWindows()
執行結果:
可以發現捲積完的二維矩陣,散度較大的地方(白色線條)和邊緣有蠻大的關連性。
Note:
以上為筆者對 Laplacian 的理解,數學部分可能沒那麼嚴謹,筆記內容如有錯誤竟請多多包容,謝謝~