PIL JPEG pixel problem

Carl Banks imbosol at vt.edu
Tue Jan 7 14:33:29 EST 2003


Mark wrote:
> I'm having problems changing the pixels in a .jpg file.
> 
>>>>import Image
>>>> x = Image.open('te.jpg')
>>>> x.getpixel((0,0))
> (255, 255, 255)
>>>> x.putpixel((0,0),(100,150,165))
>>>> x.save('asdf.jpg')
>>>>
>>>> x = Image.open('asdf.jpg')
>>>> x.getpixel((0,0))
> (146, 146, 146)
> 
> When I open it up after changing the pixels they are I get totally
> different pixels from (100,150,165) to (146,146,146).  I've tried
> using the different options in the save() method(not all possible
> combonations), but they always are different.  Does anyone know how I
> can fix this?

Yes, use a different image format.  JPEG uses lossy compression when
it saves an image, meaning that it sacrifices exact pixel values for
better compression ratios.

A single off-color pixel, such as what you wrote to your image, has no
chance of surviving a JPEG compression.  This is because it adds very
little to the overall impression of the image, yet worsens the
compression ratio quite a bit.  The compressor essentially changes the
off-color pixel to something resembling its surroundings.


Depending on what your purpose is, you have two options.  You could
use JPEG, but make sure you write enough pixels to have an big effect
on the overall image (like if you're adding a logo), and don't worry
about exact pixel values because they're just not going to be right.

Or use a non-lossy image format such as PNG.  PNG might be a good
choice because most modern web browsers can display it.


-- 
CARL BANKS




More information about the Python-list mailing list