Scipy:運用 Sobel operator 計算圖像導數
運用 Sobel operator 計算圖像導數:
Sobel operator 如下所示,Sx 用於檢測水平的梯度變化,Sy 用於檢測垂直的梯度變化:
$$S_{x}=\begin{bmatrix} -1 & 0 & 1\\ -2 & 0 & 2\\ -1& 0 & 1 \end{bmatrix}$$ $$S_{y}=\begin{bmatrix} -1 & -2 & -1\\ 0 & 0 & 0\\ 1& 2 & 1 \end{bmatrix}$$下面程式中的的 mag 為 dX 和 dY 的平方合開根號,代表梯度:
if __name__ == "__main__":
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
from scipy.ndimage import filters
pli_img = Image.open("lena.jpg").convert("L")
img = np.array(pli_img)
plt.subplot(221)
plt.title("original")
plt.imshow(img, cmap="gray")
imx = np.zeros (img.shape)
# 1 for horizontal derivative
filters.sobel(img, 1, imx)
plt.subplot(222)
plt.title("imx")
plt.imshow(imx, cmap="gray")
imy = np.zeros (img.shape)
# 0 for vertical derivative
filters.sobel(img, 0, imy)
plt.subplot(223)
plt.title("imy")
plt.imshow(imx, cmap="gray")
# magnitude
mag = np.hypot(imx, imy)
# normalize
mag *= 255.0 / np.max(mag)
plt.subplot(224)
plt.title("edge")
plt.imshow(mag, cmap="gray")
plt.show()

留言
張貼留言