如何将Figure对象转换为具有RGBA值的Numpy数组?

问题描述 投票:0回答:1

我有Plotly Figure对象,我曾经使用Plotly创建图形。我想将此Figure对象转换为Numpy Array。这样我就可以将该数组数据转换为PIL Image对象。然后使用.drawImage方法在Reportlab上绘制drawImage。

这里,b是情节图对象。

def fig2data ( b ):
    """
    @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

buf = fig2data(b)
buf

这给了我

AttributeError: 'Figure' object has no attribute 'canvas'

谢谢。

python python-3.x numpy plotly reportlab
1个回答
0
投票
from matplotlib.backends.backend_agg import FigureCanvasAgg def fig2data ( b ): """ @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 """ canvas = FigureCanvasAgg(fig) # 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 buf = fig2data(b) buf

希望这会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.