简体   繁体   English

PIL 保存时改变像素值

[英]PIL changes pixel value when saving

This is as simple as it gets.这很简单。 Make RGB image, one pixel big.制作一个像素大的 RGB 图像。 Set pixel value to (a,b,c).将像素值设置为 (a,b,c)。 Save.救球。 Problem is, the saved image has a different pixel value then (a,b,c).问题是,保存的图像与 (a,b,c) 具有不同的像素值。 Usually, with +-1 on one of the channels, as if it were random noise, but its consistent.通常,其中一个通道上有 +-1,就好像它是随机噪声一样,但它是一致的。 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)其输出为:(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)如果我使用 (4, 2, 0) 作为要保存的像素,则输出为: (4, 2, 0) (3, 2, 0)

and (0,10,0) gives: (0, 10, 0) (0, 10, 1)和 (0,10,0) 给出: (0, 10, 0) (0, 10, 1)

for example.例如。

Why does the value change upon saving?为什么值在保存时会发生变化? How do I prevent it?我该如何预防? Please help.请帮忙。

Thanks.谢谢。

Save it as a .png .将其另存为.png .jpg is a lossy compressed format. .jpg是一种有损压缩格式。

JPG doesn't promise to store precisely the pixels you intended. JPG 不承诺准确存储您想要的像素。 It compresses your data to make the file smaller, and the compression is based on human perception.它压缩您的数据以使文件更小,并且压缩是基于人类感知的。 The idea is to create an array of pixels that appear the same to a human, even though they are different pixels.这个想法是创建一个像素阵列,这些像素对人类来说看起来是一样的,即使它们是不同的像素。

So the pixel you are writing is in the output, but the adjacent pixels have been altered to be able to store the entire image in less space.因此,您正在写入的像素在输出中,但相邻像素已被更改,以便能够在更小的空间中存储整个图像。 This is called "lossy compression" because data is lost.这称为“有损压缩”,因为数据会丢失。

Other image formats don't have this property.其他图像格式没有此属性。 PNG is a lossless compressed format, meaning precisely the same pixels will results after decompressing a compressed PNG. PNG 是一种无损压缩格式,这意味着解压缩压缩的 PNG 后会产生完全相同的像素。 If you save your image as a PNG, you will have the result you want.如果将图像保存为 PNG,您将获得所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM