# coding=gbk
from PIL import Image
import numpy as np
# import scipy
import matplotlib.pyplot as plt
def ImageToMatrix(filename):
# 讀取圖片
im = Image.open(filename)
# 顯示圖片
# im.show()
width,height = im.size
im = im.convert("L")
data = im.getdata()
data = np.matrix(data,dtype=‘float‘)/255.0
#new_data = np.reshape(data,(width,height))
new_data = np.reshape(data,(height,width))
return new_data
# new_im = Image.fromarray(new_data)
# # 顯示圖片
# new_im.show()
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) 新建圖片