pythonnumpypython-imaging-library

PIL.Image.verify() changes Image to None, preventing conversion


This code works as expected:

import numpy as np
import PIL.Image


img = PIL.Image.open('test.png')
img_np = np.array(img)
print(img_np.dtype, img_np.shape)

> uint8 (192, 256)

When I add verify(), img_np becomes an object, not the image data:

import numpy as np
import PIL.Image


img = PIL.Image.open('test.png')
img.verify()
img_np = np.array(img)
print(img_np.dtype, img_np.shape)

> object ()

Is there a way to convert the PIL image to numpy after verify()? Or do we really have to open the image again? The following does work, but is hacky.

import numpy as np
import PIL.Image


img = PIL.Image.open('test.png')
img.verify()
img = PIL.Image.open('test.png')
img_np = np.array(img)
print(img_np.dtype, img_np.shape)

> uint8 (192, 256)

Solution

  • This is documented behaviour:

    Image.verify()

    Verifies the contents of a file. For data read from a file, this method attempts to determine if the file is broken, without actually decoding the image data. If this method finds any problems, it raises suitable exceptions. If you need to load the image after using this method, you must reopen the image file.