I'm trying to create a distractor set and I'm doing that with this for loop:
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!')
It basically takes every image, converts the pixel of every image to black, and makes a copy of it. But this is the error it's throwing after a while:
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
I don't understand why I'm getting this. I am only referencing one color, which is black. Is there a quicker way to make purely black copies of images?
CodePudding user response:
I have no idea why you would want to fill an image with black, but here's a way to do it:
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))
Another way to do it is with a point processing function that makes each pixel zero:
# Make greyscale and set all pixels equal to zero
im = im.convert('L').point(lambda i: 0)