随笔 - 632  文章 - 17  评论 - 54  阅读 - 93万

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);
    }

}
复制代码

 

二、效果图

 

posted on   飘杨......  阅读(149)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
< 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

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