matplotlibpython-imaging-librarypyscriptpyodide

Plotting an Image from GitHub using pyscript and matplotlib


Using pyscript it's easy to load in raw data from GitHub, like in the intro tutorial where you read in a Pandas DataFrame like so:

url = (
    "https://raw.githubusercontent.com/Cheukting/pyscript-ice-cream/main/bj-products.csv"
)
ice_data = pd.read_csv(open_url(url))

I would like to do something similar, but load in a jpg file and plot it using matplotlib. Would someone be able to help me understand what I should be doing here? I am very new to using pyscript.

I would think that the code required to do that would look something like the below, but I haven't been able to get anything working.

from pyodide.http import open_url
import matplotlib.pyplot as plt
from PIL import Image

fig, ax = plt.subplots(figsize=(15, 15))

image = Image.open(open_url("https://raw.githubusercontent.com/path/to/img.jpg"))
ax.imshow(image)
display(fig, target="graph-area", append=False)

Solution

  • Thanks TachyonicBytes, I was able to get that work in the most recent pyscript version by doing the following

    import asyncio
    from pyodide.http import pyfetch
    from PIL import Image
    import matplotlib.pyplot as plt
    import io
    
    async def plot_image(url):
        img = await pyfetch(url)
        res = await img.bytes()
        iobuf = io.BytesIO(res)
        image = Image.open(iobuf)
        fig, ax = plt.subplots(figsize=(15, 15))
        ax.imshow(image)
    
        display(fig, target="graph-area", append=False)
    
    asyncio.ensure_future(plot_image(url))