1. 程式人生 > >opencv2.4.9 findContours並求面積

opencv2.4.9 findContours並求面積

程式碼

#include<opencv2\highgui\highgui.hpp>
#include<opencv2\imgproc\imgproc.hpp>

#include<iostream>

using namespace std;
using namespace cv;

int main()
{
    Mat src = imread( "D:/MyDesktop/1.bmp" );
    Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);

    Mat canny_output;

    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    RNG rng;

    vector<double> area;

    /// Detect edges using canny
    Canny(src, canny_output, 100, 200);

    findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

    /// Draw contours
    Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);
    for (int i = 0; i< contours.size(); i++)
    {
        Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
        drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
        area.push_back( contourArea(contours[i]) );
    }

    cout << area.size() << endl;


    imshow("111", drawing);

    waitKey();
    return 0;
}

影象

原圖

這裡寫圖片描述

結果圖

這裡寫圖片描述