opencv3学习笔记——查找并绘制轮廓findContours

函数
findContours()
drawContours()
findcontours与drawcontours配合使用,用findcontours找出轮廓后,便可以用drawcontours函数将检测到的轮廓绘制出来。

完整代码

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


Mat srcimage, grayimage;
int g_threshold = 80, thresholdmax = 255;
Mat cannyoutput;
RNG rng(12345);

vector> contours;
vectorhierarchy;

void on_threshold(int, void*);

int main()
{	
	srcimage = imread("1.jpg");
	//转换为灰度图并模糊化降噪
	cvtColor(srcimage, grayimage, COLOR_BGR2GRAY);
	blur(grayimage, grayimage, Size(3 ,3));

	//创建窗口
	namedWindow("【原始图窗口】", WINDOW_AUTOSIZE);
	imshow("【原始图窗口】", srcimage);

	//创建滚动条并初始化
	createTrackbar("canny阈值", "【原始图窗口】", &g_threshold, thresholdmax, on_threshold);
	on_threshold(0, 0);

	waitKey(0);
	return(0);
	
}
//回调函数
void on_threshold(int, void*)
{	
	//canny边缘检测
	Canny(grayimage, cannyoutput, g_threshold, g_threshold * 2, 3);
	
	//寻找轮廓
	findContours(cannyoutput, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));

	//绘制轮廓
	Mat drawing = Mat::zeros(cannyoutput.size(), CV_8UC3);
	//遍历contours里的轮廓
	for (int i = 0; i < contours.size(); i++)
	{
		Scalar color = Scalar(rng.uniform(0, 255),rng.uniform(0,255),rng.uniform(0,255));//随机取轮廓颜色
		drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());//描绘轮廓
	}
	imshow("【轮廓图】", drawing);
}

运行截图
opencv3学习笔记——查找并绘制轮廓findContours_第1张图片opencv3学习笔记——查找并绘制轮廓findContours_第2张图片

你可能感兴趣的:(opencv)