Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...