Reputation: 113
Is there any way to vectorize this code. It is similar to bitwise and? IF "A" is a greyscale image and "B" is a binary image and "C" is matrix of same size of "A" containing zeroes
for row in range(A.shape[0]):
for col in range(A.shape[1]):
if B[row, col] == 1:
C[row, col] = ~A[row, col]
else:
C[row, col] = A[row, col]
Upvotes: 1
Views: 65
Reputation: 19382
If A, B, and C are numpy
arrays of the same size, you can do operations on the whole array, with approximately the same code you would write for each value.
So, you can do a B == 1
to get a boolean array of the same size as B
e.g. [True, False, True, False]
. A C[B == 1]
will then be a sub-array of C
at all indices at which B
contains 1
.
To sum it all up, you can do this:
C[B == 1] = ~A[B == 1]
C[B != 1] = A[B != 1]
Alternatively, if you don't even have a C
to start with:
C = A.copy()
C[B == 1] = ~C[B == 1]
BTW, I would recommend using a
, b
, and c
rather than A
, B
, and C
, because that is how we usually name variables in Python. See PEP-8 for more info.
Upvotes: 1