opencv基础(3)——cvFindContours提取轮廓

1、findContours函数原型以及参数介绍

void findContours
(
                 InputOutputArray image,            //输入图像,必须是8位单通道图像,并且应该转化成二值的

                  OutputArrayOfArrays contours, //检测到的轮廓,每个轮廓被表示成一个point向量

                  OutputArray hierarchy,              //可选的输出向量,包含图像的拓扑信息。其中元素的个数和检测到的轮廓的数量相等

                  int mode,                                   //说明需要的轮廓类型和希望的返回值方式

                  int method,                                //轮廓近似方法

                  Point offset = Point()                 //轮廓点相对偏移点
  )

2、测试代码

#include <stdio.h>
#include <iostream>
#include <vector>
#include "core.hpp" 
#include "highgui.hpp"
#include "imgproc.hpp"

using namespace cv;
using namespace std;
 
int main()
{
    //1 加载和现实原图
    Mat matSrc = imread("1.jpg", IMREAD_COLOR);
    namedWindow("matSrc");
    imshow("matSrc", matSrc);

    //2二值化原图
    Mat matBinnay(matSrc.rows, matSrc.cols, CV_8UC1);
    threshold(matSrc, matBinnay, 128, 255, THRESH_BINARY);
    imwrite("22.bmp", matBinnay);

    //3提取轮廓
    vector<vector<Point>> vPoints; //保存轮廓点
    vector<Vec4i> hierarchy; //保存轮廓块关系
    findContours(matBinnay, vPoints, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);

    //4画轮廓点
    Mat matDraw = imread("1.bmp", IMREAD_COLOR);
    int iCount = vPoints.size();
    for (int i = 0; iCount; i++)
    {
        vector<Point> vPoint = vPoints[i];
        int iSize = vPoint.size();
        for (int j = 0; j < iSize; j++)
        {
            Point pt = vPoint[j];
            line(matDraw, pt, pt, Scalar(0, 0, 255), 3);
        }
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/cwj066/article/details/83243679