OpenCV3之——查找并绘制轮廓findContours()和drawContours()

版权声明:转载请注明出处 https://blog.csdn.net/qq_35294564/article/details/82947011

一、基础示例:

#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main() {
	Mat srcImage = imread("1.jpg", 0);
	imshow("原始图", srcImage);

	Mat dstImage = Mat::zeros(srcImage.rows, srcImage.cols, CV_8UC3);
	srcImage = srcImage > 119;//srcImage取大于阈值119的那部分
	imshow("取阈值后的原始图", srcImage);

	//定义轮廓和层次结构
	vector<vector<Point>> contours;
	vector<Vec4i> hierarchy;

	findContours(srcImage, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);

	int index = 0;
	for (; index >= 0; index = hierarchy[index][0]) {
		Scalar color(rand() & 255, rand() & 255, rand() & 255);
		drawContours(dstImage, contours, index, color, CV_FILLED, 8, hierarchy);
	}

	imshow("轮廓图", dstImage);
	waitKey(0);
	return 0;
}

 

二、综合示例:

#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;

#define WINDOW_NAME1 "原始窗口"
#define WINDOW_NAME2 "轮廓图"

//全局变量声明
Mat g_srcImage;
Mat g_grayImage;
int g_nThresh = 80;
int g_nThresh_max = 255;
RNG g_rng(12345);
Mat g_cannyMat_output;
vector<vector<Point>> g_vContours;
vector<Vec4i> g_vHierarchy;
//全局函数声明部分
void on_ThreshChange(int, void *);

int main() {
	system("color 1F");
	g_srcImage = imread("1.jpg", 1);
	if (!g_srcImage.data) {
		printf("图片读入错误!\n");
		return false;
	}
	cvtColor(g_srcImage, g_grayImage, COLOR_BGR2GRAY);
	blur(g_grayImage, g_grayImage, Size(3, 3));

	//创建窗口
	namedWindow(WINDOW_NAME1, WINDOW_AUTOSIZE);
	imshow(WINDOW_NAME1, g_srcImage);

	//创建滚动条并初始化
	createTrackbar("canny阈值", WINDOW_NAME1, &g_nThresh, g_nThresh_max, on_ThreshChange);
	on_ThreshChange(0, 0);
	waitKey(0);
	return 0;
}

void on_ThreshChange(int, void*) {
	//用Canny算子检测边缘
	Canny(g_grayImage, g_cannyMat_output, g_nThresh, g_nThresh * 2, 3);
	//寻找轮廓
	findContours(g_cannyMat_output, g_vContours, g_vHierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
	//绘出轮廓
	Mat drawing = Mat::zeros(g_cannyMat_output.size(), CV_8UC3);
	for (int i = 0; i < g_vContours.size(); i++) {
		Scalar color = Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255));
		drawContours(drawing, g_vContours, i, color, 2, 8, g_vHierarchy, 0, Point());
	}
	imshow(WINDOW_NAME2, drawing);
}

 运行效果:

 

猜你喜欢

转载自blog.csdn.net/qq_35294564/article/details/82947011