03 輪廓包覆(boundingRect、minAreaRect、minEnclosingCircle)

#include <iostream>
#include <opencv2/core/core.hpp> 
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>

using namespace cv ;
using namespace std ;

int main() {
    
    Mat src_gray;
    cv::Mat src = cv::imread("/Users/powenko/Desktop/1.png");
    if(src.data!=NULL){
       
        ///////////////////////
        Mat img(500, 500, CV_8UC3);
        RNG& rng = cv::theRNG();
        
        cout << "\n這個程序演示了凸包函數的使用,任意給定一些點,求出包圍這些點的凸包\n" <<endl;
        
       
            char key;
        int i, count = 100; //(unsigned)rng%100 + 1;
            
            vector<Point> points;
            //隨機在1-100個點,這些點位於圖像中心3/4處。
            for( i = 0; i < count; i++ )
            {
                Point pt;
                pt.x = rng.uniform(img.cols/4, img.cols*3/4);
                pt.y = rng.uniform(img.rows/4, img.rows*3/4);
                
                points.push_back(pt);
            }
            
            //計算凸包
            vector<int>hull;
            convexHull(Mat(points), hull, true);
            
            //畫隨機點
            img = Scalar::all(0);
            for( i = 0; i < count; i++ )
                circle(img, points[i], 3, Scalar(0, 0, 255), CV_FILLED, CV_AA);
            
            int hullcount = (int)hull.size();
            Point pt0 = points[hull[hullcount-1]];
            //畫凸包
            for( i = 0; i < hullcount; i++ )
            { 
                Point pt = points[hull[i]]; 
                line(img, pt0, pt, Scalar(0, 255, 0), 1, CV_AA); 
                pt0 = pt; 
            }
        
        ///////////////////////
        
        cv::namedWindow("Image") ;
        cv::imshow("result", img) ;
        cv::waitKey() ;
    }
    return 0;
}

screen-shot-2016-11-14-at-12-46-36-am

OpenCV
CH01 簡介CH02 OpenCV APICH03 繪圖CH04 應用範例CH06 haarcascadesCH06 surf和siftCH07 OCRCH09 FaceCH5 輪廓(findContours、drawContours)