OpenCV—椭圆拟合fitEllipse

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/i_chaoren/article/details/78358991

本文的主要参考为官方文档OpenCV249-fitEllipse博客-opencv中的椭圆拟合

以及《Learning OpenCV 3》page424-425

OpenCV中提供的椭圆拟合API如下:

RotatedRect fitEllipse(InputArray points)
输入:二维点集,要求拟合的点至少为6个点。存储在std::vector<> or Mat

处理:该函数使用的是最小二乘的方法进行拟合的。参考论文:《Direct least square fitting of ellipses》

输出:RotatedRect 类型的矩形,是拟合出椭圆的最小外接矩形。


绘制椭圆用到的API如下,官方文档OpenCV249-ellipse

void ellipse(Mat& img, Point center, Size axes, double angle, double startAngle, double endAngle, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
void ellipse(Mat& img, const RotatedRect& box, const Scalar& color, int thickness=1, int lineType=8)
对应的参数可参见下图:


示例代码如下:

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;

int main( )
{
	const char* filename = "rect-45度.bmp";
	Mat src_image = imread(filename, 0);
	if( src_image.empty() )
	{
		cout << "Couldn't open image!" << filename;
		return 0;
	}

	imshow("原图", src_image);
	
	//轮廓
	vector<vector<Point>> contours;

	//使用canny检测出边缘
	Mat edge_image;
	Canny(src_image,edge_image,30,70);
	imshow("canny边缘",edge_image);

	//边缘追踪,没有存储边缘的组织结构
	findContours(edge_image, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
	Mat cimage = Mat::zeros(edge_image.size(), CV_8UC3);

	for(size_t i = 0; i < contours.size(); i++)
	{
		//拟合的点至少为6
		size_t count = contours[i].size();
		if( count < 6 )
			continue;

		//椭圆拟合
		RotatedRect box = fitEllipse(contours[i]);

		//如果长宽比大于30,则排除,不做拟合
		if( MAX(box.size.width, box.size.height) > MIN(box.size.width, box.size.height)*30 )
			continue;

		//画出追踪出的轮廓
		drawContours(cimage, contours, (int)i, Scalar::all(255), 1, 8);
		
		//画出拟合的椭圆
		ellipse(cimage, box, Scalar(0,0,255), 1, CV_AA);
	}
	imshow("拟合结果", cimage);

	waitKey();
	return 0;
}


展开阅读全文

没有更多推荐了,返回首页