from PIL import Imageimport numpy as npimport matplotlib.pyplot as pltdef ImageToMatrix(filename): # 读取图片 im = Image.open(filename) width,height = im.size data = im.getdata() data = np.matrix(data,dtype='float')/255 # 这里处理的是rgb三通道的图片 new_data = np.reshape(data.getA(),(height,width,3)) # 单色图片:new_data = np.reshape(data,-1,height*width) return new_datadef MatrixToImage(data): # 显示图片 data = data*255 new_im = Image.fromarray(data.astype(np.uint8)) return new_imfilename = '/Users/gaowenfeng/Documents/图片/头像.png'data = ImageToMatrix(filename)# print(data)new_im = MatrixToImage(data)plt.imshow(data, cmap=plt.cm.gray, interpolation='nearest')new_im.show()复制代码