opencv中的findContours的使用

1. findContours对0包围1的情况,会找出1来。

例如:

0,0,0

0,1,0

0,0,0 找出来的contour是1,1.

2. findContours对1包围0的情况,会找出0周围的点来。

1,1,1

1,0,1

1,1,1 找出来的contour是1,0;2,1;1,2;0,1

3. findContours会将传入的矩阵中的非零值设置成1,零值设置成0,找出相应的contour。

4. 以下是一个打印处所有contour的例子:

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv/cv.h"
#include <iostream>

using namespace std;
using namespace cv;

void printContours(Mat & mat, Mat& copy);

int main(char* args) {
  int length = 15;
  int border3 = 3;
  int border1 = 1;
  Mat mat1(length, length, CV_8UC1, Scalar::all(1));
  Mat mat2(length, length, CV_8UC1, Scalar::all(0));

  Mat mat3(length, length, CV_8UC1, Scalar::all(1));
  mat2.at< unsigned char >(2,2) = 0;

    cout << "mat2 = "<< endl << " "  << mat2 << endl << endl;
    Mat copy = mat2.clone();
    printContours(mat2, copy);
}

void printContours(Mat & mat, Mat& copy) {
  /// Find contours
  vector<vector<Point> > contours;
  vector<Vec4i> hierarchy;
  findContours( mat, contours, hierarchy, RETR_TREE, CV_CHAIN_APPROX_SIMPLE);

  int contourSize = contours.size();
  for(int i = 0; i < contourSize; i++) {
    cout << "contours = "<< endl << " "  << contours[i] << endl << endl;

    Rect rect = cv::boundingRect(contours[i]);
    cout << "rect = "<< endl << " "  << rect << endl << endl;

    double area = cv::contourArea(contours[i], true);
    cout << "area = "<< endl << " "  << area << endl << endl;

  }

  int hierarchySize = hierarchy.size();
  for(int i = 0; i < hierarchySize; i ++) {
    cout << "hierarchy = "<< endl << " "  << hierarchy[i] << endl << endl;
  }

  cout << "mat = "<< endl << " "  << mat << endl << endl;
}