一。查找绘制轮廓
1.查找轮廓
2.绘制轮廓
1 #include<opencv.hpp> 2 #include<iostream> 3 #include<vector> 4 using namespace std; 5 using namespace cv; 6 int main() 7 { 8 Mat srcImg = imread("F:/opencv/lena.jpg", 0); 9 imshow("yuantu", srcImg); 10 Mat dstImg = Mat::zeros(srcImg.rows, srcImg.cols, srcImg.type()); 11 threshold(srcImg, srcImg, 119, 255, THRESH_BINARY);//通过threshold进行二值化 12 imshow("二值图", srcImg); 13 vector<vector<Point>>contours; //每个轮廓由多个Point组成,有多个轮廓 14 vector<Vec4i>hierarchy; //保存每个轮廓的4个信息,hierarchy[i]代表第i个轮廓 hierarchy[i][0]表示第i个轮廓的后一个轮廓 15 findContours(srcImg, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE); //寻找轮廓,保存轮廓信息,和轮廓的索引信息 16 int index = 0; //第1个轮廓的索引 17 for (; index >= 0; index = hierarchy[index][0]) //index++,若index后面没有对应项,为-1 18 { 19 Scalar color(rand() % 255, rand() % 255, rand() % 255); 20 drawContours(dstImg, contours, index, color, FILLED, 8, hierarchy);//画轮廓 21 } 22 imshow("轮廓", dstImg); 23 waitKey(); 24 return 0; 25 }