C#最小二乘法拟合圆获取圆心坐标、圆半径

  1. NuGet->安装MathNet.Numerics ;
  2. 引用“System.Drawing”;
  3. Using指令:
using System.Drawing;
using MathNet.Numerics.LinearAlgebra;
  1. 代码块(转):
/// 
/// 最小二乘法拟合圆获取圆心坐标、圆半径
/// 
/// 输入的List类型的变量
/// 圆心x坐标
/// 圆心y坐标
/// 圆半径
/// 
public static int FitCircle(List<PointF> pointFs, out float CenterX, out float CenterY, out float CenterR)
{
    Matrix<float> YMat;
    Matrix<float> RMat;
    Matrix<float> AMat;
    List<float> YLit = new List<float>();
    List<float[]> RLit = new List<float[]>();

    foreach (var pointF in pointFs)
        YLit.Add(pointF.X * pointF.X + pointF.Y * pointF.Y);

    float[,] Yarray = new float[YLit.Count, 1];
    for (int i = 0; i < YLit.Count; i++)
        Yarray[i, 0] = YLit[i];

    YMat = CreateMatrix.DenseOfArray<float>(Yarray);

    foreach (var pointF in pointFs)
        RLit.Add(new float[] { -pointF.X, -pointF.Y, -1 });

    float[,] Rarray = new float[RLit.Count, 3];
    for (int i = 0; i < RLit.Count; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            Rarray[i, j] = RLit[i][j];
        }
    }

    RMat = CreateMatrix.DenseOfArray<float>(Rarray);
    Matrix<float> RTMat = RMat.Transpose();
    Matrix<float> RRTInvMat = (RTMat.Multiply(RMat)).Inverse();
    AMat = RRTInvMat.Multiply(RTMat.Multiply(YMat));

    float[,] Array = AMat.ToArray();
    float A = Array[0, 0];
    float B = Array[1, 0];
    float C = Array[2, 0];
    CenterX = A / -2.0f;
    CenterY = B / -2.0f;
    CenterR = (float)(Math.Sqrt(A * A + B * B - 4 * C) / 2.0f);
    return 0x0000;
}

你可能感兴趣的:(代码块,c#,.net)