Python将二维数组输出为图片

原文链接

使用Python读取二维数组,将二维数组输出为图片,并保存在本地。

代码如下:

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

a = 300
b = 500
x = 20
y = 20
w = 40
h = 80
         
def Gener_mat(a,b,x,y,w,h):             #生成图片矩阵
    img_mat = np.zeros((a, b), dtype=np.int)
    for i in range(0,a):
        for j in range(0,b):
            img_mat[i][j] = 0
    for i in range(x,x+w):
        for j in range(y,y+h):
            img_mat[i][j] = 1
    return img_mat

def out_img(data):                 #输出图片
    new_im = Image.fromarray(data)     #调用Image库,数组归一化 
    #new_im.show() 
    pyplot.imshow(data)                  #显示新图片
    misc.imsave('new_img.jpg', new_im)   #保存图片到本地


img_mat = Gener_mat(a,b,x,y,w,h)
out_img(img_mat)
 

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

代码的路

你可能感兴趣的:(Python将二维数组输出为图片)