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()
maxis the Python scalar function. I think you wantnp.maximum(A,B), an elementwise maximum.