Python将二维数组输出为图片

电子说

1.2w人已加入

描述

原文链接

使用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。

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

python

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

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”,即可完成配置。再次启动,就能正常显示了。

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分