筛选最大连通域

本文介绍了一种使用OpenCV进行图像处理的方法,通过cv::connectedComponents找到图像中的最大连通域。首先读取图像并进行边缘检测,然后通过连接组件找出轮廓,过滤掉面积过小或宽高比不满足条件的轮廓。最后,提取并显示最大连通域,并将其保存到文件。

#include <opencv2/opencv.hpp>  

#include <opencv2/highgui/highgui.hpp>  

#include <opencv2/ml/ml.hpp>  
#include <io.h>
#include <direct.h>
#include<Windows.h>
using namespace std;
using namespace cv;
/*采用cvFindContours提取轮廓,并过滤掉小面积轮廓,最后将轮廓保存*/
RNG rng;
static int getContoursByCplus(string Imgname, double minarea, double whRatio)

{

    cv::Mat src, dst, canny_output;

    /// Load source image and convert it to gray

    src = imread(Imgname, 0);
    if (!src.data)

    {
        std::cout << "read data error!" << std::endl;

        return -1;
    }

    blur(src, src, Size(3, 3));
    //the pram. for findContours,

    vector<vector<Point> > contours;

    vector<Vec4i> hierarchy;

    /// Detect edges using canny

    Canny(src, canny_output, 80, 255, 3);

    /// Find contours

    findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

    //CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE
    double maxarea = 0;

    int maxAreaIdx = 0;

    for (int i = 0; i < contours.size(); i++)

    {
        double tmparea = fabs(contourArea(contours[i]));

        if (tmparea > maxarea)

        {
            maxarea = tmparea;

            maxAreaIdx = i;

            continue;

        }

        if (tmparea < minarea&&tmparea>20000)
        {

            //删除面积小于设定值的轮廓

            contours.erase(contours.begin() + i);

            std::wcout << "delete a small area" << std::endl;

            continue;
        }

        //计算轮廓的直径宽高

        Rect aRect = boundingRect(contours[i]);
        

        if ((aRect.width / aRect.height) < whRatio)

        {
            //删除宽高比例小于设定值的轮廓

            contours.erase(contours.begin() + i);

            std::wcout << "delete a unnomalRatio area" << std::endl;

            continue;

        }
        Mat hsv, mask;
        Mat roi = src(aRect);
        Mat person=roi.clone();
        imshow("hsv", roi);
        drawContours(person,contours[i],i,Scalar(255),0);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值