0

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?
1
  • 2
    Don't use nested loops: this is very inefficient. Use vectorized operations instead. Note that the np.array conversion may convert values to floats in the [0,1] range and not [0,255]. Not to mention only data may be modified and not img if it is a deep copy. Commented Aug 4, 2021 at 18:12

2 Answers 2

2

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]]])
Sign up to request clarification or add additional context in comments.

Comments

1
data[x][y] == [0, 0, 0, 0] # Doesn't change value at index?

should be :

data[x][y] = [0, 0, 0, 0]

1 Comment

Definitely didn't notice that careless mistake lmao

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.