0

I created a numpy array of shape (4,3,2); I expected following code can print out a array shaped 4 X 3 or 3 X 4

import numpy as np

x = np.zeros((4,3,2), np.int32)

print(x[:][:][0])

However, I got

[[0 0]
 [0 0]
 [0 0]]

Looks like a 2 X 3? I am really confused on numpy matrix now. Shouldn't I get

  [[0 0 0]
   [0 0 0]
   [0 0 0]
   [0 0 0]]

in stead? How to do map a 3D image into a numpy 3D matrix?

For example, in MATLAB, the shape (m, n, k) means (row, col, slice) in a context of an (2D/3D) image.

Thanks a lot

1
  • 1
    In numpy the display is (panel, row, col). The first dimension is the outermost one. In MATLAB x(:)` ravels the array, making a (24,1) size. x(:,:,1) selects the first panel. Why did you try x[:][:][0]? Commented Mar 5, 2018 at 22:48

2 Answers 2

2

x[:] slices all elements along the first dimension, so x[:] gives the same result as x and x[:][:][0] is thus equivalent to x[0].

To select an element on the last dimension, you can do:

x[..., 0]
#array([[0, 0, 0],
#       [0, 0, 0],
#       [0, 0, 0],
#       [0, 0, 0]], dtype=int32)

or:

x[:,:,0]
#array([[0, 0, 0],
#       [0, 0, 0],
#       [0, 0, 0],
#       [0, 0, 0]], dtype=int32)
Sign up to request clarification or add additional context in comments.

Comments

1

You need to specify all slices at the same time in a tuple, like so:

x[:, :, 0]

If you do x[:][:][0] you are actually indexing the first dimension three times. The first two create a view for the entire array and the third creates a view for the index 0 of the first dimension

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.