UnsignedByte
UnsignedByte

Reputation: 897

PIL Image.open creates corrupted image

Python's PIL module has been working fine for me in past projects, but I noticed that for certain images when opening and showing the color is corrupted, while for other images it is fine. However, saving it is fine for both images. Is there a reason why this only works for some images?


Example:

from PIL import Image

img = Image.open("banana.png")
img.convert("RGBA")
img.show()
img.save('out.png')
img1 = Image.open("banana2.png")
img1.convert("RGBA")
img1.show()
img1.save('out2.png')

Original Images

banana.pngbanana2.png

Shown Images

tmpi8l0e6nk.pngtmpnr61e6ib.png

Saved Images

out.pngout2.png


Furthermore, I only noticed one difference between the two images; banana.png has no color profile, while banana2.png does. Both are located in the same directory as well. I am not sure whether this has to do with the problem; it is just an observation.

Also, when reading pixel data in images, banana.png returns 0 whereas banana2.png returns (0,0,0,0) on a transparent pixel. Again, this is just an observation.

Original File Information

Screenshot

Any help would be appreciated!


Edit:

Running our program without convert has the same result:

Shown Images:

tmpj6g2tkbk.pngtmppq7nt2zg.png

Upvotes: 1

Views: 2164

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308392

When PIL displays an image with show it removes all transparency. The easiest way to do this is to just pass along whatever color values exist in those transparent areas. This will depend on the application that created the images.

Your first image has random image colors in the transparent areas, while the second one uses white.

Upvotes: 0

Ari K
Ari K

Reputation: 434

My guess is it's related to calling convert("RGBA") on an image without a color profile. PIL could require that information.

P.S. Have you tried seeing if it's still corrupted when calling show() without convert()?

Here's the PIL convert source code https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.convert

Upvotes: 1

Related Questions