如何从pyplot图形中直接读取图像作为数组?

2024-04-25 02:25:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将pyplot图形的当前视图读取为numpy数组,而不保存文件并加载它

我首先尝试的是绘制数据并保存它,然后使用imread加载它。但我猜这种节省和加载会降低任务的时间效率

# Plotting
plt.plot(data_x, data_y, data_z)
plt.savefile('output.png')
plt.close()

# Load image as numpy array
im = cv2.read('output.png')

如何更改此代码以执行相同的工作,但提高时间效率


Tags: 文件数据numpy视图图形outputdatapng
1条回答
网友
1楼 · 发布于 2024-04-25 02:25:31

很抱歉打扰你。我的代码是在三维坐标系中查看三维骨骼关节模型(每个相邻关节连接为直线)

import matplotlib.pyplot as plt
import numpy as np


def draw_3D_model(file_name)
   fig = plt.figure()
   ax = plt.axes(projection = '3d')
   ax.grid(False)
   ax.view_init(azim = -90,elev = -50)

   draw_skeleton(file_name)   # this is the function I made to draw a line between neighbor joints(only used plt.plot()

   return fig


def make_animation   
   for file_name in file_names:
      fig = draw_3D_model(file_name)
      fig.canvas.draw ( )
      w,h = fig.canvas.get_width_height()
      buf = numpy.fromstring ( fig.canvas.tostring_argb(), dtype=numpy.uint8 )
      buf.shape = ( w, h,4 )

这是我的代码的简化结构,当执行buf.shape=(w,h,4)时,它会显示错误消息,即无法将buf的大小重塑为(w,h,4)

相关问题 更多 >