0

I have a Python NumPy array like this:

array([[[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0, 125, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]]], dtype=uint8)

And I'm trying to get the index of 125 inside the array with 2 numbers in it. At first I had only 3 values, instead of 4, and this worked to get the indexed position:

p = np.unravel_index(tiles[tileindex].argmax(), tiles[tileindex].shape)

Can't seem to find what I need to use now instead of argmax(); the value 125, can be 255 as well, so I'd like to make my selection based on the number of non-zero values in the nested arrays instead of the value itself.

So basically, how to find the line with two values, and then get the position of 125 in this example.

Any help much appreciated.

MarianD
  • 13,096
  • 12
  • 42
  • 54
hdries
  • 121
  • 9

2 Answers2

1

This will return the position of the value of interest, with both its first and second axis' index:

axis0, axis1 = np.where((a > 0).cumsum(2)[...,-1] > 1)

Or similarly:

axis0, axis1 = np.where((a>0).view('i1').sum(-1) > 1)

print(axis0)
#2
print(axis1)
#0
print(a[axis0, axis1])
# array([[  0,   0, 125, 255]])
yatu
  • 86,083
  • 12
  • 84
  • 139
0

I'm not sure to totally understand the question, but you say you want to select on the number of non-zeros, so you can use np.count_nonzero

Let say that we call A the matrix you set in your question. A first option, not optimal but more readable is the following

for a in A:
    print( np.count_nonzero(a,axis=1) # print just for example here, you can stock it

And you will have, as a result, for each submatrix of your array A a vector with number of nonzero by lines. You can see that for the fourth matrix, you have two non-zeros values on the first line

[1 1 1 1 1 1 1 1]

[1 1 1 1 1 1 1 1]

[2 1 1 1 1 1 1 1] -> two non-zeros values on the first line

[1 1 1 1 1 1 1 1]

You can do it in a shorter way like this

np.count_nonzero(A,axis=2)
Guilhem L.
  • 421
  • 2
  • 8