如何寻找第二大轮廓

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

 

 


之前我们有这样的函数:
复制代码
//寻找最大的轮廓
    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];
    }
复制代码

 

posted on   jsxyhelu  阅读(58)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示