OpenCV结构分析与形状描述符(11)椭圆拟合函数fitEllipse()的使用

发布于:2024-09-18 ⋅ 阅读:(115) ⋅ 点赞:(0)
  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

围绕一组2D点拟合一个椭圆。

该函数计算出一个椭圆,该椭圆在最小二乘意义上最好地拟合一组2D点。它返回一个内切椭圆的旋转矩形。使用了由[90]描述的第一个算法。开发者应该注意,由于数据点靠近包含的 Mat 元素的边界,返回的椭圆/旋转矩形数据可能包含负索引。”

fitEllipse 函数是 OpenCV 库中的一个常用函数,用于拟合一个椭圆来描述一组点。这个函数通常用于图像处理和计算机视觉任务中,例如物体检测、形状分析等。

函数原型


RotatedRect cv::fitEllipse
(	
	InputArray 	points
)	

参数

  • 参数points 输入的2D点集。这些点可以存储在 std::vector 或 Mat 中。

代码示例


#include <opencv2/opencv.hpp>
#include <vector>

using namespace cv;

int main()
{
    // 创建一个空白图像
    Mat img( 400, 400, CV_8UC3, Scalar( 255, 255, 255 ) );

    // 创建一组2D点
    std::vector< Point2f > points;
    points.push_back( Point2f( 150, 100 ) );
    points.push_back( Point2f( 100, 150 ) );
    points.push_back( Point2f( 200, 150 ) );
    points.push_back( Point2f( 200, 250 ) );
    points.push_back( Point2f( 100, 250 ) );
    points.push_back( Point2f( 150, 300 ) );


    // 拟合椭圆
    RotatedRect ellipse2 = fitEllipse( points );

    // 绘制拟合的椭圆
    Point2f center = ellipse2.center;  // 椭圆中心
    Size2f axes    = ellipse2.size;    // 轴长
    float angle    = ellipse2.angle;   // 旋转角度
    ellipse( img, center, axes, angle, 0, 360, Scalar( 0, 0, 255 ), 2 );
    

    // 绘制原始点
    for ( const auto& pt : points )
    {
        circle( img, pt, 5, Scalar( 0, 255, 0 ), -1 );
    }

    // 显示结果
    namedWindow( "Ellipse Fitting", WINDOW_AUTOSIZE );
    imshow( "Ellipse Fitting", img );
    waitKey( 0 );

    return 0;
}

运行结果

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到