关于python:Python将图片输出为二维数组并保存到txt中

0次阅读

共计 705 个字符,预计需要花费 2 分钟才能阅读完成。

原文链接

应用 Python 将图片输入为二维数组,并保留到 txt 文件中。

代码如下:

# coding=utf8
from PIL import Image
import numpy as np
from scipy import misc
import matplotlib.pyplot as pyplot 

#读图片
def loadImage():
    im = Image.open("0001.jpg")    #读取图片
    im.show()                     #显示原图
    im = im.convert("L")           #转换成灰度图
    data = im.getdata()
    data = np.matrix(data)          #Image 类返回矩阵的操作
    data = np.reshape(data,(304,720))   #变换成 304*720
    new_im = Image.fromarray(data)     #调用 Image 库,数组归一化 
    new_im.show()                        #显示新图片
    misc.imsave('new_img.jpg', new_im)   #保留新图片到本地
    return data

#写数据
def Writedata(data):
    filename = 'C:\\Users\\DZF\\Desktop\\negative.txt'  #数据文件保留地位
    row = np.array(data).shape[0]   #获取行数 n
    with open(filename,'w') as f: # 若 filename 不存在会主动创立,写之前会清空文件
        for i in range(0,row):
            f.write(str(data[i][0:]))
            f.write("\n")
            
            
data = loadImage()
Writedata(data)

学习更多编程常识,请关注我的公众号:

代码的路

正文完
 0