寻找轮廓: findContours() 函数
绘制轮廓: drawContours()
例程: 轮廓查找
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/video.hpp>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
//1.载入原始图,且必须以二进制图模式载入
Mat srcImgae = imread("700levi.jpg", 0);
imshow("原始图", srcImgae);
//2.初始化结果图
Mat dstImage = Mat::zeros(srcImgae.rows, srcImgae.cols, CV_8UC3);
//3.srcImage取大于阈值119的那部分
srcImgae = srcImgae > 119;
imshow("取阈值后的原始图", srcImgae);
//4.定义轮廓和层次结构
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
//5.查找轮廓
findContours(srcImgae, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);
//6.遍历所有顶层的轮廓,以随机颜色绘制出每个链接组件的颜色
int index = 0;
for (;index>=0; index=hierarchy[index][0])
{
Scalar color(rand() & 255, rand() & 255, rand() & 255);
drawContours(dstImage, contours, index, color, FILLED, 8, hierarchy);
}
imshow("轮廓图", dstImage);
waitKey(0);
return 0;
}
效果图