from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
def ImageToMatrix(filename):
im = Image.open(filename)
width,height = im.size
im = im.convert("L")
data = im.getdata()
data = np.matrix(data,dtype=‘float‘)/255.0
new_data = np.reshape(data,(height,width))
return new_data
def MatrixToImage(data):
data = data*255
new_im = Image.fromarray(data.astype(np.uint8))
return new_im
filename = ‘lena.jpg‘
data = ImageToMatrix(filename)
print data
new_im = MatrixToImage(data)
plt.imshow(data, cmap=plt.cm.gray, interpolation=‘nearest‘)
new_im.show()
new_im.save(‘lena_1.bmp‘)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
上面要先对图片去除颜色,就是变成黑白的,转换成二维数据矩阵,不去颜色的还要保存颜色的,然后后面转换就不行了,下面利用Image.fromarray(data) 新建图片
http://www.cnblogs.com/theskulls/p/4925147.html