首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >OpenCV系列(14)|点集凸包

OpenCV系列(14)|点集凸包

作者头像
用户9831583
发布2022-06-16 16:18:16
发布2022-06-16 16:18:16
6220
举报
文章被收录于专栏:码出名企路码出名企路

效果:将所有点集的外围找出来做出一个封闭的图形

应用:最大包裹圈

函数:convexHull

代码语言:javascript
复制
void convexHull(InputArray points, OutputArray hull, bool clockwise=false, bool returnPoints=true);

第一个参数是要求凸包的点集,

第二个参数是输出的凸包点,

第三个参数是一个bool变量,表示求得的凸包是顺时针方向还是逆时针方向,true是顺时针方向。

注意:第二个参数可以为vector<int>,此时返回的是凸包点在原轮廓点集中的索引,也可以为vector<Point>,此时存放的是凸包点的位置。

代码:

代码语言:javascript
复制
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;

static void help()
{
    cout << "\nThis sample program demonstrates the use of the convexHull() function\n"
         << "Call:\n"
         << "./convexhull\n" << endl;
}

int main( int argc, char** argv )
{
    CommandLineParser parser(argc, argv, "{help h||}");
    if (parser.has("help"))
    {
        help();
        return 0;
    }
    Mat img(500, 500, CV_8UC3);
    RNG& rng = theRNG();

    for(;;)
    {
        int i, count = (unsigned)rng%100 + 1;

        vector<Point> points;
        //随机在1-100个点,这些点位于图像中心3/4处
        for( i = 0; i < count; i++ )
        {
            Point pt;
            pt.x = rng.uniform(img.cols/4, img.cols*3/4);
            pt.y = rng.uniform(img.rows/4, img.rows*3/4);

            points.push_back(pt);
        }

        vector<int> hull;
        convexHull(Mat(points), hull, true);//点集组成的凸包围圈
        //随机点画出来
        img = Scalar::all(0);
        for( i = 0; i < count; i++ )
            circle(img, points[i], 3, Scalar(0, 0, 255), FILLED, LINE_AA);

        int hullcount = (int)hull.size();
        Point pt0 = points[hull[hullcount-1]];
        //随机点的凸包围圈画出来
        for( i = 0; i < hullcount; i++ )
        {
            Point pt = points[hull[i]];
            line(img, pt0, pt, Scalar(0, 255, 0), 1,LINE_AA);
            pt0 = pt;
        }

        imshow("hull", img);

        char key = (char)waitKey();
        if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
            break;
    }

    return 0;
}

效果:


本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-10-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 码出名企路 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档