15
在Python和Matplotlib中,很容易将绘图显示为弹出窗口或将绘图另存为PNG文件。我怎样才能将绘图保存为RGB格式的数组?Matplotlib:将绘图保存为numpy数组
在Python和Matplotlib中,很容易将绘图显示为弹出窗口或将绘图另存为PNG文件。我怎样才能将绘图保存为RGB格式的数组?Matplotlib:将绘图保存为numpy数组
当您需要对保存的图进行像素到像素的比较时,这对于单元测试等是非常方便的技巧。
一种方法是使用fig.canvas.tostring_rgb
,然后使用numpy.fromstring
和适当的dtype。还有其他方法,但这是我倾向于使用的方法。
例如
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,))
非常好! 12345 – Petter
这只支持某些后端?似乎没有找到'macosx'后端('tostring_rgb')。 – mirosval
Works on Agg,在'import matplotlib.pyplot as plt'之前加'matplotlib.use('agg')'来使用它。 – mirosval