Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy array loses dimension upon assignment/copy, why?

I have the following code:

print(type(a1), a1.shape)
a2 = a1                  #.reshape(-1,1,2) this solves my problem
print(type(a2), a2.shape)

The output is:

<class 'numpy.ndarray'> (8, 1, 2)
<class 'numpy.ndarray'> (8, 2)

I know the (commented out) reshape solves my problem, however, I'd like to understand why a simple assignment results in losing the central dimension of the array.

Does anybody know what is going on? Why referring to the array with another name changes its dimensions?

like image 250
Tony Power Avatar asked Oct 18 '25 12:10

Tony Power


2 Answers

Looking at the openCV script mentioned in the comments, the reshape to three dimensions is necessary because a dimension is being lost via Boolean indexing, and not by the assignment alone.

The names of the arrays in that script which motivated the question are p0 and good_new.

Here is a breakdown of the operations in that script:

  1. p0 is a 3D array with shape (17, 1, 2).

  2. The line:

    p1, st, err = cv.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)
    

    creates new arrays, with array p1 having shape (17, 1, 2) and array st having shape (17, 1).

  3. The assignment good_new = p1[st==1] creates a new array object by a Boolean indexing operation on p1. This is a 2D array has shape (17, 2). A dimension has been lost through the indexing operation.

  4. The name p0 needs to be assigned back to the array data contained in good_new, but p0 also needs to be 3D. To achieve this, the script uses p0 = good_new.reshape(-1, 1, 2).


For completeness, it is worth summarising why the Boolean indexing operation in step (3) results in a dimension disappearing.

The Boolean array st == 1 has shape (17, 1) which matches the initial dimensions of p1, (17, 1, 2).

This means that the selection occurs in the second dimension of p1: the indexer array st == 1 is determining which arrays of shape (2,) should be in the resulting array. The final array will be of shape (n, 2), where n is the number of True values in the Boolean array.

This behaviour is detailed in the NumPy documentation here.

like image 181
Alex Riley Avatar answered Oct 21 '25 02:10

Alex Riley


I am not sure why your are getting this.but it should not return like this.Can you please share how your a1 has been created.

I tried like below but not able to re create it

a1=np.ones((8,1,2),dtype=np.uint8)
print(type(a1), a1.shape)

<class 'numpy.ndarray'> (8, 1, 2)

a2=a1

print(type(a2), a2.shape)

<class 'numpy.ndarray'> (8, 1, 2)`
like image 32
Ajit Singh Avatar answered Oct 21 '25 01:10

Ajit Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!