1

I have a numpy array of shape (206, 482, 3). I wanted to pick the 1st channel so I used name_of_array[:][:][0] but apparently that doesn't select the 1st channel.

I think name_of_array[:,:,0] picks the 1st channel. I don't understand why. Why name_of_array[:][:][0] != name_of_array[:,:,0]?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
DLopezG
  • 115
  • 1
  • 5

2 Answers2

3

It's important to understand what each thing does. To do this break up the action left to right. Perhaps rewriting will make this more clear:

x[:][:][0] -> ( ( x[:] )[:] )[0]  # Both are valid and equivalent Python syntax

So basically, we apply [:] to x, then [:] to the result, then [0] to this result. What does x[:]? Just return a copy of x! Thus

( (x[:])[:] )[0] == ( (x)[:] )[0] == (x[:])[0] == x[0]

This is of course, not what you expected. On the other hand,

x[:, :, 0]

returns at once the 0 column of all rows of all frames (I'm treating the index as [frame, row, col]).

kabanus
  • 24,623
  • 6
  • 41
  • 74
0

The short answer: because thats the syntax (see Numpy basics indexing).

arr[:]       == arr # full slice of all dimensions of the array 
arr[:][:]    == arr # full slice of a full slice of all dimensions 
arr[:][:][0] == arr # equal to arr[0] because the first 2 [:] slice all

vs

arr[:,:,0]  # slice all of 1st dim, slice all of 2nd dim, get 0th of 3rd arr

One way to figure things like this out yourself is to make a simplified example and experiment (heeding How to debug small programs):

import numpy as np

res = np.arange(4 * 3 * 2).reshape(4,3,2)


print(":,:,:")
print(res[:, :, :])  

print("\n1:2,1:2,:")
print(res[1:2, 1:2, :])

print("\n:,:,0")
print(res[:, :, 0])

print("\n:,:,1")
print(res[:,:,1])

Output:

# :,:,:   == all of it  
[[[ 0  1]
  [ 2  3]
  [ 4  5]]

[[ 6  7]
  [ 8  9]
  [10 11]]

[[12 13]
  [14 15]
  [16 17]]

[[18 19]
  [20 21]
  [22 23]]]

# 1:2,1:2,:
[[[8 9]]]

# :,:,0
[[ 0  2  4]
[ 6  8 10]
[12 14 16]
[18 20 22]]

# :,:,1
[[ 1  3  5]
[ 7  9 11]
[13 15 17]
[19 21 23]]

There are lots of questions about on SO, some of which are worthwhile studying to advance your knowledge (suggested as probably dupes but they do not address the confusion correctly):

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69