如何计算多边形主延伸方向与X轴的夹角?排查计算异常
多边形主延伸方向与X轴夹角计算问题
已知任意简单凸/凹多边形的顶点坐标与质心,需计算其主延伸方向与参考系X轴的夹角。示例里蓝色线是多边形主延伸方向,黄色圆代表质心,红色圆是多边形中点。
我尝试通过计算协方差矩阵最大特征值对应的特征向量来求解,多数测试场景下结果有效,但某一多边形的计算结果约为80°,和预期的0°不符,不确定是数学逻辑出错还是C#代码实现有问题,相关代码如下:
// Returns the angle between the x-axis and the line along which the figure extends mainly. public double GetOrientation() { Point centroid = this.GetCentroid(); // Centroid of the polygon. int vertexesNumber = this.GetVertexesNumber(); // Number of vertexes of the polygon. double covXX = 0.0; // Variance of x, indicates how much x varies from the mean. double covYY = 0.0; // Variance of y, indicates how much y varies from the mean. double covXY = 0.0; // Covariance between x and y, indicates how much x and y vary together. // Calculates the covariance matrix, indicates how the vertexes are distributed with respect to the centroid. foreach (Point vertex in vertexes) // For each vertex of the polygon. { double x = vertex.X - centroid.X; // Calculates the difference of the vertex at x from the centroid at x. double y = vertex.Y - centroid.Y; // Calculates the difference of the vertex at y from the centroid at y. covXX += x * x; // Adds the square of the deviation from x to the centroid. covYY += y * y; // Adds the square of the deviation from y to the centroid. covXY += x * y; // Adds the product of deviations from x and y. } covXX /= vertexesNumber; // Calculates the mean of the variance along x. covYY /= vertexesNumber; // Calculates the mean of the variance along y. covXY /= vertexesNumber; // Calculates the mean of the covariance between x and y. double tr = covXX + covYY; // Calculates the trace of the matrix. double det = covXX * covYY - covXY * covXY; // Calculates the determinant of the matrix. double lambda = (tr + Math.Sqrt(tr * tr - 4 * det)) / 2; // Calculates the greatest eigenvalue of the matrix. double a1 = covXY; // Calculates the component along the x-axis of the eigenvector associated with the greatest eigenvalue. double a2 = lambda - covXX; // Calculates the component along the y-axis of the eigenvector associated with the greatest eigenvalue. double angle = Math.Atan2(a2, a1); // Calculates the angle between the x-axis and the line along which the polygon extends mainly, defined by the vector a1, a2. angle *= 180.0 / Math.PI; // Converts the angle from radians to degrees. return angle; }
内容的提问来源于stack exchange,提问作者user28277546
相关产品推荐
相关产品推荐

