Using plots/images directly within Streamlit app without saving them
rdzudzar opened this issue · comments
Hi there,
Excellent Streamlit component, thanks for making it available!
I wanted to ask if there is a way of parsing directly figures from plot onto it, instead of using saved image files?
Example usage:
Having fig1, fig2 created in matplotlib within Streamlit app and then using fig1 and fig2 directly in streamlit-image-comparison?
Cheers,
Robert
Ok, so I found solution.
I've saved plot into BytesIO, and then using Image from PIL parsed it into the image_comparison.
Example:
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
x = [1,2,3]
y = [5,6,7]
z = [2,2,2]
plt.plot(x, y)
fig1 = BytesIO()
plt.savefig(fig1)
plt.plot(x, z)
fig2 = BytesIO()
plt.savefig(fig2)
image_comparison(
img1=Image.open(fig1).convert('RGB'), #need to convert to RGB
img2=Image.open(fig2).convert('RGB'),
label1="Figure 1",
label2="Figure 2"
)
@rdzudzar awesome solution! How can we automate it inside image_comparison
function?
Is it possible to come up with something like:
if isinstance(fig1, matplotlib.figure):
buf = io.BytesIO()
fig1.savefig(buf)
buf.seek(0)
img1_pillow = PIL.Image.open(buf)
Yes, possibly, adding some checks of what is parsed. I could check code as true with this modifications:
if isinstance(fig1, io.IOBase):
buf = BytesIO()
plt.savefig(buf)
buf.seek(0)
img1_pillow = Image.open(buf)
Since figure is within BytesIO, so its <class '_io.BytesIO'>
.
fig1.savefig(buf)
didn't work, so I replaced it with plt.savefig(buf)
.