Skip to content

np.array(img) should not hide errors for corrupted images #5084

@akamaus

Description

@akamaus

What did you do?

I spent a lot of time debugging a code which loads png images from disk and converts them to numpy arrays to do some processing.

What did you expect to happen?

If I take any png and corrupt it, say, by truncating,

$ dd if=good.png of=corrupted.png bs=1024 count=10
$ python

I expect the following code to fail with some exception because image pixels can not be read into an array.

>>> from PIL import Image
>>> import numpy as np
>>> img = Image.open('corrupted.png') 
>>> arr = np.array(img)

What actually happened?

Instead, I got an object array with a single element:

>>> print(arr)
<PIL.PngImagePlugin.PngImageFile image mode=RGB size=384x288 at 0x7F38258C6240>

and now the code fails later with a strange error message, like:

>>> arr / 255
TypeError: unsupported operand type(s) for /: 'PngImageFile' and 'int'

img.verify() behaves strangely, too

Funny and counter-intuitive thing, if I try instead doing:

>>> img = Image.open('good.png') 
>>> img.verify()
>>> arr = np.array(img)
>>> arr / 255
TypeError: unsupported operand type(s) for /: 'PngImageFile' and 'int'

I still got an error presumably because calling verify() makes image unusable, but again, np.array() doesn't care. So now the code fails for all good images.

What are your OS, Python and Pillow versions?

  • OS: ubuntu-18.04
  • Python: 3.6
  • Pillow: 8.0.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions