# opencv中的椭圆拟合

//创建一个用于绘制图像的空白图
cv::Mat image = cv::Mat::ones(480, 640, CV_8UC3);
//设置蓝色背景
image.setTo(cv::Scalar(100, 0, 0));

//输入拟合点
std::vector<cv::Point> points;

points.push_back(cv::Point(200, 240));
points.push_back(cv::Point(300, 400));
points.push_back(cv::Point(400, 360));
points.push_back(cv::Point(500, 300));
points.push_back(cv::Point(500, 200));
points.push_back(cv::Point(300, 150));

//将拟合点绘制到空白图上
for (int i = 0; i < points.size(); i++)
{
cv::circle(image, points[i], 5, cv::Scalar(0, 0, 255), 2, 8, 0);
}

//获取拟合椭圆的外包围矩形
cv::RotatedRect rotate_rect = cv::fitEllipse(points);
//绘制拟合椭圆
cv::ellipse(image, rotate_rect, cv::Scalar(0, 255, 255), 2, 8);

cv::imshow("image", image);
cv::waitKey(0);  

opencv中的椭圆通过RotatedRect来定义，其center(块中心(x,y)), size(宽和高,宽小于高), angle（旋转角）分别对应椭圆的中心，短轴长轴，旋转角度。

         RotatedRect box = fitEllipse(pointsf);

//把那些长轴与短轴之比很多的那些椭圆剔除。
if( MAX(box.size.width, box.size.height) > MIN(box.size.width, box.size.height)*8 )
continue;
//绘制轮廓
drawContours(cimage, contours, (int)i, Scalar::all(255), 1, 8);

//绘制椭圆
ellipse(cimage, box, Scalar(0,0,255), 1, CV_AA);
//绘制椭圆
// ellipse(cimage, box.center, box.size*0.5f, box.angle, 0, 360, Scalar(0,255,255), 1, CV_AA);  //注意这里需要乘以0.5

xiamentingtao

• 擅长领域：
• cv
• math
• 考博
• 算法
• AI