連接 NumPy 與 剩余世界
# 來源:NumPy Cookbook 2e Ch4
使用緩沖區(qū)協(xié)議
# 協(xié)議在 Python 中相當(dāng)于接口
# 是一種約束
import numpy as np
import Image
# from PIL import Image (Python 3)
import scipy.misc
lena = scipy.misc.lena()
# Lena 是 512x512 的灰度圖像
# 創(chuàng)建與 Lena 寬高相同的 RGBA 圖像,全黑色
data = np.zeros((lena.shape[0], lena.shape[1], 4), dtype=np.int8)
# 將 data 的不透明度設(shè)置為 Lena 的灰度
data[:,:,3] = lena.copy()
# 將 data 轉(zhuǎn)成 RGBA 的圖像格式龙填,并保存
img = Image.frombuffer("RGBA", lena.shape, data, 'raw', "RGBA", 0, 1)
img.save('lena_frombuffer.png')
# 每個(gè)像素都設(shè)為 #FC0000FF (紅色)
data[:,:,3] = 255
data[:,:,0] = 222
img.save('lena_modified.png')
數(shù)組協(xié)議
from __future__ import print_function
import numpy as np
import Image
import scipy.misc
# 獲取上一節(jié)的第一個(gè)圖像
lena = scipy.misc.lena()
data = np.zeros((lena.shape[0], lena.shape[1], 4), dtype=np.int8)
data[:,:,3] = lena.copy()
img = Image.frombuffer("RGBA", lena.shape, data, 'raw', "RGBA", 0, 1)
# 獲取數(shù)組接口(協(xié)議)炸客,實(shí)際上它是個(gè)字典
array_interface = img.__array_interface__
print("Keys", array_interface.keys())
print("Shape", array_interface['shape'])
print("Typestr", array_interface['typestr'])
'''
Keys ['shape', 'data', 'typestr']
Shape (512, 512, 4)
Typestr |u1
'''
# 將圖像由 PIL.Image 類型轉(zhuǎn)換回 np.array
numpy_array = np.asarray(img)
print("Shape", numpy_array.shape)
print("Data type", numpy_array.dtype)
'''
Shape (512, 512, 4)
Data type uint8
'''
與 Matlab 和 Octave 交換數(shù)據(jù)
# 創(chuàng)建 0 ~ 6 的數(shù)組
a = np.arange(7)
# 將 a 作為 array 保存在 a.mat 中
scipy.io.savemat("a.mat", {"array": a})
'''
octave-3.4.0:2> load a.mat
octave-3.4.0:3> array
array =
0
1
...
6
'''
# 還可以再讀取進(jìn)來
mat = io.loadmat("a.mat")
print mat
# {'array': array([[0, 1, 2, 3, 4, 5, 6]]), '__version__': '1.0', '__header__': 'MATLAB 5.0 MAT-file Platform: nt, Created on: Sun Jun 11 18:48:29 2017', '__globals__': []}