以下代码实现图片和矩阵相互转换

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import PIL.Image as Image
import numpy as np
import pandas as pd
import os
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, (height, width))
    return new_data

#将矩阵转换为图片
def matrixToImage(data):
    data = data * 255.0
    new_im = Image.fromarray(data)
    return new_im

#定义图片路径
filename = "d:/m2.png"
#将图片转换为矩阵并输出到csv文件
data = imageToMatrix(filename)
dataframe = pd.DataFrame(data=data)
dataframe.to_csv('d:/out.csv', sep=' ', header=False, float_format='%.2f', index=False)
# 将矩阵转换为图片
new_im = matrixToImage(data)
plt.imshow(data, cmap=plt.cm.gray, interpolation="nearest")
new_im.show()
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐