简体   繁体   中英

How to rotate an array of indices in numpy?

I have a grid which is a numpy array of shape (522, 476) .

I then have another numpy array which is a trajectory of individual xy points (indices of the grid) of shape (2, 3866) .

I rotate the grid successfully using np.rot90(grid) . My question is how do I rotate the trajectory in the same way such that the individual xy points continue to be aligned with the grid.

If you always want to rotate 90 degrees just once and always the same direction (so rot90 without any other arguments) you can use this formula:

idx2 = np.array([[n.shape[0]-1-x[1], x[0]] for x in idx])

Assuming idx is your indices array (2, 3866) and n is the grid you want to index (522, 476). It simply uses the knowledge of what single rotation does to the elements, which is it switches first dimension to the second and makes the second dimension counted from the end the first dimension.

You can define a rotate function :

def rotate(origin, point, angle):
    """
    Rotate a point counterclockwise by a given angle around a given origin.

    The angle should be given in radians.
    """
    ox, oy = origin
    px, py = point

    qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
    qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
    return qx, qy

And then apply this function to all (X,Y) points of your trajectory.

origin = tuple(0, 0)
newTrajectory = []
for i in range(0:len(trajectory[0])):
    p = tuple(trajectory[i][0], trajectory[i][1])
    newP = rotate(origin, p, math.pi/2)
    row = [newP[0], newP[1]]
    newTrajectory.append(row)

Best

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM