当前位置: 首页 > 后端技术 > Python

Python将图片输出为二维数组保存在txt中

时间:2023-03-26 12:37:41 Python

原文链接使用Python将图片输出为二维数组保存到txt文件中。代码如下:#coding=utf8fromPILimportImageimportnumpyasnpfromscipyimportmiscimportmatplotlib.pyplotaspyplot#读取图像defloadImage():im=Image.open("0001.jpg")#读取图像im.show()#显示原图im=im.convert("L")#转为灰度图data=im.getdata()data=np.matrix(data)#图像类返回矩阵运算data=np.reshape(data,(304,720))#转换为304*720new_im=Image.fromarray(data)#调用图片库,数组归一化new_im.show()#显示新图片misc.imsave('new_img.jpg',new_im)#保存新的图片到本地返回数据#writedatadefWritedata(data):filename='C:\\Users\\DZF\\Desktop\\negative.txt'#数据文件保存位置row=np.array(data).shape[0]#获取n行数withopen(filename,'w')asf:#如果filename不存在,会自动创建,写入前清空文件foriinrange(0,row):f.write(str(data[i][0:]))f.write("\n")data=loadImage()Writedata(data)学习更多编程知识,请关注我的公众号:码道