一、简介
1、访问每一个轮廓
1 for(int i = 0; i < contours.size(); i++) 2 { 3 .......... 4 }
2、轮廓个数和单个轮廓中点的个数
1 vector<vector<Point>> contours;
vector<Point> --- size()表示单个轮廓中点的个数
vector<vector<Point>> --- size()表示轮廓的中个数
3、访问每一个轮廓的所有点
1 for( int i = 0; i < contours.size(); i++) 2 { 3 for(int j = 0; j < contours[i].size(); j += 15) 4 { 5 circle(dst, Point(contours[i][j].x, contours.[i][j].y), 3, Scalar(0, 255, 0), 2, 8); 6 waitKey(100); 7 8 line(dst, Point(10,10), Point(contours[i][j].x, contours[i][j].y), Scalar(0, 255, 0), 1, 8); 9 imshow("dst", dst); 10 } 11 }
二、画出每个轮廓的每个点
1 //画出每个轮廓的每个点 2 #include "opencv2/opencv.hpp" 3 4 using namespace cv; 5 6 int main() 7 { 8 Mat src=imread("2.jpg"); 9 Mat temp=src.clone(); 10 //转灰度图,二值化 11 cvtColor(src,src,CV_BGR2GRAY); 12 threshold(src,src,100,255,THRESH_BINARY); 13 imshow("thres",src); 14 //查找并绘制轮廓 15 vector<vector<Point>>contours; 16 vector<Vec4i>hierarcy; 17 findContours(src,contours,hierarcy,CV_RETR_TREE,CV_LINK_RUNS); 18 /*drawContours(temp,contours,-1,Scalar(0,255,0),2,8); 绘制并显示所有轮廓 19 imshow("contours",temp);*/ 20 21 //绘制轮廓的每一个点 22 for(int i=0; i<contours.size(); i++){ 23 for(int j=0; j<contours[i].size(); j++){ 24 circle(temp,Point(contours[i][j].x,contours[i][j].y),3,Scalar(0,255,0),2,8); 25 } 26 } 27 imshow("contours",temp); 28 waitKey(0); 29 return 0; 30 }
点的密度可以在第二层for循环中,通过控制自变量的取值来控制,具体操作如下:
1 for(int j=0; j<contours[i].size(); j+=15){ 2 circle(temp,Point(contours[i][j].x,contours[i][j].y),3,Scalar(0,255,0),2,8); 3 }
在绘制点时,可以添加一些别的操作,例如下面这个例子:
1 for(int i=0; i<contours.size(); i++){ 2 for(int j=0; j<contours[i].size(); j+=15){ 3 circle(temp,Point(contours[i][j].x,contours[i][j].y),3,Scalar(0,255,0),2,8); 4 line(temp,Point(10,10),Point(contours[i][j].x,contours[i][j].y), Scalar(0, 0, 255), 1, 8); 5 waitKey(100); 6 imshow("contours", temp); 7 } 8 }
三、孔洞填充
【示例】
1 //孔洞填充 2 #include "opencv2/opencv.hpp" 3 4 using namespace cv; 5 6 int main() 7 { 8 Mat src=imread("3.jpg"); 9 Mat temp=src.clone(); 10 //转灰度图,二值化 11 cvtColor(src,src,CV_BGR2GRAY); 12 threshold(src,src,100,255,THRESH_BINARY); 13 imshow("thres",src); 14 //查找并绘制轮廓 15 vector<vector<Point>>contours; 16 vector<Vec4i>hierarcy; 17 findContours(src,contours,hierarcy,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE); 18 19 ///孔洞填充 20 findContours(src, contours, hierarcy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); //查找轮廓 21 drawContours(temp, contours, -1, Scalar(0, 255, 0), -1, 8); //绘制轮廓 22 imshow("contours",temp); 23 waitKey(0); 24 return 0; 25 }