I have two numpy ndarrays of the same shape.
A = [[12, 25, 6],
[28, 52, 74]]
B = [[100, 2, 4],
[2, 12, 14]]
My goal is to replace every element where there the value in B is <= 5 by 0 in A. So my result should be :
# So C[0][0] = 12 because A[0][0] = 12 and B[0][0] >= 5
C = [[12, 0, 0],
[0, 52, 74]]
Is there an efficient way to do this? For context, this is to try to do some background substraction on images, and replace all background by black color.
CodePudding user response:
Here you go:
A = np.array([[12, 25, 6],[28, 52, 74]])
B = np.array([[100, 2, 4],[2, 12, 14]])
A = np.where(B <= 5, 0, A)
Output:
array([[12, 0, 0],
[ 0, 52, 74]])
CodePudding user response:
If you want a new array, I would do this:
C = A.copy()
C[B <= 5] = 0
It's a bit faster than np.where()
on my machine anyway.
If you don't mind overwriting A
, just do A[B <= 5] = 0
.