1. 最小二乘法

推导过程可参考 Kåsa Fit 算法:

 1// fitCenterByLeastSquare 最小二乘法拟合圆
 2func fitCenterByLeastSquare(points []gocv.Point2f) (gocv.Point2f, float32) {
 3	var sumX, sumY, sumX2, sumY2, sumXY, sumX3, sumY3, sumX2Y, sumY2X float32
 4	for _, p := range points {
 5		sumX += p.X
 6		sumY += p.Y
 7		sumX2 += p.X * p.X
 8		sumY2 += p.Y * p.Y
 9		sumXY += p.X * p.Y
10		sumX3 += p.X * p.X * p.X
11		sumY3 += p.Y * p.Y * p.Y
12		sumX2Y += p.X * p.X * p.Y
13		sumY2X += p.Y * p.Y * p.X
14	}
15	N := float32(len(points))
16	C := N*sumX2 - sumX*sumX
17	D := N*sumXY - sumX*sumY
18	E := N*(sumX3+sumY2X) - sumX*(sumX2+sumY2)
19	G := N*sumY2 - sumY*sumY
20	H := N*(sumX2Y+sumY3) - sumY*(sumX2+sumY2)
21	a := (H*D - E*G) / (C*G - D*D)
22	b := (H*C - E*D) / (D*D - G*C)
23	c := -(a*sumX + b*sumY + sumX2 + sumY2) / N
24
25	centerX := -a / 2
26	centerY := -b / 2
27	radius := math.Sqrt(float64(a*a+b*b-4*c)) / 2
28
29	return gocv.Point2f{X: centerX, Y: centerY}, float32(radius)
30}