0

I have referenced following link to develop following csharp code to detect angle of Image. https://stackoverflow.com/a/34285205/7805023

 Image<Gray, byte> imgout = imgInput.Convert<Gray, byte>().Not().ThresholdBinary(new 
 Gray(50), new Gray(255));
 VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
 Mat hier = new Mat();

CvInvoke.FindContours(imgout, contours, hier, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
     for (int i = 0; i <= 1; i++)
     {
        Rectangle rect = CvInvoke.BoundingRectangle(contours[i]);
        RotatedRect box = CvInvoke.MinAreaRect(contours[i]);
        PointF[] Vertices = box.GetVertices();
        PointF point = box.Center;
        PointF edge1 = new PointF(Vertices[1].X - Vertices[0].X, 
        Vertices[1].Y - Vertices[0].Y);
        PointF edge2 = new PointF(Vertices[2].X - Vertices[1].X,Vertices[2].Y - Vertices[1].Y);                     
        double edge1Magnitude = Math.Sqrt(Math.Pow(edge1.X, 2) + Math.Pow(edge1.Y, 2));
        double edge2Magnitude = Math.Sqrt(Math.Pow(edge2.X, 2) + Math.Pow(edge2.Y, 2));
        PointF primaryEdge = edge1Magnitude > edge2Magnitude ? edge1 : edge2;
        PointF reference = new PointF(Vertices[1].X, Vertices[0].Y);
        double thetaRads = Math.Acos((primaryEdge.X * reference.X) + (primaryEdge.Y * reference.Y))/(edge1Magnitude* edge2Magnitude);
        double thetaDeg = thetaRads * 180 / Math.PI;
    }

I am getting NaN as output for angle. Please go through the code let me know what wrong I have done?

I have used emgucv for image processing.

Any help will be highly appreciated.

manthan
  • 102
  • 1
  • 15

1 Answers1

1

NaN, Not a Number, is returned by Math.Acos() when the provided value is not between -1 and 1.

Your calculation of thetaRads is wrong, you need to calculate the Acos of the vectors' dot product divided by the product of the vectors' magnitudes, as per:

enter image description here

double thetaRads = Math.Acos(((primaryEdge.X * reference.X) + (primaryEdge.Y * reference.Y)) / (primaryMagnitude * refMagnitude));
George Kerwood
  • 1,248
  • 8
  • 19