Matplotlib figure to image as a numpy array

后端 未结 5 1053
礼貌的吻别
礼貌的吻别 2020-11-28 10:58

I\'m trying to get a numpy array image from a Matplotlib figure and I\'m currently doing it by saving to a file, then reading the file back in, but I feel like there has to

5条回答
  •  离开以前
    2020-11-28 11:41

    from the docs:

    https://matplotlib.org/gallery/user_interfaces/canvasagg.html#sphx-glr-gallery-user-interfaces-canvasagg-py

    fig = Figure(figsize=(5, 4), dpi=100)
    # A canvas must be manually attached to the figure (pyplot would automatically
    # do it).  This is done by instantiating the canvas with the figure as
    # argument.
    canvas = FigureCanvasAgg(fig)
    
    # your plotting here
    
    canvas.draw()
    s, (width, height) = canvas.print_to_buffer()
    
    # Option 2a: Convert to a NumPy array.
    X = np.fromstring(s, np.uint8).reshape((height, width, 4))
    

提交回复
热议问题