Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently rotate a set of points with a rotation matrix in numpy

Tags:

I have a list of 3D points stored in numpy array A with shape (N,3) and a rotation matrix R with shape (3,3). I'd like to compute the dot product of R.x for each point x in A in-place. Naively I can do this:

for n in xrange(N):     A[n,:] = dot(R, A[n,:])  

Is there a way to vectorize this with a native numpy call? If it matters, N is on order of a couple thousand.

like image 939
Hooked Avatar asked Aug 27 '12 19:08

Hooked


People also ask

How do I rotate a matrix in NumPy?

NumPy: rot90() function The rot90() function is used to rotate an array by 90 degrees in the plane specified by axes. Rotation direction is from the first towards the second axis. Array of two or more dimensions. Number of times the array is rotated by 90 degrees.

How do you rotate a set of points in Python?

How do you rotate a set of points in Python? To rotate multiple points (x1,y1), (x2,y2), , use: points = np. this is a great solution. Using this function I sometimes get negative coordinates when my original coordinates are within [0,127] and I set the rotation center as (63.5,63.5).

How do you rotate a matrix 90 degrees in Python using NumPy?

The numpy. rot90() method performs rotation of an array by 90 degrees in the plane specified by axis(0 or 1). Parameters : array : [array_like]i.e. array having two or more dimensions.

How do you rotate a point matrix?

To perform the rotation on a plane point with standard coordinates v = (x, y), it should be written as a column vector, and multiplied by the matrix R: If x and y are the endpoint coordinates of a vector, where x is cosine and y is sine, then the above equations become the trigonometric summation angle formulae.


2 Answers

You can multiply A with the transpose of the rotation matrix:

A = dot(A, R.T) 
like image 180
Aapo Kyrola Avatar answered Sep 20 '22 20:09

Aapo Kyrola


There's a couple of minor updates/points of clarification to add to Aapo Kyrola's (correct) answer. First, the syntax of the matrix multiplication can be slightly simplified using the recently added matrix multiplication operator @:

A = A @ R.T 

Also, you can arrange the transformation in the standard form (rotation matrix first) by taking the transpose of A prior to the multiplication, then transposing the result:

A = (R @ A.T).T 

You can check that both forms of the transformation produce the same results via the following assertion:

np.testing.assert_array_equal((R @ A.T).T, A @ R.T) 
like image 24
tel Avatar answered Sep 18 '22 20:09

tel