"Running out of colors" 为图像创建黑色蒙版时出错

"Running out of colors" error when creating black masks for images

我正在尝试创建一个干扰集,我正在用这个 for 循环来做:

for mask in input_images:
    img = Image.open(path + mask)
    print(mask)

    width = img.size[0]
    height = img.size[1]

    for i in range(0, width):  # process all pixels
        for j in range(0, height):
            data = img.getpixel((i, j))
            img.putpixel((i, j), (0, 0, 0))

    img.save(masks_path + '/' + mask[:-4] + '.png')
    print(masks_path + '/' + mask[:-4] + '.png saved!')

它基本上是获取每张图像,将每张图像的像素转换为黑色,然后复制一份。但这是它在一段时间后抛出的错误:

Traceback (most recent call last):
  File "/home/onur/PycharmProjects/masking-image/main.py", line 24, in <module>
    img.putpixel((i, j), (0, 0, 0))
  File "/home/onur/PycharmProjects/masking-image/venv/lib/python3.9/site-packages/PIL/Image.py", line 1794, in putpixel
    value = self.palette.getcolor(value, self)
  File "/home/onur/PycharmProjects/masking-image/venv/lib/python3.9/site-packages/PIL/ImagePalette.py", line 143, in getcolor
    raise ValueError("cannot allocate more than 256 colors") from e
ValueError: cannot allocate more than 256 colors

我不明白为什么我会收到这个。我只引用一种颜色,即黑色。有没有更快的方法来制作纯黑色图像副本?

我不知道你为什么要用黑色填充图像,但有一种方法可以做到:

from PIL import Image

# Load original image and convert to greyscale to save space
im = Image.open('input.png').convert('L')

# Fill with black
im.paste(0, box=(0,0,*im.size))

另一种方法是使用使每个像素为零的点处理函数:

# Make greyscale and set all pixels equal to zero
im = im.convert('L').point(lambda i: 0)