Search code examples
pythonimagepngbytesio

Trying to display images with PIL and BytesIO but returns nothing


I'm trying to display the logos from a dataset. The dataset looks like this:

Player      Club Logo        
tom         https://abc.png
jerry       https://def.png
peter       https://frf.png
woody       https://awt.png

However, it didnt return me any logos. All it did show was 4 empty grid boxes. My code is below. I also did try to use im = Image.open(BytesIO(r.content)).show() but the logos ended up opening on my computer instead.

import matplotlib.pyplot as plt
import requests

from PIL import Image
from io import BytesIO

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

for i in range(4):
    r = requests.get(df['Club Logo'][i])
    im = Image.open(BytesIO(r.content))

plt.show()

Thanks


Solution

  • Starting with these images:

    "0.png":

    enter image description here

    "1.png":

    enter image description here

    "2.png":

    enter image description here

    "3.png":

    enter image description here

    I think you want this:

    #!/usr/bin/env python3
    
    from PIL import Image
    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots(2,2, figsize=(2,2))
    
    for i in range(4): 
        # Load image and make into Numpy array
        im = Image.open(f'{i}.png').convert('RGB') 
        na = np.array(im) 
        # Shove into the plot
        ax[i%2][i//2].imshow(na) 
    
    fig.show()
    

    enter image description here