简体   繁体   中英

Python Numpy Matrix Operations - matrix[a==b]?

I've been trying to create a watershed algorithm and as all the examples seem to be in Python I've run into a bit of a wall. I've been trying to find in numpy documentation what this line means:

matrixVariable[A==255] = 0

but have had no luck. Could anyone explain what that operation does?

For context the line in action: label [lbl == -1] = 0

The expression A == 255 creates a boolean array which is True where x == 255 in A and False otherwise.

The expression matrixVariable[A==255] = 0 sets each index corresponding to a True value in A == 255 to 0.

EG:

import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = np.zeros([3, 3])
print('before:')
print(B)
B[A>5] = 5
print('after:')
print(B)

OUT:

[[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]
after:
[[ 0.  0.  0.]
 [ 0.  0.  5.]
 [ 5.  5.  5.]]

I assumed that matrixVariable and A are numpy arrays. If the assumption is correct then "matrixVariable[A==255] = 0" expression first gets the index of the array A where values of A are equal to 255 then gets the values of matrixVariable for those index and set them to "0"

Example:

import numpy as np

matrixVariable = np.array([(1, 3),
                           (2, 2),
                           (3,1)])

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

So A[0] and A[2] are equal to 255

matrixVariable[A==255]=0 #then sets matrixVariable[0] and matrixVariable[2] to zero

print(matrixVariable) # this would print 

[[0 0] 
 [2 2] 
 [0 0]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM