zoukankan      html  css  js  c++  java
  • 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);
        }
    
    }

    二、效果图

  • 相关阅读:
    团队项目:二次开发1.0
    文法分析2
    文法分析1
    词法分析实验总结
    0916 编程实验一 词法分析程序
    0909初学编译原理
    复利计算
    0302思考并回答一些问题
    1231 实验四 递归下降语法分析程序设计
    1118实验三有限自动机构造与识别
  • 原文地址:https://www.cnblogs.com/tony-yang-flutter/p/14845911.html
Copyright © 2011-2022 走看看