12/29/2016

findContours, drawContours example code

The code is various example code for drawing contours.


...
namedWindow("show1", 0);
 namedWindow("threshold", 0);
 namedWindow("contours", 0);

 Mat img;
 img = imread("pattern.jpg");

 cvtColor(img, img, CV_RGB2GRAY);
 
 imshow("show1", img);


 threshold(img, img, 128, 255, CV_THRESH_BINARY);
 imshow("threshold", img);


 Mat dst = Mat::zeros(img.rows, img.cols, CV_8UC3);
 
 vector< vector< Point> > contours;
 vector< Vec4i> hierarchy;

 findContours(img.clone(), contours, hierarchy,
  RETR_CCOMP, CHAIN_APPROX_SIMPLE);

 
 //ex 1)
 drawContours(dst, contours, -1, CV_RGB(255,0,0), 1, 8, hierarchy);

 
 // iterate through all the top-level contours,
 // draw each connected component with its own random color
 //ex 2)
 int idx = 0;
 for (; idx >= 0; idx = hierarchy[idx][0])
 {
  Scalar color(rand() & 255, rand() & 255, rand() & 255);
  //drawContours(dst, contours, idx, color, FILLED, 8, hierarchy);
  drawContours(dst, contours, idx, color, 1, 8, hierarchy);
 }
 


 //ex3
 for (int i = 0; i < contours.size(); ++i)
 {
  
  for (int j = 0; j < contours[i].size() - 1; ++j)
  {
   line(dst, contours[i][j], contours[i][j + 1], CV_RGB(255, 0, 0), 1);
  }
  line(dst, contours[i][0], contours[i][contours[i].size()-1], CV_RGB(255, 0, 0), 1);
  
 }

 //ex4
 for (int i = 0; i < contours.size(); ++i)
 {

  Scalar color(rand() & 255, rand() & 255, rand() & 255);
  //drawContours(dst, contours, idx, color, FILLED, 8, hierarchy);
  drawContours(dst, contours, i, color, 1, 8, hierarchy);
 }
 

 //imshow("show3", img);
 imshow("contours", dst);


...



No comments:

Post a Comment