How to show PIL Image in ipython notebook

前端 未结 12 1323
抹茶落季
抹茶落季 2020-12-22 23:18

This is my code

from PIL import Image
pil_im = Image.open(\'data/empire.jpg\')

I would like to do some image manipulation on it, and then s

相关标签:
12条回答
  • 2020-12-22 23:42

    Use IPython display to render PIL images in a notebook.

    from PIL import Image               # to load images
    from IPython.display import display # to display images
    
    pil_im = Image.open('path/to/image.jpg')
    display(pil_im)
    
    0 讨论(0)
  • 2020-12-22 23:43

    Just use

    from IPython.display import Image 
    Image('image.png')
    
    0 讨论(0)
  • 2020-12-22 23:47

    You can use IPython's Module: display to load the image. You can read more from the Doc.

    from IPython.display import Image 
    pil_img = Image(filename='data/empire.jpg')
    display(pil_img)
    

    updated

    As OP's requirement is to use PIL, if you want to show inline image, you can use matplotlib.pyplot.imshow with numpy.asarray like this too:

    from matplotlib.pyplot import imshow
    import numpy as np
    from PIL import Image
    
    %matplotlib inline
    pil_im = Image.open('data/empire.jpg', 'r')
    imshow(np.asarray(pil_im))
    

    If you only require a preview rather than an inline, you may just use show like this:

    pil_im = Image.open('data/empire.jpg', 'r')
    pil_im.show()
    
    0 讨论(0)
  • 2020-12-22 23:50

    case python3

    from PIL import Image
    from IPython.display import HTML
    from io import BytesIO
    from base64 import b64encode
    
    pil_im = Image.open('data/empire.jpg')
    b = BytesIO()  
    pil_im.save(b, format='png')
    HTML("<img src='data:image/png;base64,{0}'/>".format(b64encode(b.getvalue()).decode('utf-8')))
    
    0 讨论(0)
  • 2020-12-22 23:56

    You can open an image using the Image class from the package PIL and display it with plt.imshow directly.

    # First import libraries.
    from PIL import Image
    import matplotlib.pyplot as plt
    
    # The folliwing line is useful in Jupyter notebook
    %matplotlib inline
    
    # Open your file image using the path
    img = Image.open(<path_to_image>)
    
    # Since plt knows how to handle instance of the Image class, just input your loaded image to imshow method
    plt.imshow(img)
    
    0 讨论(0)
  • 2020-12-22 23:56

    A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.

    import matplotlib.pyplot as plt
    from PIL import Image
    import numpy as np
    
    pil_im = Image.open('image.jpg')
    ## Uncomment to open from URL
    #import requests
    #r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
    #pil_im = Image.open(BytesIO(r.content))
    im_array = np.asarray(pil_im)
    plt.imshow(im_array)
    plt.show()
    
    0 讨论(0)
提交回复
热议问题