原文链接

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

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

代码的路

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐