Home > Mobile >  How many columns/rows in this array?
How many columns/rows in this array?

Time:09-26

I know this is probably a stupid question (bare with me please). When I print out an array that has a shape (2, 493, 452), there should be 2 rows right? How come it looks like multiple rows below (e.g. first row is [ 0 0 0...0 0 0]) And then for the second output (2, 222836), this means there are 2 rows and 222836 columns?

(2, 493, 452)
[[[  0   0   0 ...   0   0   0]
  [  1   1   1 ...   1   1   1]
  [  2   2   2 ...   2   2   2]
  ...
  [490 490 490 ... 490 490 490]
  [491 491 491 ... 491 491 491]
  [492 492 492 ... 492 492 492]]

 [[  0   1   2 ... 449 450 451]
  [  0   1   2 ... 449 450 451]
  [  0   1   2 ... 449 450 451]
  ...
  [  0   1   2 ... 449 450 451]
  [  0   1   2 ... 449 450 451]
  [  0   1   2 ... 449 450 451]]]
(2, 222836)
[[  0   0   0 ... 492 492 492]
 [  0   1   2 ... 449 450 451]]

This is my code:

original_image=cv2.imread("mickey mouse.jpg")
img=cv2.cvtColor(original_image,cv2.COLOR_BGR2RGB)
vectorized=img.reshape((-1,3))
#print(vectorized.shape)
#print(vectorized)
ind=np.indices((m,n))
print(ind.shape)
print(ind)

ind.resize((2,m*n))
print(ind.shape)
print(ind)

CodePudding user response:

indices makes 'indices' for each of the 2 dimensions:

ind=np.indices((m,n))
print(ind.shape)
print(ind)

So the result is a (2,m,n) array. ind[9,:,:] are indices for the first demension, an (m,n) array.

Actually this should be reshape, but it makes (2, m*n) shape array from the original ind.

ind.resize((2,m*n))
print(ind.shape)
print(ind)

Rows/columns does not make a whole lot of sense when talking about these index arrays.

Look at a smaller case (from another recent SO, How to get all indices of NumPy array, but not in a format provided by np.indices())

In [71]: list(np.ndindex(3,2))
Out[71]: [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
In [72]: np.indices((3,2))
Out[72]: 
array([[[0, 0],
        [1, 1],
        [2, 2]],

       [[0, 1],
        [0, 1],
        [0, 1]]])

meshgrid does the same thing, but as a list of 2 arrays:

In [75]: np.meshgrid(np.arange(3),np.arange(2),indexing='ij')
Out[75]: 
[array([[0, 0],
        [1, 1],
        [2, 2]]),
 array([[0, 1],
        [0, 1],
        [0, 1]])]

CodePudding user response:

When you have a numpy array with shape (2, 493, 452) and you print it out on the console, numpy will print it like it is 2 arrays with shape (493, 452). This threw me off for a long time. Perhaps you might be thinking about the original array like 452 arrays of shape (2, 493), in which case you might expect the console output to differ.

The shape will always be given by arr.shape even if the console output does not match what you expect.

  • Related