图片转矩阵,矩阵转图片

2019-05-30  本文已影响0人  雨夜剪魂

# 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可能会导致转的图片有问题

上一篇 下一篇

猜你喜欢

热点阅读