Opencv 曲線擬合圓
阿新 • • 發佈:2019-02-07
void circleLeastFit(const std::vector<cv::Point2f> points, cv::Point2f ¢er, double &radius)
{
radius = 0.0f;
double sum_x = 0.0f, sum_y = 0.0f;
double sum_x2 = 0.0f, sum_y2 = 0.0f;
double sum_x3 = 0.0f, sum_y3 = 0.0f;
double sum_xy = 0.0f, sum_x1y2 = 0.0f, sum_x2y1 = 0.0f;
int N = points.size();
for (int i = 0; i < N; i++)
{
double x = points[i].x;
double y = points[i].y;
double x2 = x * x;
double y2 = y * y;
sum_x += x;
sum_y += y;
sum_x2 += x2;
sum_y2 += y2;
sum_x3 += x2 * x;
sum_y3 += y2 * y;
sum_xy += x * y;
sum_x1y2 += x * y2;
sum_x2y1 += x2 * y;
}
double C, D, E, G, H;
double a, b, c;
C = N * sum_x2 - sum_x * sum_x;
D = N * sum_xy - sum_x * sum_y;
E = N * sum_x3 + N * sum_x1y2 - (sum_x2 + sum_y2) * sum_x;
G = N * sum_y2 - sum_y * sum_y;
H = N * sum_x2y1 + N * sum_y3 - (sum_x2 + sum_y2) * sum_y;
a = (H * D - E * G) / (C * G - D * D);
b = (H * C - E * D) / (D * D - G * C);
c = -(a * sum_x + b * sum_y + sum_x2 + sum_y2) / N;
center.x = a / (-2 );
center.y = b / (-2);
radius = sqrt(a * a + b * b - 4 * c) / 2;
}
新增一個Python版本,輸入的是點的list 輸出是圓心xy座標和半徑rad
def circleLeastFit( points):
N =len(points)
sum_x = 0
sum_y = 0
sum_x2 = 0
sum_y2 = 0
sum_x3 = 0
sum_y3 = 0
sum_xy = 0
sum_x1y2 = 0
sum_x2y1 = 0
for i in range(N) :
# print(points[i][0])
x = float(points[i][0][0])
y = float(points[i][0][1])
x2 = x * x
y2 = y * y
sum_x += x
sum_y += y
sum_x2 += x2
sum_y2 += y2
sum_x3 += x2 * x
sum_y3 += y2 * y
sum_xy += x * y
sum_x1y2 += x * y2
sum_x2y1 += x2 * y
C = N * sum_x2 - sum_x * sum_x
D = N * sum_xy - sum_x * sum_y
E = N * sum_x3 + N * sum_x1y2 - (sum_x2 + sum_y2) * sum_x
G = N * sum_y2 - sum_y * sum_y
H = N * sum_x2y1 + N * sum_y3 - (sum_x2 + sum_y2) * sum_y
a = (H * D - E * G) / (C * G - D * D+1e-100)
b = (H * C - E * D) / (D * D - G * C+1e-100)
c = -(a * sum_x + b * sum_y + sum_x2 + sum_y2) / N
centerx = a / (-2)
centery = b / (-2)
rad = math.sqrt(a * a + b * b - 4 * c) / 2
return centerx,centery,rad