# Scipy Ndimage

SciPy的`ndimage`子模組專用於影象處理。這裡，`ndimage`表示一個`n`維影象。

• 輸入/輸出，顯示影象
• 基本操作 - 裁剪，翻轉，旋轉等
• 影象過濾 - 去噪，銳化等
• 影象分割 - 標記對應於不同物件的畫素
• 分類
• 特徵提取
• 註冊/配準

## 開啟和寫入影象檔案

SciPy中的`misc`包附帶了一些影象。在這裡，使用這些影象來學習影象操作。請看看下面的例子。

``````from scipy import misc
f = misc.face()
misc.imsave('face.png', f) # uses the Image module (PIL)

import matplotlib.pyplot as plt
plt.imshow(f)
plt.show()
``````

``````from scipy import misc
f = misc.face()
misc.imsave('face.png', f) # uses the Image module (PIL)

face = misc.face(gray = False)
print (face.mean(), face.max(), face.min())
``````

``````110.162743886 255 0
``````

``````from scipy import misc
f = misc.face()
misc.imsave('face.png', f) # uses the Image module (PIL)
face = misc.face(gray = True)
lx, ly = face.shape

crop_face = face[int(lx/4): -int(lx/4), int(ly/4): -int(ly/4)]

import matplotlib.pyplot as plt
plt.imshow(crop_face)
plt.show()
``````

``````from scipy import misc

face = misc.face()
flip_ud_face = np.flipud(face)

import matplotlib.pyplot as plt
plt.imshow(flip_ud_face)
plt.show()
``````

``````# rotation
from scipy import misc,ndimage
face = misc.face()
rotate_face = ndimage.rotate(face, 45)

import matplotlib.pyplot as plt
plt.imshow(rotate_face)
plt.show()
``````

## 濾鏡

``````from scipy import misc
face = misc.face()
blurred_face = ndimage.gaussian_filter(face, sigma=3)
import matplotlib.pyplot as plt
plt.imshow(blurred_face)
plt.show()
``````

`sigma`值表示`5`級模糊程度。通過調整`sigma`值，可以看到影象品質的變化。

## 邊緣檢測

• 索貝爾(Sobel)
• 坎尼(Canny)
• 普魯伊特(Prewitt)
• 羅伯茨Roberts
• 模糊邏輯方法

``````import scipy.ndimage as nd
import numpy as np

im = np.zeros((256, 256))
im[64:-64, 64:-64] = 1
im[90:-90,90:-90] = 2
im = ndimage.gaussian_filter(im, 8)

import matplotlib.pyplot as plt
plt.imshow(im)
plt.show()
``````

``````import scipy.ndimage as nd
import matplotlib.pyplot as plt

im = np.zeros((256, 256))
im[64:-64, 64:-64] = 1
im[90:-90,90:-90] = 2
im = ndimage.gaussian_filter(im, 8)

sx = ndimage.sobel(im, axis = 0, mode = 'constant')
sy = ndimage.sobel(im, axis = 1, mode = 'constant')
sob = np.hypot(sx, sy)

plt.imshow(sob)
plt.show()
``````