当我使用pylab plot()函数创建绘图时,我可以显示它,或绘制它。我也可以访问像素矩阵吗?
我想避免像
这样的操作import matplotlib.pyplot as plt
import matplotlib.image as mpimg
plt.savefig("name.png")
mpimg.imread("name.png")
有没有办法直接从创建的情节中获取图像矩阵?
答案 0 :(得分:2)
诀窍是使用numpy.fromstring
并将fig输出为字节串。
我找到了问题的确切解决方案here。
def fig2data ( fig ):
"""
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
# draw the renderer
fig.canvas.draw ( )
# Get the RGBA buffer from the figure
w,h = fig.canvas.get_width_height()
buf = numpy.fromstring ( fig.canvas.tostring_argb(), dtype=numpy.uint8 )
buf.shape = ( w, h,4 )
# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = numpy.roll ( buf, 3, axis = 2 )
return buf
答案 1 :(得分:1)
您提到的两种方法都可以使用“类文件”对象,因此无需将文件写入磁盘:
import StringIO
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
plt.plot([1,2,3,4])
imgdata = StringIO.StringIO()
plt.savefig(imgdata, format='png')
imgdata.seek(0)
mpimg.imread(imgdata)