02 凸殼(convexHull)

凸殼(convexHull)

凸殼(Convex Hull)是一個計算幾何中的概念,在給定二維平面上的點集合,凸殼就是將最外層的點連接起來的凸多邊型,
能包含點集合中的所有點,在影像處理中,通常是找到某個物件後,用來填補空隙,或者是進一步的進行物件辨識。

OpenCV凸殼

void convexHull(InputArray points, OutputArray hull, bool clockwise=false, bool returnPoints=true)

  • points:輸入資訊,可以為包含點的容器(vector)或是Mat。
  • hull:輸出資訊,包含點的容器(vector)。
  • lockwise:方向旗標,如果true是順時針,false是逆時針。

 

#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){
        cvtColor( src, src_gray, CV_BGR2GRAY );
        
        //Dilate
        int erosion_size =10;
        Mat element = getStructuringElement(cv::MORPH_ELLIPSE,
                                            cv::Size(2 * erosion_size + 1, 2 * erosion_size + 1),
                                            cv::Point(erosion_size, erosion_size) );
        
        dilate(src_gray,src_gray,element);
        
        imshow( "Source", src_gray );
        
        // Convex Hull implementation
        Mat src_copy = src_gray.clone();
        Mat threshold_output;
        vector<vector<Point> > contours;
        vector<Vec4i> hierarchy;
        
        // Find contours
        threshold( src_gray, threshold_output, 200, 255, THRESH_BINARY );
        findContours( threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
        
        // Find the convex hull object for each contour
        vector<vector<Point> >hull( contours.size() );
        for( int i = 0; i < contours.size(); i++ )
        {  convexHull( Mat(contours[i]), hull[i], false ); }
        
        // Draw contours + hull results
        RNG rng;
        Mat drawing = Mat::zeros( threshold_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, 1, 8, vector<Vec4i>(), 0, Point() );
            drawContours( drawing, hull, i, color, 1, 8, vector<Vec4i>(), 0, Point() );
        }
        
        
        
        cv::namedWindow("Image") ;
        cv::imshow("Image", src) ;
        cv::imshow("result", src_gray) ;
        cv::waitKey() ;
    }
    return 0;
}

screen-shot-2016-11-14-at-12-35-23-am

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