保存图片后如何避免Pillow稍微编辑我的图片?

Mit*_*rek 3 python image-processing python-imaging-library python-3.x

我正在尝试创建一个生成二进制RGB图像的脚本,所有像素必须为black(0,0,0)或white(255,255,255)。问题在于,当脚本保存输出时,某些像素将具有不同黑白阴影的随机值,例如(14,14,14),(18,18,18),(241,241,241)。

#Code generated sample:
from PIL import Image
sample = Image.new('RGB', (2,2), color = (255,255,255)) 
#A four pixel image that will do just fine to this example
pixels = sample.load()
w, h = sample.size #width, height
str_pixels = ""

for i in range(w): #lines
    for j in range(h): #columns

        from random import randint
        rand_bool = randint(0,1)
        if rand_bool:
            pixels[i,j] = (0,0,0)

        str_pixels += str(pixels[i,j]) 
#This will be printed later as single block for readability

print("Code generated sample:") #The block above
print(str_pixels)

#Saved sample:

sample.save("sample.jpg")   
saved_sample = Image.open("sample.jpg")
pixels = saved_sample.load()
w, h = saved_sample.size
str_pixels = ""

for i in range(w):
    for j in range(h):
        str_pixels += str(pixels[i,j])

print("Saved sample:")
print(str_pixels)

>> Code generated sample:
>>(255, 255, 255)(0, 0, 0)(0, 0, 0)(255, 255, 255)
>>Saved sample:
>>(248, 248, 248)(11, 11, 11)(14, 14, 14)(242, 242, 242)
Run Code Online (Sandbox Code Playgroud)

一种解决方案是创建一个将其实际使用时将值更改为0或255的字母,但希望有一个更好的值。这是使用Windows测试的。

Jwe*_*ely 6

此问题源于的使用.jpg,后者使用有损空间压缩。

我建议您使用.png,这是一种无损压缩,非常适合像您这样的数据(您几乎没有什么不同的值)。您可以阅读有关.png压缩算法的信息,以了解更多信息。