OpenCV使用连通组件检测并输出图像中的对象

一、代码

/**
 * 中值滤波:通常用于去除椒盐噪声,丢失细小细节(在这幅图中会把小沙子一样的小点点全部丢弃)
 */
void showSort(char *inputImagePath) {
    //原图
    Mat src = imread(inputImagePath);
    imshow("input", src);
    waitKey(0);
    //灰度图
    Mat gray;
    cvtColor(src, gray, COLOR_BGR2GRAY);
    //中值滤波去除椒盐噪声,此处卷积核用3、5都不是很理想,所以选择了7。有兴趣可以试试其他的。
    Mat mBlur;
    medianBlur(gray, mBlur, 7);
    imshow("mBlur", mBlur);
    waitKey(0);
    //对原始图像执行大模糊以得到光模式(和输入图像背景差不多的的背景图)
    Mat pattern;
    blur(mBlur, pattern, Size(mBlur.cols / 3, mBlur.rows / 3));
    imshow("pattern", pattern);
    waitKey(0);
    //减除输入图像背景:有两种算法:1.减法=光模式图像-原始矩阵图像。2.除法=255*(1-(原生图像/光模式))
    Mat removeLightPattern;
    removeLightPattern = pattern - mBlur;
    //输出背景减除后的图像
    imshow("removeLightPattern", removeLightPattern);
    waitKey(0);
//    //对图像进行二值化,二值分割
    Mat thresholdMat;
    threshold(removeLightPattern, thresholdMat, 30, 255, THRESH_BINARY);
    imshow("thresholdMat", thresholdMat);
    waitKey(0);
    //执行连通组件
    Mat labels;
    int nums_object = connectedComponents(thresholdMat, labels);
    if (nums_object < 2) {//如果小于2则意味着只检测到了背景图像
        cout << "No objects detected" << endl;
        return;
    } else {
        cout << "Number of objects detected :" << nums_object - 1 << endl;
    }
    Mat conn_output = Mat::zeros(thresholdMat.rows, thresholdMat.cols, CV_8UC3);
    for (int i = 0; i < nums_object; i++) {
        //循环得到图像中的单个组件
        Mat mask = labels == i;
        //循环显示图像中的一个个图片
        imshow("mask", mask);
        waitKey(0);
    }

}

二、效果图

原文地址:https://www.cnblogs.com/tony-yang-flutter/p/14845911.html