opencv删除小轮廓---mat版本

利用vector迭代器(iterator)遍历内容,利用erase()函数删除轮廓,实验设计为小于20的轮廓被删除,为了效果更明显,在阈值分割前不做平滑和滤波的处理,代码如下:

#include<iostream>  
#include <cv.h>  
#include <highgui.h>  
#include <cvaux.h>  
#include <tchar.h> 

using namespace std;  
using namespace cv;  
int main()
{
    Mat srcImage;
    Mat thresholdImage;  
    Mat grayImage;
    srcImage = imread("1.png");
     cvtColor(srcImage,grayImage,CV_BGR2GRAY);
    threshold(grayImage, thresholdImage, 0, 255, CV_THRESH_OTSU+CV_THRESH_BINARY);  
    Mat resultImage;
    thresholdImage.copyTo(resultImage);
    vector< vector< Point> > contours;  
    findContours(resultImage,contours,CV_RETR_EXTERNAL,  CV_CHAIN_APPROX_NONE); 
    vector<vector<Point> >::iterator itc= contours.begin();  
    while (itc!=contours.end()) 
    {  
        if( itc->size()<20)
        {  
            itc= contours.erase(itc);  
        }
        else
        {  
            ++itc;  
        }  
    }  
    drawContours(resultImage, contours, -1, Scalar(255), CV_FILLED);
    imshow("原图",srcImage);
    imshow("灰度",grayImage);
    imshow("二值图",thresholdImage);
    imshow("结果图",resultImage);
    waitKey(0);
    return 0;
}
  • 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
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

实验结果:

这里写图片描述

这里写图片描述

这里写图片描述

可以看到,轮廓面积小于20个像素的被删除了。

补充一下drawContours()函数:主要用于画出图像的轮廓

CV_EXPORTS_W void drawContours( InputOutputArray image,
                             InputArrayOfArrays contours,                               
                             int contourIdx, 
                             const Scalar& color,
                             int lineType=8,
                             InputArray hierarchy=noArray(),
                             int maxLevel=INT_MAX, 
                             Point offset=Point() );
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

其中第一个参数image表示目标图像, 
第二个参数contours表示输入的轮廓组,每一组轮廓由点vector构成, 
第三个参数contourIdx指明画第几个轮廓,如果该参数为负值,则画全部轮廓, 
第四个参数color为轮廓的颜色, 
第五个参数thickness为轮廓的线宽,如果为负值或CV_FILLED表示填充轮廓内部, 
第六个参数lineType为线型, 
第七个参数为轮廓结构信息, 

第八个参数为maxLevel

微信扫码关注我们:跟着数理化走天下


获得更多的信息哦,一起交流,一起成长哦:微信号:跟着数理化走天下,纯属个人的交流,无盈利目的


  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值