# coding=utf8
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=np.float32) / 255.0
new_data = data.reshape(width, height)
return new_data
def MatrixToImage(data):
data = data * 255
new_im = Image.fromarray(np.uint8(data))
return new_im
filename = 'test.jpg'
data = ImageToMatrix(filename)
new_im = MatrixToImage(data)
plt.imshow(data, cmap=plt.cm.gray, interpolation='nearest')
需要注意的是格式需要是 jpg的,如果是png可能会导致转的图片有问题
网友评论