简体   繁体   中英

Convert pyplot figure into wand.image Image

Is there a way to convert a pyplot figure created with pyplot.Figure into a wand image? I have tried using the following to no avail:

image_data = BytesIO()
figure.savefig(image_data, format='png')
image_data.seek(0)
image = Image(file=image_data, resolution=250)

The end goal of this is to convert a list of figures into a long png. The only other method (which is ugly) is to convert to pdf and then concatenate the pages.

I believe you are on the right track. Without seeing the figure, I would assume the issue would be related to holding the C structure pointer using the with keyword.

image_data = BytesIO()
figure.savefig(image_data, dpi=250, format='png')
image_data.seek(0)
with Image(file=image_data) as img:
    # ... do work
    img.save(filename='/tmp/out.png')

I was trying to figure out how to do this same thing. I went down a rabbit hole for a bit thinking I needed to also use PIL (Pillow) to accomplish this task. With the help of the previous answer I was able to come up with a complete example:

import matplotlib
from io import BytesIO
import numpy
import matplotlib.pyplot as plt
from wand.display import display
from wand.image import Image

plt.plot([1,5,3,2])
plt.ylabel('y axis numbers')
plt.xlabel('x axis numbers')

image_data = BytesIO() #Create empty in-memory file
plt.savefig(image_data, format='png') #Save pyplot figure to in-memory file
image_data.seek(0) #Move stream position back to beginning of file 
img = Image(file=image_data) #Create wand.image
display(img) #Use wand to display the img

I tried the recommended code above and had no luck. I posted the question to the WandB forum ( here ) and the following was recommended:

fig, ax1 = plt.subplots(...)
...
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
wandb.log(({"chart": wandb.Image(Image.open(buf)) }))
fig.show()

It seems that using the file parameter is no longer allowed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM