Skip to content
Advertisement

Replace pixel value in RGBA numpy array

I have a 2D array of RGBA values (Ex: [30, 60, 90, 255]) and I want to replace all white [255 255 255 255] with [0 0 0 0]. What is the simplest way to do this?

Using for loops I have tried assigning a new array to an index but the index does not change:

data = np.array(img)
for y in range(img.size[0]):
    for x in range(img.size[1]):
        if (data[x][y] == [255, 255, 255, 255]).all():
            data[x][y] == [0, 0, 0, 0] # Doesn't change value at index?

Advertisement

Answer

You can use np.all to check all four values for each row and column:

>>> img = np.array([[[220, 119, 177, 145],
                     [255, 255, 255, 255]],

                    [[  3,  67,  69,  74],
                     [  1, 104, 120,  98]]])

Get the index mask with a boolean condition against [255, 255, 255, 255]:

>>> mask = np.all(img == [255, 255, 255, 255], axis=-1)
array([[False,  True],
       [False, False]])

At this point, you can either assign a four element list or one element using mask:

>>> img[mask] = 0
array([[[220, 119, 177, 145],
        [  0,   0,   0,   0]],

       [[  3,  67,  69,  74],
        [  1, 104, 120,  98]]])
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement