1

I have two arrays 5x5x3:

A = np.random.randint(0, 255, (5,5,3), np.uint8)
B = np.random.randint(0, 255, (5,5,3), np.uint8)

and I need to populate a third array C (same shape of A and B) populating its values from A or B according to the values in A.

Pure Python code should be:

C = np.zeros(A.shape, dtype=np.uint8) 
h, w, ch = C.shape

for y in range(0, h):
    for x in range(0, w):
        for z in range(0, ch):
            if A[y, x, z] > 128:
                C[y, x, z] = max(A[y, x, z], B[y, x, z])
            else:
                C[y, x, z] = min(A[y, x, z], B[y, x, z])

The above code works but it's very slow with big arrays. My attempt with numpy was the following:

C = np.zeros(A.shape, dtype=np.uint8) 
C[A>128] = max(A,B)
C[A<128] = min(A,B) 

but the output was:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
1
  • max is the Python scalar function. I think you want np.maximum(A,B), an elementwise maximum. Commented Nov 1, 2019 at 16:15

3 Answers 3

2

With np.where you can avoid creating empty array before. np.maximum, np.minimum return arrays with the same shape as A and B. Condition A>128 will select from them correct values

С = np.where(A>128, np.maximum(A,B), np.minimum(A,B))
Sign up to request clarification or add additional context in comments.

1 Comment

np.where() is undisputably the right tool for the job. It's made for this, unless the workarounds others use.
0

Try the following code:

C = np.zeros(shape=A.shape)
C = (A>128)*np.maximum(A,B)+(A<=128)*np.minimum(A,B)

It was 5 times faster for me.

Comments

0

Pythons min/max functions does not seem to work element-wise on numpy ndarrays (which it seems like you are looking for)

You should be able to use np.maximum and np.minimum instead

C[A>128] = np.maximum(A,B)[A>128]
C[A<=128] = np.minimum(A,B)[A<=128]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.