如何寻找第二大轮廓

在有背景的图像处理中,往往你关注的区域并不是最大的轮廓(那是背景),而是第二大轮廓

之前我们有这样的函数:
//寻找最大的轮廓
    VP FindBigestContour(Mat src){    
         int imax  =  0//代表最大轮廓的序号
         int imaxcontour  =  - 1//代表最大轮廓的大小
        std : :vector <std : :vector <Point >>contours;    
        findContours(src,contours,CV_RETR_LIST,CV_CHAIN_APPROX_SIMPLE);
         for ( int i = 0;i <contours.size();i + +){
             int itmp  =  contourArea(contours[i]); //这里采用的是轮廓大小
             if (imaxcontour  < itmp ){
                imax  = i;
                imaxcontour  = itmp;
            }
        }
         return contours[imax];
    }
使用的是冒泡方法。实际上vector肯定是可以有排序算法的,能否将其融入进去?
肯定是可以的,我采用了这样的方法,效果很好。
//寻找第nth的轮廓
     //ith  =  0代表最大,ith = 1 代表第 2个,以此类推
    bool sortfunction (std : :vector <Point > c1,std : :vector <Point > c2) {  return (contourArea(c1) >contourArea(c2)); }  
    VP FindnthContour(Mat src, int ith ){    
        std : :vector <std : :vector <Point >>contours;    
        findContours(src,contours,CV_RETR_LIST,CV_CHAIN_APPROX_SIMPLE);
        std : :sort(contours.begin(),contours.end(),sortfunction);
         return contours[ith];
    }




猜你喜欢

转载自www.cnblogs.com/jsxyhelu/p/9004507.html