PIL changes pixel value when saving

2020-04-05 07:55发布

This is as simple as it gets. Make RGB image, one pixel big. Set pixel value to (a,b,c). Save. Problem is, the saved image has a different pixel value then (a,b,c). Usually, with +-1 on one of the channels, as if it were random noise, but its consistent. Heres the code:

from PIL import Image
newImg = Image.new('RGB', (1,1), "black")
pixels = newImg.load()
pixels[0,0] = (0,3,0)
newImg.save("point.jpg")
savedImage = Image.open("point.jpg")
pixelsSaved = savedImage.load()

print pixels[0,0]
print pixelsSaved[0,0]

The output from this is: (0, 3, 0) (1, 3, 0)

consistently.

If I use (4, 2, 0) as the pixel to save, the output is: (4, 2, 0) (3, 2, 0)

and (0,10,0) gives: (0, 10, 0) (0, 10, 1)

for example.

Why does the value change upon saving? How do I prevent it? Please help.

Thanks.

2条回答
forever°为你锁心
2楼-- · 2020-04-05 08:30

JPG doesn't promise to store precisely the pixels you intended. It compresses your data to make the file smaller, and the compression is based on human perception. The idea is to create an array of pixels that appear the same to a human, even though they are different pixels.

So the pixel you are writing is in the output, but the adjacent pixels have been altered to be able to store the entire image in less space. This is called "lossy compression" because data is lost.

Other image formats don't have this property. PNG is a lossless compressed format, meaning precisely the same pixels will results after decompressing a compressed PNG. If you save your image as a PNG, you will have the result you want.

查看更多
霸刀☆藐视天下
3楼-- · 2020-04-05 08:40

Save it as a .png. .jpg is a lossy compressed format.

查看更多
登录 后发表回答