# 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()``````