WilliamG
WilliamG

Reputation: 137

Pillow - Change every pixel's RGB value

I'm new to python and am trying to learn pil. I want to lower every pixels rgb value by 1. For examle (100, 239, 54) should be (99, 238, 53). However once the picture is saved it doesn't have the pixel values i saved to it. But not identical to the original picture either.

from PIL import Image 

img = Image.open('dog2.jpg', 'r') 
imgdata = list(img.getdata())
print(imgdata[:5])

imgdata = [val for sublist in imgdata for val in sublist]
for i, pixbit in enumerate(imgdata):
    imgdata[i] -= 1
imgdata = list(zip(*[iter(imgdata)]*3))

print(imgdata[:5])

newimg = Image.new(img.mode, img.size)
newimg.putdata(imgdata)
newimg.save('newimg.jpg')

img = Image.open('newimg.jpg', 'r')
print(list(img.getdata())[:5])

The three prints prints:

[(36, 79, 86), (36, 79, 86), (36, 79, 86), (36, 79, 86), (37, 80, 87)]
[(35, 78, 85), (35, 78, 85), (35, 78, 85), (35, 78, 85), (36, 79, 86)]
[(36, 79, 88), (36, 79, 88), (36, 79, 88), (36, 79, 88), (36, 79, 88)]

The last print should be identical to the second one.

Could anyone explain to me why this is? Thank you!

Upvotes: 1

Views: 491

Answers (1)

Imperishable Night
Imperishable Night

Reputation: 1533

JPEG is a lossy compression format, which means you should not expect to retrieve the exact same pixel values you saved. If you want exact values, you should probably try PNG.

Upvotes: 1

Related Questions