简体   繁体   中英

Reading image using Pillow fails in Jupyter notebook

I'm trying to read a jpg file using Pillow (Version 3.2.0) in Jupyter notebook (Python 3.4), but it fails with the following error:

OSError: broken data stream when reading image file

I'm using the following code:

from PIL import Image
im = Image.open("/path/to/image.jpeg")
im.show()

It works fine both in the interactive Python shell and using Python 2.7 instead of 3.4.

I've followed these steps already: Using Pillow with Python 3

Anyone an idea what's going on?

Looks like you're not pointing to the directory where your photo is stored.

import os
defaultWd = os.getcwd()
defaultWd # Sets your curretn wd

os.chdir(defaultWd + '\\Desktop') # Points to your photo--e.g., on Desktop
os.getcwd() # Shows change in wd

from PIL import Image
im = Image.open("Mew.jpg")
im.show() # Will plot to your default image viewing software

And another way if you don't want to change current wd:

im = Image.open(os.getcwd() + "\\Desktop\\Mew.jpg")
im.show()

And if you want to plot inline:

from matplotlib.pyplot import imshow

%matplotlib inline
inlinePic = Image.open(os.getcwd() + "\\Desktop\\Mew.jpg")
imshow(inlinePic)

Note: You may also want to simply try typing 'jpg' instead of 'jpeg' as you did above, if your image is in your current working directory. Also, if PIC is not installed, you'll get this error NameError: name 'Image' is not defined .

The problem was related to another import: I was importing Tensorflow before PIL, which caused the problem. Same issue as this one: https://github.com/scikit-image/scikit-image/issues/2000 . Changing the order of the imports solved it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM