I'm trying to create a script that generate binary RGB images, all pixels must be black(0,0,0) or white(255,255,255). The problem is that when the script saves the output, some pixels will have random values of different shades of black and white such as (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)
A solution would be to create a philter that changes the values to 0 or 255 when those values will be actually on use, but hopefully there's a better one. This was tested using Windows.