0

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.

tristan19954
  • 103
  • 9

2 Answers2

3

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]])
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
sehan2
  • 1,700
  • 1
  • 10
  • 23
  • 1
    I think this is reasonable if you're creating a new array, but if you're going to clobber `A` then `A[B <= 5] = 0` seems neater. But then I find `np.where()` a bit unintuitive. – Matt Hall Oct 19 '21 at 15:33
0

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.

Matt Hall
  • 7,614
  • 1
  • 23
  • 36