温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Opencv如何提取连通区域轮廓

发布时间:2021-06-11 14:03:55 来源:亿速云 阅读:518 作者:小新 栏目:编程语言

小编给大家分享一下Opencv如何提取连通区域轮廓,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

在进行图像分割后,可能需要对感兴趣的目标区域进行提取,比较常用的方法是计算轮廓。

通过轮廓可以获得目标的一些信息:

(1)目标位置

(2)目标大小(即面积)

(3)目标形状(轮廓矩)

当然,轮廓不一定代表希望目标区域,阈值分割时可能造成一部分信息丢失,因此可以计算轮廓的质心坐标,再进行漫水填充。

程序中有寻找质心+填充,但效果不好,因此就不放填充后的图了。

Opencv如何提取连通区域轮廓

实验结果:

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdio.h>
 
using namespace cv;
using namespace std;
 
vector<vector<Point> > contours; //轮廓数组
vector<Point2d> centers; //轮廓质心坐标 
vector<vector<Point> >::iterator itr; //轮廓迭代器
vector<Point2d>::iterator itrc; //质心坐标迭代器
vector<vector<Point> > con; //当前轮廓
 
 
int main()
{
 double area;
 double minarea = 100;
 double maxarea = 0;
 Moments mom; // 轮廓矩
 Mat image,gray,edge,dst;
 namedWindow("origin");
 namedWindow("connected_region");
 
 image = imread("view.jpg");
 cvtColor(image, gray, COLOR_BGR2GRAY);
 blur(gray, edge, Size(3,3)); //模糊去噪
 threshold(edge,edge,200,255,THRESH_BINARY); //二值化处理
 
 /*寻找轮廓*/
 findContours( edge, contours,
 CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE );
 itr = contours.begin(); //使用迭代器去除噪声轮廓
 while(itr!=contours.end())
 {
 area = contourArea(*itr);
 if(area<minarea)
 {
 itr = contours.erase(itr); //itr一旦erase,需要重新赋值
 }
 else
 {
 itr++;
 }
 if (area>maxarea)
 {
 maxarea = area;
 }
 }
 dst = Mat::zeros(image.rows,image.cols,CV_8UC3);
 
 /*绘制连通区域轮廓,计算质心坐标*/
 Point2d center;
 itr = contours.begin();
 while(itr!=contours.end())
 {
 area = contourArea(*itr);
 con.push_back(*itr);
 if(area==maxarea)
 drawContours(dst,con,-1,Scalar(0,0,255),2); //最大面积红色绘制
 else
 drawContours(dst,con,-1,Scalar(255,0,0),2); //其它面积蓝色绘制
 con.pop_back();
 
 //计算质心
 mom = moments(*itr);
 center.x = (int)(mom.m10/mom.m00);
 center.y = (int)(mom.m01/mom.m00);
 centers.push_back(center);
 
 itr++;
 }
 imshow("origin",image);
 imshow("connected_region",dst);
 waitKey(0);
 
 /*漫水填充连通区域*/
 Point2d seed;
 int new_scalar = 0;
 int loDiff = 8, upDiff = 8;
 int connectivity = 4; 
 
 itrc = centers.begin();
 while(itrc!=centers.end())
 { 
 seed = *itrc;
 floodFill(image,seed,Scalar::all(new_scalar),NULL,
 Scalar::all(loDiff),Scalar::all(upDiff),connectivity);
 itrc++;
 }
 
 waitKey(0);
 return 0 ;
}

以上是“Opencv如何提取连通区域轮廓”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI