简体   繁体   English

Python Numpy矩阵运算-矩阵[a == b]?

[英]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. 我一直在尝试创建一个分水岭算法,并且所有示例似乎都在Python中,因此我碰到了一堵墙。 I've been trying to find in numpy documentation what this line means: 我一直试图在numpy文档中找到这行的含义:

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 对于上下文,该行在label [lbl == -1] = 0label [lbl == -1] = 0

The expression A == 255 creates a boolean array which is True where x == 255 in A and False otherwise. 表达式A == 255创建一个布尔数组,该数组为True ,其中A中x == 255,否则为False

The expression matrixVariable[A==255] = 0 sets each index corresponding to a True value in A == 255 to 0. 表达式matrixVariable[A==255] = 0将与A == 255中的True值相对应的每个索引设置为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. 我假设matrixVariable和A是numpy数组。 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" 如果假设正确,则“ matrixVariable [A == 255] = 0”表达式首先获取数组A的索引,其中A的值等于255,然后获取这些索引的matrixVariable值并将其设置为“ 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 所以A [0]和A [2]等于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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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