Home > Software design >  how np.all works with axis
how np.all works with axis

Time:03-10

I've tried to use np.all to translate arrays. but the results seems not worked as i expected.

x = np.array([[
        [0, 255, 0],
        [255, 0, 255]],
       [[0, 0, 0],
        [0, 255, 0]],
       [[0, 0, 0],
        [0, 0, 0]]
])
label = np.array([255, 0, 0])
ret = np.all(x == label, axis=0)
print(ret)

results:

[[False False  True]
 [False False False]]

expected:

[[False True False]
 [True False True ]]

As i think, compare array at dimension 0, should works as this:

x[:,0,0] == [255, 0, 0], x[:,0,1] == [255, 0, 0], x[:,0,2] == [255, 0, 0]
x[:,1,0] == [255, 0, 0], x[:,1,1] == [255, 0, 0], x[:,1,2] == [255, 0, 0]

but the result seems not working so. Most curiously is that if i change dimension to 1

ret = np.all(x == label, axis=1)

I've also got a result like this:

[[False False False]
 [False False  True]
 [False  True  True]]

the variable x's dimension 1 has a size of 2, how can it compared with an array which size is 3 and got a True result!

CodePudding user response:

x is (3,2,3), label is (3,)

x == label broadcasts label to (1,1,3)

The all reduces the first axis leaving (2,3)

So the test is x[0,0,:] == [255, 0, 0] etc

  • Related