findContours函数用于在二值图中寻找轮廓。
void cv::findContours | ( | InputArray | image, |
OutputArrayOfArrays | contours, //检测到的轮廓,运算结果存储在这,每一个轮廓存储为一个点向量,即point类型中的vector表示 | ||
OutputArray | hierarchy,//可选的输出向量,包含图像的拓扑信息,每个轮廓contours[i]对应4个hierarchy元素hierarchy[i][0]--[i][3]分别表示后一个轮廓,前一个轮廓,父轮廓,内嵌轮廓的索引编号。 | ||
int | mode, //轮廓检索模式 | ||
int | method, // 轮廓近似方法 | ||
Point | offset = Point() // 每个轮廓点的可选偏移量 | ||
) |
findContours常与drawContours()函数配合使用
例如:
vector<vector<Point>>contours;
findContours(img,contours,RETR_EXTERNAL,CHAIN_APPROX_NONE);
drawContour:
void cv::drawContours | ( | InputOutputArray | image, |
InputArrayOfArrays | contours,//所有输入的轮廓,每个轮廓存储为一个点向量 | ||
int | contourIdx, // 轮廓绘制的指示变量,若为负则绘制所有轮廓 | ||
const Scalar & | color, | ||
int | thickness = 1 , //线条粗细 | ||
int | lineType = LINE_8 , //线条类型 | ||
InputArray | hierarchy = noArray() , //可选层次结构信息 | ||
int | maxLevel = INT_MAX ,//用于绘制轮廓的最大等级 | ||
Point | offset = Point() //可选轮廓偏移参数 | ||
) |
案例:
#include<iostream>
#include<opencv2/opencv.hpp>
#include<opencv2/imgproc.hpp>
#include<opencv2/highgui.hpp>
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<vector<Point>>contours;
vector<Vec4i>hierarchy;
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;
}
结果展示: