OpenCV凸包

一、概述

  案例:输入一张图片将其凸包绘制出来

  概念:最大外接多边形

convexHull(
InputArray points,// 输入候选点,来自findContours
OutputArray hull,// 凸包
bool clockwise,// default true, 顺时针方向
bool returnPoints)// true 表示返回点个数,如果第二个参数是            vector<Point>则自动忽略
)
ps:凸包检测是基于轮廓发现候选点的

  实现步骤:

  1.加载图像,并将图像转为灰度图

  2.执行边缘检测

  3.发现轮廓

  4.在轮廓中检测凸包

  5.绘制凸包和轮廓

  6.显示凸包和轮廓

  

二、代码示例

 Mat src = imread(filePath);
    if(src.empty()){
        return;
    }
    imshow("src",src);
    Mat gray;
    cvtColor(src,gray,COLOR_BGR2GRAY);
    imshow("gray",gray);
    //执行边缘 检测
    Canny(gray,gray,50,100,3,false);
    imshow("canny",gray);
    //发现轮廓
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    findContours(gray,contours,hierarchy,RETR_TREE,CHAIN_APPROX_SIMPLE,Point(0,0));
    //绘制轮廓
    RNG rng;
    Mat drawImg=Mat::zeros(gray.size(),CV_8UC3);
    //从轮廓数据中检测凸包
    vector<vector<Point>> hull(contours);
    for(int i=0;i<contours.size();i++){
        convexHull(Mat(contours[i]),hull[i],false);
    }
    for(int i=0;i<contours.size();i++){
        double area = contourArea(contours[i],false);
        if(area>100){
            Scalar color = Scalar(rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255));
            //绘制凸包
            drawContours(drawImg,hull,i,color,1,LINE_8,hierarchy,0,Point(0,0));
            //绘制轮廓
            drawContours(drawImg,contours,i,color,2,LINE_8,hierarchy,0,Point(0,0));
        }

    }
    imshow("drawImg",drawImg);

 

三、是图片

 

posted on 2022-03-03 09:47  飘杨......  阅读(165)  评论(0编辑  收藏  举报