关于python:Python将二维数组输出为图片

2次阅读

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

原文链接

应用 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)
 

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

代码的路

正文完
 0