我正在尝试创建一个生成二进制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 …Run Code Online (Sandbox Code Playgroud)