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
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;
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:
We create a tempvector (1,0)
We apply the matrix transform on the vector and get a rotated temp vector
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);
}
Your answers will be in radians, http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/c14fd846-19b9-4e8a-ba6c-0b885b424439/.
So simply convert the values back to degrees using the following:
double deg = angle * (180.0 / Math.PI);
Related
I am using following thread to perform angle detection for a rectangle image.
Detect centre and angle of rectangles in an image using Opencv
I am stuck at following piece of code.
cv::Point2f edge1 = cv::Vec2f(rect_points[1].x, rect_points[1].y) - cv::Vec2f(rect_points[0].x, rect_points[0].y);
cv::Point2f edge2 = cv::Vec2f(rect_points[2].x, rect_points[2].y) - cv::Vec2f(rect_points[1].x, rect_points[1].y);
cv::Point2f usedEdge = edge1;
if(cv::norm(edge2) > cv::norm(edge1)) usedEdge = edge2;
cv::Point2f reference = cv::Vec2f(1,0); // horizontal edge
angle = 180.0f/CV_PI * acos((reference.x*usedEdge.x + reference.y*usedEdge.y) / (cv::norm(reference) *cv::norm(usedEdge)));
I am not able to figure out following few lines which i required to convert in emgu csharp.
cv::Point2f edge1 = cv::Vec2f(rect_points[1].x, rect_points[1].y) - cv::Vec2f(rect_points[0].x, rect_points[0].y);
cv::Point2f edge2 = cv::Vec2f(rect_points[2].x, rect_points[2].y) - cv::Vec2f(rect_points[1].x, rect_points[1].y);
angle = 180.0f/CV_PI * acos((reference.x*usedEdge.x + reference.y*usedEdge.y) / (cv::norm(reference) *cv::norm(usedEdge)));
if(cv::norm(edge2) > cv::norm(edge1)) usedEdge = edge2;
cv::Point2f reference = cv::Vec2f(1,0);
Can anyone help me how to resolve the same? Any help or suggestion will be highly appreciated?
The Point2f here are simply points, having float precision properties of X and Y, being used to store 2D vectors of I and J. Their method if declaration is setting the edges to be the vector between two points, i.e. the delta between those two points. In C#, I would write this as:
float deltaX = rect_points[1].X - rect_points[0].X;
float deltaY = rect_points[1].Y - rect_points[0].Y;
PointF edge1 = new PointF(deltaX, deltaY);
OR of course...
PointF edge1 = new PointF(rect_points[1].X - rect_points[0].X, rect_points[1].Y - rect_points[0].Y);
PointF edge2 = new PointF(rect_points[2].X - rect_points[1].X, rect_points[2].Y - rect_points[1].Y);
These PointF are now the two vectors, or edges, that join at rect_points[1]. Next, norm is performed in order to compare the magnitude of the two. This is simply Pythagoras if we perform the same manually:
edge1Magnitude = Math.Sqrt(Math.Pow(edge1.X, 2) + Math.Pow(edge1.Y, 2));
edge2Magnitude = Math.Sqrt(Math.Pow(edge2.X, 2) + Math.Pow(edge2.Y, 2));
The longer of the edges, that with the greatest magnitude, is considered the "primary", or longer edge the rectangle:
PointF primaryEdge = edge1Magnitude > edge2Magnitude ? edge1 : edge2;
double primaryMagnitude = edge1Magnitude > edge2Magnitude ? edge1Magnitude : edge2Magnitude;
Finally, to find the angle between the primaryEdge, and a horizontal vector, reference. This is the acos, of the "Dot Product", of the two, or:
PointF reference = new PointF(1,0);
double refMagnitude = 1;
double thetaRads = Math.Acos(((primaryEdge.X * reference.X) + (primaryEdge.Y * reference.Y)) / (primaryMagnitude * refMagnitude));
double thetaDeg = thetaRads * 180 / Math.PI;
Now, thetaDeg is the angle between edge1 and the horizontal, in degrees.
I was trying to map the 360 video pixel coordinate to sphere surface coordinate but I couldn't get right result... It just mapped to the wrong position I already know the points of the XY data for 360 video pixels.
how map 2d grid points (x,y) onto sphere as 3d points (x,y,z)
I checked this link and I copied method from this but what I'm getting is not mapped to the desired position.
How can I get radius from the pixels?
I am not sure if I'm passing right radius for imageRadius but I thought it will be circumference/PI to get radius and the video ratio is 4096x2048. I also tried to pass the number 1 because UV is 0-1 but it was not right...
Is Method wrong?
Maybe the method is wrong. I passed random numbers into the imageRadius but couldn't get the right position... If I make X to negative number the seems like little bit closer to result....?
Current Result
https://youtu.be/t0I7Hlb-tbk
It mapped to up right position with the method that I found online...
Project File
https://drive.google.com/a/swordfish-sf.com/file/d/0B45RYzVs0t0_VVdaaHdmNHRWTk0/view?usp=sharing
If somebody can check the Unity project file that will be great...
Current Code
public class mapScript : MonoBehaviour {
public int input = 4098;
float imageRadius = 4098f / Mathf.PI; //2098? 3072? 4098?
float radius;
public GameObject testSphere;
void Start () {
radius = this.transform.localScale.x;
}
void Update () {
imageRadius = input / Mathf.PI;
int currentFrame = (int)this.GetComponent<VideoPlayer>().frame;
testSphere.transform.position = MercatorProjection(mapVals[currentFrame,0],mapVals[currentFrame,1]);
}
Vector3 MercatorProjection(float xVal, float yVal)
{
float lon = (xVal / imageRadius);
float lat = (2 * Mathf.Atan(Mathf.Exp(yVal / imageRadius)) - Mathf.PI / 2);
float calcX = radius * Mathf.Cos(lat) * Mathf.Cos(lon);
float calcY = radius * Mathf.Cos(lat) * Mathf.Sin(lon);
float calcZ = radius * Mathf.Sin(lat);
Vector3 result = new Vector3(calcX,calcY,calcZ);
Debug.Log(result);
return result;
}
float[,] mapVals = new float[,] {
{1969.21f, 928.625f},
{1969.6f, 928.533f},
{1968.92f, 928.825f},
{1968.68f, 929f},
{1968.47f, 929.067f},
{1968.41f, 929.025f},
{1968.48f, 928.992f},
....
};
}
Thank you.
As a side note, the radius is arbitrary. The pixel coordinates only map to the directional coordinates (polar [θ] and azimuthal [ϕ] angles).
We can do this by mapping each pixel to equal θ and ϕ intervals. The diagram below illustrates a low-resolution setup:
Let us adopt the convention that, for an image of with W, ϕ = 0 corresponds to:
Even W: half way between X = floor((W - 1) / 2) and X = ceil((W - 1) / 2)
Odd W: in the middle of the pixel column at X = floor((W - 1) / 2)
The pixel row at Y maps to the equilatitudinal line at θ = (Y + 0.5) / H * π.
To map all pixels in their entirety, let X start at -0.5 instead of 0, and end at W - 0.5; likewise for Y. Since integer coordinates map to the centers of the pixel regions shown above, this allows the whole area of any particular pixel to be addressed. You may need this later on if you plan on doing multi-sampling filtering for e.g. anti-aliasing.
Code:
Vector3 Mercator(float x, float y, int w, int h)
{
// outside of valid pixel region
if (x < -0.5f || x >= w - 0.5f || y < -0.5f || y >= h - 0.5f)
return new Vector3();
float theta = (y + 0.5f) / h * Math.PI;
float phi = ((x + 0.5f) / w - 0.5f) * 2.0 * Math.PI;
float c_t = Math.Cos(theta);
return new Vector3(c_t * Math.Cos(phi), c_t * Math.Sin(phi), Math.Sin(theta));
}
... and multiply the resulting direction vector by any "radius" you like, since it has (basically) nothing to do with the mapping anyway.
I have a position of a character as xyz coordinates x= 102, y= 0.75, z= -105.7 for example. And i have the rotation matrix for the character as
M11 = -0.14
M12 = 0
M13 = -0.99
M21 = 0
M22 = 1
M23 = 0
M31 = 0.99
M32 =0
M33 = 0.14
I don't have much understanding about graphics and how these data can correlate to the facing direction of the character. I want to find a vector such that i can use that vector to aim at a direction that the character is facing. How do i do that?
The direction your character is facing is the 3rd row of the rotation matrix. So that would be:
Vector3 facingDirection = new Vector3(0.99f, 0f, 0.14f);//(m31,m32,m33)
this vector appears to be normalized, but if it weren't, you would do:
Vector3 facingDirection = Vector3.Normalize(new Vector3(0.99f, 0f, 0.14f));
If the matrix is an XNA Matrix, then you would simply use the Matrix.Forward property of the Matrix structure and get the same result.
I am finally able to resolve it. Actually it's pretty simple vector mathematics. The rotation matrix was already giving me the direction vector as Steve suggests above, but I had to fire along that line to some particular point to make my animation working...So I actually needed a point along the line denoted by the direction vector. So, i just calculated a point some 1000 units away from the character's current position along the direction vector and fired at the line, it worked!
Vector3 facingDirection = new Vector3(RotMatrix[2, 0], RotMatrix[2, 1], RotMatrix[2, 2]); // direction vector
Vector3 currentPos = new Vector3(character.PosX, character.PosY, character.PosZ); // I also have position of the character
// Now calculate a point 10000 units away along the vector line
var px = currentPos.X + facingDirection.X * 10000;
var py = currentPos.Y + facingDirection.Y * 10000;
var pz = currentPos.Z + facingDirection.Z * 10000;
return new Vector3(px, py, pz);
I have 3 particles and one of them is the center particle. I want to rotate other two particle ( stored in particles list ) relative to the center particle with the formula q' = Θq + p where q' is the new position of the rotated particle, Θ is the orientation angle and p is the position of center particle. The initial position of other two particles is stored in initialParticlePosition list. THe problem is I think the angle I calculate is wrong because of the range. I thing I should take the range as [-pi, pi) or something like this. In some parts it calculates correct but sometimes it is wrong. Can someone help me with this code or give me another method of rotating.
{
angle = Math.Acos(Vector2.Dot(heading,new Vector2(0,-1) ));
for (int i = 0; i < 2; i++)
{
tempX = (double)initialParticlePositions[i].X * Math.Cos(angle) - (double)initialParticlePositions[i].Y * Math.Sin(angle) + centerParticle.position.x;
tempY = (double)initialParticlePositions[i].X * Math.Sin(angle) + (double)initialParticlePositions[i].Y * Math.Cos(angle) + centerParticle.position.y;
particles[i].position.x = tempX;
particles[i].position.y = tempY;
}
}
Some methods that might help (angles always in degrees, not rad):
public static double GetAngle(Vector v)
{
return Math.Atan2(v.X, -v.Y) * 180.0 / Math.PI;
}
public static Vector SetAngle(Vector v, double angle)
{
var angleInRads = angle * (Math.PI / 180.0);
var distance = v.Length;
v.X = (Math.Sin(angleInRads) * distance);
v.Y = -(Math.Cos(angleInRads) * distance);
return v;
}
static public Point RotatePointAroundCenter(Point point, Point center, double rotationChange)
{
Vector centerToPoint = point - center;
double angle = GetAngle(centerToPoint);
Vector centerToNewPoint = SetAngle(centerToPoint, angle + rotationChange);
return center + centerToNewPoint;
}
(You should start marking answers that help as answer, click the checkmark outline below the votes on the left, e.g. you could accept this answer)
Edit: Optimized the methods a bit.
The particle positions that are orbiting can be set with a single line of code each:
Assume p1, p2, & p3 are Vector2s and p2 & p3 are orbiting p1.
p2 = Vector2.Transform(p2 - p1, Matrix.CreateRotationZ(rotationChangeP2)) + p1;
p3 = Vector2.Transform(p3 - p1, Matrix.CreateRotationZ(rotationChangeP3)) + p1;
The Matrix.Create...() method will call the two trig functions for you.
edit. the Matrix & Vector2 structures & methods are XNA specific but included here because that's what the OP tagged his Q with.
angle = Math.Acos(Vector2.Dot(heading,new Vector2(0,-1)));
As you suspect, your combination of dot product and Acos will only give you angles in a 180
degree range.
Instead, use Atan2 on your unit vector to get a full range of angles from -pi to pi.
angle = (float)Math.Atan2((double)heading.Y, (double)heading.X);
You may need to negate the Y term if your Y axis is positive in the down direction.
I've been trying to do this for a while but haven't had much success. All I want to do is rotate the rectangle and then create a new rectangle which encompasses the rotated points.
Anyone have any ideas how it should be done properly?
The code I have doesn't work, but I'm not sure where it's going wrong exactly (the numbers make me think it actually works), for example if I have a rectangle with the following values:
{X:865 Y:76 Width:22 Height:164}
The result is:
{X:1863 Y:1740 Width:164 Height:22}
Where it is rotated -1.57094443
What I do is grab all four points of the original rectangle and rotate them with this function:
static public Vector2 RotateVectorAround(Vector2 anchor, Vector2 vector, float rotation)
{
Matrix mat = new Matrix();
mat.Translation = new Vector3(vector.X - anchor.X, vector.Y - anchor.Y, 0);
Matrix rot = new Matrix();
rot = Matrix.CreateRotationZ(rotation);
mat *= rot;
mat.Translation += new Vector3(anchor.X, anchor.Y, 0);
return new Vector2(mat.Translation.X, mat.Translation.Y);
}
Where 'anchor' is the pivot point (I'm not sure if this function is mathematically sound), then I determine the corners of the rotated rectangle with this:
Vector2 newTopLeft = new Vector2( Math.Min(Math.Min(topleft.X, bottomRight.X), Math.Min(bottomleft.X, topright.X)),
Math.Min(Math.Min(topleft.Y, bottomRight.Y), Math.Min(bottomleft.Y, topright.Y)));
Vector2 newBottomRight = new Vector2(
Math.Max(Math.Max(topleft.X, bottomRight.X), Math.Max(bottomleft.X, topright.X)),
Math.Max(Math.Max(topleft.Y, bottomRight.Y), Math.Max(bottomleft.Y, topright.Y) ));
You can multiply the points of the rectangle with a rotation matrix.
so given point P in a rotation will result in point R
where a is the rotation
a = degrees * (PI/180)
Rx = Px * cos(a) + Py * -sin(a)
Ry = Px * sin(a) + Py * cos(a)
to rotate about a point you can substract the pivot point before rotating it and add them after the rotation again (so the rotation is virtually around (0,0)
Px = Px - PivotX
Py = Py - PivotY
Rx = Px * cos(a) + Py * -sin(a)
Ry = Px * sin(a) + Py * cos(a)
Px = Rx + PivotX
Py = Ry + PivotY
I would not use the 3'th dimension here for a 2d rotation
in XNA that is something like (sorry no VStudio here):
point -= pivot
point = Vector2.Transform(point, Matrix.CreateRotationZ(angle));
point += pivot