import matplotlib.pyplot as plt
import numpy as np
# Make a random plot...
fig = plt.figure()
fig.add_subplot(111)
# If we haven't already shown or saved the plot, then we need to
# draw the figure first...
fig.canvas.draw()
# Now we can save it to a numpy array.
data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
from moviepy.video.io.bindings import mplfig_to_npimage
import matplotlib.pyplot as plt
fig = plt.figure() # make a figure
numpy_fig = mplfig_to_npimage(fig) # convert it to a numpy array
8条答案
按热度按时间fruv7luv1#
当您需要对保存的图进行像素到像素的比较时,这对于单元测试等是一个方便的技巧。
一种方法是使用
fig.canvas.tostring_rgb
,然后使用numpy.fromstring
和适当的dtype。还有其他方法,但这是我倾向于使用的方法。例如:
u1ehiz5o2#
@JUN_NETWORKS的答案有一个更简单的选项。可以使用其他格式,如
raw
或rgba
,而不是将数字保存为png
,并跳过cv2
解码步骤。换句话说,实际的plot-to-numpy转换归结为:
霍普这个有用
rggaifut3#
有些人提出了一种方法,它是这样的
当然,这个代码工作。但是,输出的numpy数组图像分辨率很低。
我的提案代码是这样的。
这段代码运行良好。
如果在dpi参数上设置了一个大的数字,则可以将高分辨率图像作为numpy数组。
kognpnkq4#
是时候对您的解决方案进行基准测试了。
在这种情况下,IO原始缓冲区是将matplotlib图形转换为numpy数组的最快方法。
补充说明:
fig = ax.figure
channel x height x width
的数组,请执行im = im.transpose((2, 0, 1))
。i86rm4rw5#
MoviePy使得将数字转换为numpy数组变得非常简单。它有一个内置函数,名为
mplfig_to_npimage()
。你可以这样使用它:ubby3x7f6#
如果有人想要一个即插即用的解决方案,而不需要修改任何先前的代码(获得对pyplot图的引用和所有内容),下面的代码对我很有用。只需在所有
pyplot
语句后添加此语句即可。在pyplot.show()
之前a6b3iqyw7#
正如Joe Kington所指出的,一种方法是在画布上绘制,将画布转换为字节字符串,然后将其重塑为正确的形状。
但是,由于
canvas.get_width_height()
返回显示坐标中的宽度和高度,因此有时会出现缩放问题,在此答案中已解决。at0kjp5o8#
Jonan Gueorguiev的回答: