pythonnumpynumpy-ndarraybackground-subtraction

Python element-wise condition on numpy ndarray


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.


Solution

  • 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]])