Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OSError: broken data stream when reading image file

I am trying to read an image file using Image package of Keras.

Here is my code.

from keras.preprocessing import image
img_path = 'test/test_image.jpg'  # This is an image I took in my kitchen.
img = image.load_img(img_path, target_size=(224, 224))

When I run the code, I get the following error.

anaconda3/lib/python3.5/site-packages/PIL/ImageFile.py in load(self)
    238         if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:
    239             # still raised if decoder fails to return anything
--> 240             raise_ioerror(err_code)
    241 
    242         # post processing

anaconda3/lib/python3.5/site-packages/PIL/ImageFile.py in raise_ioerror(error)
     57     if not message:
     58         message = "decoder error %d" % error
---> 59     raise IOError(message + " when reading image file")
     60 
     61 

OSError: broken data stream when reading image file

Please note, if I convert test_image.jpg to test_image.png, then the given code works perfectly. But I have several thousands of pictures and I can't convert all of them to png format. I tried several things after searching for solution in web but couldn't get rid of the problem.

Any help would be appreciated!

like image 949
Wasi Ahmad Avatar asked Feb 25 '17 22:02

Wasi Ahmad


2 Answers

Use this at the beginning of your code:

from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

I found it here. And this is working for me.

like image 79
Preetom Saha Arko Avatar answered Nov 24 '22 04:11

Preetom Saha Arko


According to here Pillow upgrade by pip install Pillow --upgrade should solve this issue.

If you are still facing the problem you can use mogrify to batch convert all your images. mogrify -format png *.jpg

like image 21
indraforyou Avatar answered Nov 24 '22 03:11

indraforyou