2

I'm reading a bunch of RGB images, one at a time, with different size using the PIL library and then convert them to numpy array. I use the following code and with 99% of the images I use, it works well.

from PIL import Image
import numpy as np

in_image = r'path\to\img_rgb.tif'

try:
    in_img = Image.open(in_image)
    in_array = np.array(in_img)
    print(in_array.shape)
    print(in_array)
except Exception as e:
    print(e)

But some images are read by PIL, passed to numpy and the result is not an array and the shape is empty. There are no errors or exceptions raised.
I've opened an issue on numpy Github but it seems that the problem comes from PIL. Here's the link to it. There is also two test files attached to the issue.

mpelchat04
  • 21
  • 3
  • The TIFF format has _lots_ of options, and IIRC PIL doesn't handle some of the more unusual variations. What happens if you do `in_img.show()` on the images that don't work before attempting to do the array conversion? BTW, you may run into other little glitches when doing PIL-> Numpy conversions. See https://stackoverflow.com/questions/2761645/error-converting-pil-bw-images-to-numpy-arrays and https://gist.github.com/PM2Ring/b09216123cca86e9b9cf889bfd3c5cec – PM 2Ring Jul 27 '18 at 15:25
  • @pm-2ring The ```in_img.show()``` raise the error 'decoder tiff_lzw not available' – mpelchat04 Jul 27 '18 at 15:43
  • Ok. So now you have an Exception you can trap. :) But it's a bit inconvenient if you're trying to load dozens of images and don't want to view them all. Sorry, I rarely need to deal with TIFF files, but maybe someone else will have a useful idea that doesn't involve `Image.show`. Maybe you can use some other library to detect if there's a LZW chunk in the files. – PM 2Ring Jul 27 '18 at 15:46
  • If worst comes to worse, you could write something that does that in Python: a simple chunk detector should be pretty easy compared to a full parser. OTOH, TIFF files are [notoriously baroque](https://en.wikipedia.org/wiki/TIFF#Part_1:_Baseline_TIFF) in their structure... – PM 2Ring Jul 27 '18 at 15:53
  • Thanks for your input. Yes, I'd like to avoid to see all my 500 huge images to trap those that are not PIL compatible. But what's bothering me the most is that I tried to read the same image with GDAL and it works great, and I could convert each band to a numpy array... – mpelchat04 Jul 27 '18 at 15:56

0 Answers0