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);


...



Comments

Popular posts from this blog

OpenCV Stitching example (Stitcher class, Panorama)

(OpenCV Study) Background subtractor MOG, MOG2, GMG example source code (BackgroundSubtractorMOG, BackgroundSubtractorMOG2, BackgroundSubtractorGMG)

Example source code of extract HOG feature from images, save descriptor values to xml file, using opencv (using HOGDescriptor )

Real-time N camera stitching Class.

8 point algorithm (Matlab source code) / The method to get the Fundamental Matrix and the Essential matrix

Optical Flow sample source code using OpenCV

Video Stabilization example source code, (using cvFindHomography, cvWarpPerspective functions in openCV)

(OpenCV Study) calcOpticalFlowFarneback example source code ( dense optical flow )

yuv422(YUYV) to RGB and RGB to yuv422(YUYV), (Using OpenCV and TBB)

OpenCV Drawing Example, (line, circle, rectangle, ellipse, polyline, fillConvexPoly, putText, drawContours)