01 找輪廓

輪廓(findContours、drawContours)

當我們做物件辨識時,透過輪廓可得到特定物件的資訊,協助我們做判斷,OpenCV的findContours()函式可找到影像的輪廓,依實際需求調整參數輸入,而這邊的輪廓和Sobel這些找邊緣的處理不同,Sobel是將物件內部消除,只保留物件邊緣,findContours是在經過Sobel處理之後,將這個只有邊緣的影像,把各個邊緣點做分類,連結的邊緣點儲存在同個容器內,當我們找到輪廓後,可用drawContours()劃出輪廓線,檢查是否取得正確或適合的輪廓。

screen-shot-2016-11-14-at-12-50-45-am

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

using namespace cv ;
using namespace std ;

int main() {
    cv::Mat src = cv::imread("/Users/powenko/Desktop/1.png");
    if(src.data!=NULL){
        
        Mat src_gray = imread("/Users/powenko/Desktop/1.png", CV_LOAD_IMAGE_GRAYSCALE);
        Mat contoursImg = src.clone();
        Mat edge;
        blur(src_gray, src_gray, Size(3,3));
        Canny(src_gray, edge, 50, 150, 3);
        
        vector<vector<Point>> contours;
        vector<Vec4i> hierarchy;
        RNG rng(12345);
        findContours(edge, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_NONE);
        for(int i = 0; i<contours.size(); i++){
            Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0, 255), 255);
            drawContours(contoursImg, contours, i, color, 2, 8, hierarchy);
        }
        
        cv::namedWindow("Image") ;
        cv::imshow("Image", src) ;
        cv::imshow("Powenko.com  result", contoursImg) ;
        cv::waitKey() ;
    }
    return 0;
}


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