Description
I have an image and its mask. I'm using PIL and Numpy to apply the following rules:
- The pixels where the mask is red
(255, 0, 0), sets to(0, 0, 0). - The pixels where the mask is green
(0, 255, 0), sets to(64, 64, 64) - The pixels where the mask is blue
(0, 0, 255), sets to(128, 128, 128) - The pixels where the mask is yellow
(255, 255, 0), sets to(255, 255, 255) - Otherwise, keep the pixel unchanged.
What I have tried
Using the idea of array mask, I tried the following:
import numpy as np
import Image
# (R G B)
red = [255, 0, 0]
green = [0, 255, 0]
blue = [0, 0, 255]
yellow = [255, 255, 0]
def execute():
im = Image.open('input.png')
data = np.array(im)
print "Original = ", data.shape
mask = Image.open('mask2.png')
data_mask = np.array(mask)
print "Mask = ", data_mask.shape
red_mask = data_mask == red
green_mask = data_mask == green
blue_mask = data_mask == blue
yellow_mask = data_mask == yellow
data[red_mask] = [0, 0, 0]
data[green_mask] = [64, 64, 64]
data[blue_mask] = [128, 128, 128]
data[yellow_mask] = [255, 255, 255]
im = Image.fromarray(data)
im.save('output.png')
if __name__ == "__main__":
execute()
The problem
The code above outputs:
Original = (64, 64, 3)
Mask = (64, 64, 3)
ValueError: NumPy boolean array indexing assignment cannot assign 3 input values to the 5012 output values where the mask is true
Am I missing something? How can I use the idea of array masks to change pixels values?
import Imagerather thanfrom PIL import Image, that implies that you're using PIL rather than its modern fork Pillow. Unless you really need backward compatibility with very old versions of Python, or with code that for some reason won't work with Pillow (there shouldn't be any such thing, but there are always bugs, right?), don't do that.