# 使用 ndimage

``````import imageio

``````

``````gray = np.dot(img[...,:3], [0.299, 0.587, 0.114])
``````

``````filtered = ndimage.median_filter(gray, size = (3, 3))
``````

``````laplace = ndimage.laplace(filtered)
``````

``````import imageio
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

# 轉灰階
gray = np.dot(img[...,:3], [0.299, 0.587, 0.114])

# 中值濾波
filtered = ndimage.median_filter(gray, size = (3, 3))

# Laplacian 運算
laplace = ndimage.laplace(filtered)

# 取絕對值轉 uint8
edge = np.abs(laplace).astype('uint8')

plt.imshow(edge, cmap = cm.gray)
plt.show()
``````

``````Gx = (f(x + 1,y - 1) + 2 * f(x + 1, y) + f(x + 1, y + 1)) -
(f(x - 1,y - 1) + 2 * f(x - 1, y) + f(x - 1, y + 1))

Gy = (f(x - 1, y - 1) + 2 * f(x, y - 1) + f(x + 1,y - 1)) -
(f(x - 1, y + 1) + 2 * f(x, y + 1) + f(x + 1, y + 1))

G = sqrt(Gx * Gx, Gy * Gy)
``````

`Gx``Gy` 整理一下，以矩陣表示的話就是：

`ndimage``sobel` 函式可以透過 `axis` 來指定處理哪個軸的方向，預設是 -1，也就是考量兩個方向，指定軸 0 時，就圖像而言是指垂直方向（也就是 y 方向），指定軸 1 時是指水平方向（也就是 x 方向），底下的程式可以顯示三個處理的不同結果：

``````import imageio
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

# 轉灰階
gray = np.dot(img[...,:3], [0.299, 0.587, 0.114])

# 中值濾波
filtered = ndimage.median_filter(gray, size = (3, 3))

# 兩個方向
s = ndimage.sobel(filtered)
plt.subplot(1, 3, 1)
plt.imshow(np.abs(s).astype('uint8') , cmap = cm.gray)

# 水平方向
sx = ndimage.sobel(filtered, axis = 1)
plt.subplot(1, 3, 2)
plt.imshow(np.abs(sx).astype('uint8') , cmap = cm.gray)

# 垂直方向
sy = ndimage.sobel(filtered, axis = 0)
plt.subplot(1, 3, 3)
plt.imshow(np.abs(sy).astype('uint8') , cmap = cm.gray)

plt.show()
``````