栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pyplot的绘图转换为numpy矩阵

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pyplot的绘图转换为numpy矩阵

1.核心原理
height_default, dpi_default= (4.8, 100)
    
fig = plt.figure()
plt.plot(x, y)
fig.canvas.draw()
fig_str = fig.canvas.tostring_rgb()
data = np.frombuffer(fig_str, dtype=np.uint8).reshape((int(height_default*dpi_default), -1, 3)) / 255.0

主要步骤为:
(1)创建 Figure
(2)在Figure中绘图,plot()、scatter()、imshow()…都行
(3)在canvas中绘制
(4)将canvas转换为「字符串」
(5)使用numpy.frombuffer()从「字符串」中读取数组,并用reshape()转换回矩阵

2.需要注意的问题

参考上一篇文章:避免pyplot出现Fail to allocate bitmap报错的方法

3.完整程序
import matplotlib.pyplot as plt
import numpy as np


class plot_to_matrix:
    def __init__(self):
        self.width= 6
        self.height= 4
        self.dpi= 128
        self.fig_convert = plt.figure(figsize=(self.width, self.height), dpi=self.dpi)
        self.axes_convert = self.fig_convert.add_axes([0.16, 0.15, 0.75, 0.75])

    def plot_to_matrix(self, x, y):
        self.axes_convert.cla()
        self.axes_convert.plot(x, y)

        self.fig_convert.canvas.draw()
        fig_str = self.fig_convert.canvas.tostring_rgb()
        data = np.frombuffer(fig_str, dtype=np.uint8).reshape((self.height*self.dpi, -1, 3))/255.0
        return data

if __name__ == '__main__':
    x= np.linspace(0,1,100)
    y= np.sin(x*20)
    pm= plot_to_matrix()
    for i in range(1000):
        m= pm.plot_to_matrix(x, y)
        """some thing"""
    # plt.figure()
    # plt.imshow(m)
    # plt.show()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/286342.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号