Pillow: Grayscale PNG image incorrectly converted to RGB

Created on 12 Jun 2017  路  3Comments  路  Source: python-pillow/Pillow

I have a PNG image which incorrectly converts to RGB mode. This is a grayscale 16-bit image, presumably created in Photoshop. When I open it with Pillow, mode of an image is described as "I". I tried to convert it by calling:

from PIL import Image
Image.open('original.png').convert('RGB').save('result.png')

All I received was a white image with only black pixels rgb(0, 0, 0) copied from the original. I am using newest version of Pillow (4.1.1), problem appears both in Python 2.7 & 3.6.
I am attaching 2 files:

  • original.png - original image used to reproduce this problem
    original
  • result.png - result of the conversion
    result
Documentation

Most helpful comment

This should be re-opened and fixed IMO. Or at least better documented. Digging into closed issues isn't intuitive. It took quite a while to find this fix.

All 3 comments

So what's happening here is that the convert from 'I' to 'L' loses information, and the conversion isn't done is a particularly useful fashion. It's clamping the range of the 16bit image to 0-255, rather than (auto)scaling it.

Unfortunately, I don't see a quick way to autorange the image so that it fits into the destination image format, but there's a workaround with imagemath. (any of the embedded functions that rely on histogram or lookup tables aren't going to work)

>>> from PIL import ImageMath
>>> im2 = ImageMath.eval('im/256', {'im':im}).convert('L')

I'm going to call this "documented workaround" and close.

This should be re-opened and fixed IMO. Or at least better documented. Digging into closed issues isn't intuitive. It took quite a while to find this fix.

Was this page helpful?
0 / 5 - 0 ratings