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); } }
二、效果图
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库