Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate angle from matrix transform

Tags:

c#

math

wpf

matrix

I have following line of code: I have applied few rotation to the rectangle at without knowing values (of how many degrees). Now I want to get Rotation or angle of element in 2D.

Rectangle element = (Rectangle)sender;
MatrixTransform xform = element.RenderTransform as MatrixTransform;
Matrix matrix = xform.Matrix;
third.Content = (Math.Atan(matrix.M21 / matrix.M22)*(180/Math.PI)).ToString();

and the matrix is like following
|M11 M12 0|
|M21 M22 0|
|dx  dy  1|  which is Transformation Matrix I guess !!

This does not seems to be correct value. I want to get angles in 0 to 360 degrees

like image 779
Hiren Desai Avatar asked Jan 02 '13 16:01

Hiren Desai


People also ask

How do you convert a rotation matrix to an angle?

Given a rotation matrix R, we can compute the Euler angles, ψ, θ, and φ by equating each element in R with the corresponding element in the matrix product Rz(φ)Ry(θ)Rx(ψ). This results in nine equations that can be used to find the Euler angles. Starting with R31, we find R31 = − sin θ.

How do you transform a matrix into a point?

When you want to transform a point using a transformation matrix, you right-multiply that matrix with a column vector representing your point. Say you want to translate (5, 2, 1) by some transformation matrix A. You first define v = [5, 2, 1, 1]T.


2 Answers

FOR FUTURE REFERENCE:

This will give you the rotation angle of a transformation matrix in radians:

var radians = Math.Atan2(matrix.M21, matrix.M11);

and you can convert the radians to degrees if you need:

var degrees = radians * 180 / Math.PI;
like image 82
Eren Ersönmez Avatar answered Sep 24 '22 09:09

Eren Ersönmez


You can use this:

var x = new Vector(1, 0);
Vector rotated = Vector.Multiply(x, matrix);
double angleBetween = Vector.AngleBetween(x, rotated);

The idea is:

  1. We create a tempvector (1,0)
  2. We apply the matrix transform on the vector and get a rotated temp vector
  3. We calculate the angle between the original and the rotated temp vector

You can play around with this:

[TestCase(0,0)]
[TestCase(90,90)]
[TestCase(180,180)]
[TestCase(270,-90)]
[TestCase(-90, -90)]
public void GetAngleTest(int angle, int expected)
{
    var matrix = new RotateTransform(angle).Value;
    var x = new Vector(1, 0);
    Vector rotated = Vector.Multiply(x, matrix);
    double angleBetween = Vector.AngleBetween(x, rotated);
    Assert.AreEqual(expected,(int)angleBetween);
}
like image 21
Johan Larsson Avatar answered Sep 23 '22 09:09

Johan Larsson