Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

python - matplotlib: render into buffer / access pixel data

I want to use plots generated with matplotlib as textures in OpenGL. The OpenGL backends for matplotlib I came across so far are either immature or discontinued, so I want to avoid them.

My current approach is to save figures into temporary .png files from which I assemble texture atlases. However, I would prefer to avoid storing intermediate files and get pixel data directly from matplotlib instead. Is this possible somehow?


The answer I was looking for is fig.canvas.print_to_buffer(). Joe's answer contains other alternatives worth checking out.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sure, just use fig.canvas.tostring_rgb() to dump the rgb buffer to a string.

Similarly, there's fig.canvas.tostring_argb() if you need the alpha channel, as well.

If you want to dump the buffer to a file, there's fig.canvas.print_rgb and fig.canvas.print_rgba (or equivalently, print_raw, which is rgba).

You'll need to draw the figure before dumping the buffer with tostring*. (i.e. do fig.canvas.draw() before calling fig.canvas.tostring_rgb())

Just for fun, here's a rather silly example:

import matplotlib.pyplot as plt
import numpy as np

def main():
    t = np.linspace(0, 4*np.pi, 1000)
    fig1, ax = plt.subplots()
    ax.plot(t, np.cos(t))
    ax.plot(t, np.sin(t))

    inception(inception(fig1))
    plt.show()

def fig2rgb_array(fig):
    fig.canvas.draw()
    buf = fig.canvas.tostring_rgb()
    ncols, nrows = fig.canvas.get_width_height()
    return np.fromstring(buf, dtype=np.uint8).reshape(nrows, ncols, 3)

def inception(fig):
    newfig, ax = plt.subplots()
    ax.imshow(fig2rgb_array(fig))
    return newfig

main()

enter image description here enter image description here enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...