How to show PIL Image in ipython notebook

前端 未结 12 630
悲&欢浪女
悲&欢浪女 2020-12-22 23:08

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-23 00:03

    much simpler in jupyter using pillow.

    from PIL import Image
    image0=Image.open('image.png')
    image0
    
    0 讨论(0)
  • 2020-12-23 00:04

    I found that this is working

    # source: http://nbviewer.ipython.org/gist/deeplook/5162445
    from io import BytesIO
    
    from IPython import display
    from PIL import Image
    
    
    def display_pil_image(im):
       """Displayhook function for PIL Images, rendered as PNG."""
    
       b = BytesIO()
       im.save(b, format='png')
       data = b.getvalue()
    
       ip_img = display.Image(data=data, format='png', embed=True)
       return ip_img._repr_png_()
    
    
    # register display func with PNG formatter:
    png_formatter = get_ipython().display_formatter.formatters['image/png']
    dpi = png_formatter.for_type(Image.Image, display_pil_image)
    

    After this I can just do:

    pil_im
    

    But this must be last line in cell, with no print after it

    0 讨论(0)
  • 2020-12-23 00:04

    I suggest following installation by no image show img.show() (from PIL import Image)

    $ sudo apt-get install imagemagick

    0 讨论(0)
  • 2020-12-23 00:05

    Just use

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

    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)
  • 2020-12-23 00:08

    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)
提交回复
热议问题