matplotlib.pyplot画图 图片的二进制流的获取方法

yipeiwu_com5年前Python基础

有些时候,我们需要画图后的二进制数据流,matplotlib没有提供相关的api,通过源码查看与百度,得到下面此方法

import matplotlib.pyplot as plt
import numpy as np
import io
x=np.arange(10)
y=x
#plt.plot(x,y)
#canvas = plt.get_current_fig_manager().canvas
#canvas.draw()
fig=plt.figure()
plt.plot(x,y)
canvas=fig.canvas
#上面这段代码和上面注释掉的代码效果一样

#方法1
buffer = io.BytesIO()
canvas.print_png(buffer)
data=buffer.getvalue()
buffer.close()
#方法2
buf, size = canvas.print_to_buffer()
image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
buffer=io.BytesIO()
image.save(buffer,'PNG')
data=buffer.getvalue()
buffer.close()

with open('hhh.png',mode='wb') as f:
f.write(data)
#f=open('hh.png',mode='wb')
#f.write(data)
#f.close()

如果我们想把二进制的图片转成数组也是可以的,

buffer=io.BytesIO()
buffer.write(data)
img=Image.open(buffer)
img = np.asarray(img)

以上这篇matplotlib.pyplot画图 图片的二进制流的获取方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现的本地文件搜索功能示例【测试可用】

Python实现的本地文件搜索功能示例【测试可用】

本文实例讲述了Python实现的本地文件搜索功能。分享给大家供大家参考,具体如下: 偶尔需要搜索指定文件,不想每次都在windows下面去搜索,想用代码来实现搜索,而且能够收集搜索结果,...

Python中的枚举类型示例介绍

起步 Python 的原生类型中并不包含枚举类型。为了提供更好的解决方案,Python 通过 PEP 435 在 3.4 版本中添加了 enum 标准库。 枚举类型可以看作是一种标签或...

Django接受前端数据的几种方法总结

背景 测试工具箱写到一半,今天遇到了一个前后端数据交互的问题,就一起做一下整理。 环境 -------------------------------------------------...

python+opencv实现动态物体追踪

python+opencv实现动态物体追踪

简单几行就可以实现对动态物体的追踪,足见opencv在图像处理上的强大。 python代码: import cv2 import numpy as np camera=cv2.V...

Python使用pip安装报错:is not a supported wheel on this platform的解决方法

Python使用pip安装报错:is not a supported wheel on this platform的解决方法

本文讲述了Python使用pip安装报错:is not a supported wheel on this platform的解决方法。分享给大家供大家参考,具体如下: 可能的原因1:安...