python-3.5keras

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!


Solution

  • 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.