Python将二维数组输出为图片

原文链接

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

代码如下:

# coding=utf8
from PIL import Image
import numpy as np
import imageio
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):
    data = (data * 255.0).astype('uint8')  # 转换数据类型
    new_im = Image.fromarray(data)  # 调用Image库,数组归一化

    # 显示新图片
    pyplot.imshow(data)
    pyplot.show()

    # 保存图片到本地
    imageio.imsave('new_img.jpg', new_im)


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

其中 Gener_mat 函数用于生成一个300*500的矩阵,矩阵大部分值为0,在坐标(20, 20)处有一个40*80的区域,值为1。

矩阵转为的图片保存在与代码同级的目录下,图片为:


如果不能正常显示图片,出现报错:

MatplotlibDeprecationWarning: Support for FigureCanvases without a required_interactive_framework attribute was deprecated in Matplotlib 3.6 and will be removed two minor releases later.

是Pycharm设置的问题。点击菜单栏 File——Setting——Tools——Python Scientific,取消勾选“Show plots in tool window”,然后点击右下角的“OK”,即可完成配置。再次启动,就能正常显示了。

 
 

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

 
 

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容