opencv之寻找轮廓findContours

opencv之寻找轮廓findContours,第1张

opencv之寻找轮廓findContours

findContours函数用于在二值图中寻找轮廓。

void cv::findContours(InputArrayimage,OutputArrayOfArrayscontours, //检测到的轮廓,运算结果存储在这,每一个轮廓存储为一个点向量,即point类型中的vector表示OutputArrayhierarchy,//可选的输出向量,包含图像的拓扑信息,每个轮廓contours[i]对应4个hierarchy元素hierarchy[i][0]--[i][3]分别表示后一个轮廓,前一个轮廓,父轮廓,内嵌轮廓的索引编号。int mode,  //轮廓检索模式int method,  // 轮廓近似方法Pointoffset = Point()  // 每个轮廓点的可选偏移量)

findContours常与drawContours()函数配合使用

例如:

        vector>contours;

        findContours(img,contours,RETR_EXTERNAL,CHAIN_APPROX_NONE);

drawContour:

void cv::drawContours(InputOutputArrayimage,InputArrayOfArrayscontours,//所有输入的轮廓,每个轮廓存储为一个点向量int contourIdx, // 轮廓绘制的指示变量,若为负则绘制所有轮廓const Scalar & color,int thickness = 1,  //线条粗细int lineType = LINE_8, //线条类型InputArrayhierarchy = noArray(), //可选层次结构信息int maxLevel = INT_MAX,//用于绘制轮廓的最大等级Pointoffset = Point() //可选轮廓偏移参数)

案例:

#include
#include
#include
#include
using namespace std;
using namespace cv;

//全局变量随机函数
RNG rng(12345);

int main()
{

	Mat src = imread("C:/Users/Administrator/Desktop/3.png");
	if (src.empty())
	{
		cout << "请检查图片是否存在..." << endl;
		return -1;
	}
	Mat grayimg;

	cvtColor(src, grayimg, COLOR_BGR2GRAY);
	blur(grayimg, grayimg, Size(5, 5));
	namedWindow("src");
	imshow("src", src);

	//初始化阈值
	int thresh = 80, thresh_max = 255;
	Mat edgeimg;
	Canny(grayimg, edgeimg, thresh, thresh * 2, 3);

	//查找轮廓
	vector>contours;
	vectorhierarchy;
	findContours(edgeimg, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
	//绘制轮廓
	Mat drawimg = Mat::zeros(edgeimg.size(), CV_8UC3);
	for (int i = 0; i < contours.size(); i++)
	{
		//drawContours(drawimg, contours, i, Scalar::all(rng.uniform(0, 255)), 2, 8, hierarchy, 0, Point(0, 0));
		drawContours(drawimg, contours, i, Scalar(122,160,144), 2, 8, hierarchy, 0, Point(0, 0));
	}
	imshow("dstimg", drawimg);


	waitKey(0);
	return 0;
}

结果展示:

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5651814.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存