Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL changes pixel value when saving

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.

like image 401
Ethan Avatar asked Jul 22 '12 19:07

Ethan


People also ask

How do I save a PIL library image?

save() Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword options can be used to provide additional instructions to the writer.

What is pixel value in image processing?

Images are stored in the form of a matrix of numbers in a computer where these numbers are known as pixel values. These pixel values represent the intensity of each pixel. 0 represents black and 255 represents white.

What do pixel values mean?

Each of the pixels that represents an image stored inside a computer has a pixel value which describes how bright that pixel is, and/or what color it should be. In the simplest case of binary images, the pixel value is a 1-bit number indicating either foreground or background.


1 Answers

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

like image 63
fraxel Avatar answered Oct 19 '22 04:10

fraxel