Matplotlib:将图保存到numpy数组 [英] Matplotlib: save plot to numpy array
本文介绍了Matplotlib:将图保存到numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python和Matplotlib中,很容易将图显示为弹出窗口或将图另存为PNG文件.我该如何将图另存为RGB格式的numpy数组?
In Python and Matplotlib, it is easy to either display the plot as a popup window or save the plot as a PNG file. How can I instead save the plot to a numpy array in RGB format?
推荐答案
当您需要对保存的图进行像素对像素的比较时,这是单元测试之类的便捷技巧.
This is a handy trick for unit tests and the like, when you need to do a pixel-to-pixel comparison with a saved plot.
一种方法是先使用fig.canvas.tostring_rgb
,然后再将numpy.fromstring
与适当的dtype一起使用.还有其他方法,但这是我倾向于使用的方法.
One way is to use fig.canvas.tostring_rgb
and then numpy.fromstring
with the approriate dtype. There are other ways as well, but this is the one I tend to use.
例如
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.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
这篇关于Matplotlib:将图保存到numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文