1
>>> from PIL import Image
>>> im = Image.open("E:\\aaa.jpeg")
>>> color = im.getpixel((100,100))
>>> print  color
   (235, 229, 205)
>>> im.putpixel((100,100),(1,1,1))
>>> im.save("E:\\new.jpeg")
>>> im=Image.open("E:\\new.jpeg")
>>> color=im.getpixel((100,100))
>>> print color
   (8, 1, 0)

The value should have been (1,1,1)....but it shows(8,1,0)

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Anshuman
  • 67
  • 1
  • 1
  • 9

1 Answers1

2

JPEG is a lossy format.

On save, your pixel data is compressed with an algorithm that does not preserve precise pixel information. When reading and decompressing that data, there is no guarantee that specific pixels will still have the exact same colour value. (8, 1, 0) is close enough, as far as the JPEG compression is concerned.

Use a different format that preserves pixel data exactly like PNG, if this is important to your application.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thank you so much for the answer, I have been stuck for quite a while. – Anshuman Jun 26 '13 at 14:22
  • Also, is there an alternative, other than changing the format? – Anshuman Jun 26 '13 at 14:23
  • @user2524452, you can change the compression factor which might help a little but the values will never be exact - it's the nature of the format. That's why it's able to make the images so much smaller. – Mark Ransom Jun 26 '13 at 14:23
  • You can try to increase the quality setting, but you'll never get JPEG to preserve everything exactly as you set it. `im.save("E:\\new.jpeg", quality=95)` is the recommended maximum, `quality=100` disables the quantisation stage, resulting in ridiculous file sizes. – Martijn Pieters Jun 26 '13 at 14:25
  • Also, see [Is Jpeg lossless when quality is set to 100?](http://stackoverflow.com/q/7982409) – Martijn Pieters Jun 26 '13 at 14:26
  • Thank you so much Mark and Martjin. Great help. :) – Anshuman Jun 26 '13 at 14:28
  • Sorry, my bad, had a typo. – Anshuman Jun 26 '13 at 14:32