使用缓冲区协议
import numpy as np
import Image
import scipy.misc
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)
img.save('lena_frombuffer.png')
data[:,:,3] = 255
data[:,:,0] = 222
img.save('lena_modified.png')
数组协议
from __future__ import print_function
import numpy as np
import Image
import scipy.misc
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)
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
'''
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 交换数据
a = np.arange(7)
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
'''
mat = io.loadmat("a.mat")
print mat