Search code examples
pythonarraysnumpyfor-loopvalueerror

Numpy error:"ValueError: cannot copy sequence with size 2 to array axis with dimension 4" in python


I have error in my code and I did code for test.
A little description for my testing code: I imported numpy module.
I did variable for starting coordinate and then did array 7×4.
After that I came in cycle for and iterating over the array where I did steps x by 10 and y by 5 from variable for starting coordinate.
Then I added x and y in cortege and cortege in array.
Printed array:3** When I started code I had it:

ValueError: cannot copy sequence with size 2 to array axis with dimension 4

How to slove this error?
Here is CODE:

import numpy as np

#FOR TEST

pose = (640, 154)

all_poses = np.zeros((1, 7, 4))


for i in range(0, 6):
    for j in range(0, 4):
        y = pose[1] - i * 5
        x = pose[0] - j * 10
        cortege = (x, y)
        all_poses[i, j] = cortege

print(all_poses) 

Solution

  • The reason you are getting the error is that the dimensions of cortege are 1x2, whereas the dimensions of all_poses[i, j] are 1x4. So when you do all_poses[i, j] = cortege, you are doing something like [0, 0, 0, 0] = [650, 154]. The dimensions don't match here and you get the error.

    A way to avoid the error would be make the dimensions of all_poses in the beginning to 7x2 instead of 7x4, or do all_poses[i, j] = cortege*2, which will add [650, 154, 650, 154] to all_poses[i, j], thus matching the dimensions. Though what you do to avoid the error depends on what you want to achieve with the code, which is not clear in your question. Could you explain what exactly you want your code to do?