I have a 3D array filled with RGB values and I need to replace some "pixels" with another value as fast as possible.
The array looks like this:
[[[ 78 77 75]
[ 72 70 67]
[ 72 70 67]
...
[ 73 74 73]
[ 71 72 71]
[ 66 67 67]]]
I used numpy select to replace some values but this is not what I need as it doesn't check for the whole pixel RGB.
np.select([array > 77, array < 77, [0, 0], array)
I tried to compare the whole RGB array with another one but it didn't work.
np.select([array != [72, 70, 77]], [[0, 0, 0]], array)
Creating a mask didn't help either. I wasn't able to replace the mask with an RGB array.
color = [30, 30, 57]
mask = np.any(array != color, axis=2)
You can define your two conditions, combine it using logical_or()
, and then use where()
:
import numpy as np
array = np.array([[[78, 77, 75],
[72, 70, 67],
[72, 70, 67]],
[[78, 77, 75],
[72, 70, 67],
[72, 70, 67]],
[[73, 74, 73],
[71, 72, 71],
[66, 67, 67]]])
color = [30, 30, 57]
cond_a = array[:, :, 0] > 77
cond_b = array[:, :, 1] < 77
conds = np.logical_or(cond_a, cond_b)
res = np.where(conds, color, array)
print(res)
[[[30 30 57]
[30 30 57]
[30 30 57]]
[[30 30 57]
[30 30 57]
[30 30 57]]
[[30 30 57]
[30 30 57]
[30 30 57]]]