1

I have three numpy arrays: A, B, and C. I have to extract '1' that is common (pixel wise) to any two of the given arrays, and set all other elements as 0.

import numpy as np

A = np.array([[1,0,0,0,0],
               [1,0,0,0,0],
               [1,0,0,0,0]])              

B = np.array([[1,1,1,1,1],
               [1,1,1,1,1],
               [1,1,1,1,1]])

C = np.array([[0,0,0,0,1],
               [0,0,0,0,1],
               [0,0,0,0,1]])

The expected answer would be:

result = np.array([[1,0,0,0,1],
               [1,0,0,0,1],
               [1,0,0,0,1]])

How can I do it using Numpy/Scipy? A faster performance is necessary since in my real problem, the number of arrays are 50s and the size of each array is (3000, 3000), and I have to extract the '1' if common to 30 arrays.

1
  • result = (A & B) | (A & C) | (B & C) Commented Oct 12, 2020 at 12:09

1 Answer 1

2

Sum them and then use boolean operations to check whether the elements are >=2.

import numpy as np

A = np.array([[1,0,0,0,0],
               [1,0,0,0,0],
               [1,0,0,0,0]])              

B = np.array([[1,1,1,1,1],
               [1,1,1,1,1],
               [1,1,1,1,1]])

C = np.array([[0,0,0,0,1],
               [0,0,0,0,1],
               [0,0,0,0,1]])

D = A + B + C

D = (D >= 2).astype(int)

print(D)
#[[1 0 0 0 1]
# [1 0 0 0 1]
# [1 0 0 0 1]]

(D >= 2).astype(int) will return True for each value that is >=2 and False otherwise. You then convert it from True/False values to 1/0 values using .astype(int).

You mention in your question that in your real case you could have up to 50 arrays? Either store them in a list and use sum() or store them in a 3-dimensional numpy array and use your_numpy_array.sum().

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. Does it really work for my 50 arrays when extracting common in any 30 arrays as follows: (D >= 30).astype(int)?
The shape of my array in the real case is (50L, 3000L, 3000L). How can I apply axis?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.