# 关于#c++#和#opencv#拟合圆的问题，如何解决？

###### 用代码块功能插
``````
```c++

//最小二乘法你和圆
static bool CircleInfo2(std::vector<cv::Point2f>& pts, cv::Point2f& center, float& radius) {
center = cv::Point2d(0, 0);
if (pts.size() < 3) return false;;

double sumX = 0.0;
double sumY = 0.0;
double sumX2 = 0.0;
double sumY2 = 0.0;
double sumX3 = 0.0;
double sumY3 = 0.0;
double sumXY = 0.0;
double sumX1Y2 = 0.0;
double sumX2Y1 = 0.0;
const double N = (double)pts.size();
for (int i = 0; i < pts.size(); ++i) {
double x = pts.at(i).x;
double y = pts.at(i).y;
double x2 = x * x;
double y2 = y * y;
double x3 = x2 * x;
double y3 = y2 * y;
double xy = x * y;
double x1y2 = x * y2;
double x2y1 = x2 * y;

sumX += x;
sumY += y;
sumX2 += x2;
sumY2 += y2;
sumX3 += x3;
sumY3 += y3;
sumXY += xy;
sumX1Y2 += x1y2;
sumX2Y1 += x2y1;

}
double C = N * sumX2 - sumX * sumX;
double D = N * sumXY - sumX * sumY;
double E = N * sumX3 + N * sumX1Y2 - (sumX2 + sumY2) * sumX;
double G = N * sumY2 - sumY * sumY;
double H = N * sumX2Y1 + N * sumY3 - (sumX2 + sumY2) * sumY;

double denominator = C * G - D * D;
if (std::abs(denominator) < DBL_EPSILON) return false;
double a = (H * D - E * G) / (denominator);
denominator = D * D - G * C;
if (std::abs(denominator) < DBL_EPSILON) return false;
double b = (H * C - E * D) / (denominator);
double c = -(a * sumX + b * sumY + sumX2 + sumY2) / N;

center.x = a / (-2);
center.y = b / (-2);
radius = std::sqrt(a * a + b * b - 4 * c) / 2;
return true;
}
//下面是应用

//画拟合圆
Mat drawcircle = Mat(img.rows, img.cols, CV_8UC3, Scalar(0, 0, 0));
circle(drawcircle, centerP, 1, Scalar(0, 0, 255), 1);//centerP为得到的识别目标的中心

//拟合圆，三十个点拟合
if (cirV.size() < 30) {
cirV.push_back( centerP );
}
else {
float R;
//得到拟合的圆心
CircleInfo2(cirV, cc, R);
circle(drawcircle, cc, 1, Scalar(255, 0, 0),2);

cout << endl << "center" << cc.x << "," << cc.y << endl;
cirV.erase(cirV.begin());
}
if (cc.x!=0&&cc.y!=0) {
Mat rot_mat = getRotationMatrix2D(cc, 30, 1);
cout << endl << "center1" << cc.x << "," << cc.y << endl;

float sinA = rot_mat.at<double>(0,1);//sin(60)
float cosA = rot_mat.at<double>(0,0);//cso(60)
float xx = -(cc.x - centerP.x);
float yy = -(cc.y - centerP.y);
Point2f resPoint = Point2f(cc.x + cosA * xx - sinA * yy, cc.y + sinA * xx + cosA * yy);
circle(img, resPoint, 1, Scalar(0, 255, 0), 10);

}

}

}

}
namedWindow("circle", WINDOW_FREERATIO);
imshow("circle", drawcircle);

``````

• 写回答

#### 1条回答默认 最新

• CSDN-Ada助手 CSDN-AI 官方账号 2022-09-23 20:08
关注
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

• 系统已结题 2月24日
• 已采纳回答 2月16日
• 创建了问题 9月23日

#### 悬赏问题

• ¥35 引用csv数据文件（4列1800行），通过高斯-赛德尔法拟合曲线，在选取（每五十点取1点）数据，求该数据点的曲率中心。
• ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no，如何解决？
• ¥15 Google speech command 数据集获取
• ¥15 vue3+element-plus页面崩溃
• ¥15 像这种代码要怎么跑起来？
• ¥15 安卓C读取/dev/fastpipe屏幕像素数据
• ¥15 pyqt5tools安装失败
• ¥15 mmdetection
• ¥15 nginx代理报502的错误
• ¥100 当AWR1843发送完设置的固定帧后，如何使其再发送第一次的帧