• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Python二维数组输出为图片

武飞扬头像
代码的路
帮助3

原文链接

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

 
 

代码的路

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhffkkhk
系列文章
更多 icon
同类精品
更多 icon
继续加载