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:
JavaScript
x
6
1
data = np.array(img)
2
for y in range(img.size[0]):
3
for x in range(img.size[1]):
4
if (data[x][y] == [255, 255, 255, 255]).all():
5
data[x][y] == [0, 0, 0, 0] # Doesn't change value at index?
6
Advertisement
Answer
You can use np.all
to check all four values for each row and column:
JavaScript
1
6
1
>>> img = np.array([[[220, 119, 177, 145],
2
[255, 255, 255, 255]],
3
4
[[ 3, 67, 69, 74],
5
[ 1, 104, 120, 98]]])
6
Get the index mask with a boolean condition against [255, 255, 255, 255]
:
JavaScript
1
4
1
>>> mask = np.all(img == [255, 255, 255, 255], axis=-1)
2
array([[False, True],
3
[False, False]])
4
At this point, you can either assign a four element list or one element using mask
:
JavaScript
1
7
1
>>> img[mask] = 0
2
array([[[220, 119, 177, 145],
3
[ 0, 0, 0, 0]],
4
5
[[ 3, 67, 69, 74],
6
[ 1, 104, 120, 98]]])
7