opencv中的findContours的使用

本文详细介绍了OpenCV中findContours函数的工作原理及应用示例。针对0被1包围和1被0包围的不同情况,该函数能准确地找出轮廓点。通过示例代码展示了如何使用findContours函数来查找图像中的轮廓,并打印出所有找到的轮廓及其属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值