1. 程式人生 > >OpenCV 輪廓檢測

OpenCV 輪廓檢測

讀入彩色3通道影象,轉換成灰度影象,再轉換成二值影象,完後檢測輪廓。

    // cvtcolor.cpp : 定義控制檯應用程式的入口點。  
    //  
      
    #include "stdafx.h"  
    #include <iostream>  
      
      
      
    #include <opencv2/highgui/highgui.hpp>  
    #include <opencv2/core/core.hpp>  
    #include <opencv2/imgproc/imgproc.hpp>  
      
    #pragma comment(lib, "opencv_highgui2410d.lib")  
    #pragma comment(lib, "opencv_core2410d.lib")  
    #pragma comment(lib, "opencv_imgproc2410d.lib")  
      
    using namespace cv;  
    using namespace std;  
      
    int main()  
    {  
        string image_name = "swan.jpg";  
      
        Mat src = imread(image_name);  
        imshow("src",src);  
                      
        Mat gray(src.size(),CV_8U);  
        cvtColor(src,gray,CV_BGR2GRAY);//轉換成灰度圖  
      
        imshow("gray",gray);  
      
        threshold(gray,gray,128,255,THRESH_BINARY);//轉換成2值影象  
        imshow("binary",gray);  
      
        /////////////////////////////////////////////////////////////////////  
        std::vector<std::vector<cv::Point>> contours;  
        cv::findContours(gray,   
            contours, // a vector of contours   
            CV_RETR_EXTERNAL, // retrieve the external contours  
            CV_CHAIN_APPROX_NONE); // retrieve all pixels of each contours  
      
        // Print contours' length  
        std::cout << "Contours: " << contours.size() << std::endl;  
        std::vector<std::vector<cv::Point>>::const_iterator itContours= contours.begin();  
        for ( ; itContours!=contours.end(); ++itContours)   
        {  
      
            std::cout << "Size: " << itContours->size() << std::endl;  
        }  
      
        // draw black contours on white image  
        cv::Mat result(gray.size(),CV_8U,cv::Scalar(255));  
        cv::drawContours(result,contours,  
            -1, // draw all contours  
            cv::Scalar(0), // in black  
            2); // with a thickness of 2  
      
        cv::namedWindow("Contours");  
        cv::imshow("Contours",result);  
      
      
        // draw contours on the original image  
        cv::Mat original= cv::imread(image_name);  
        cv::drawContours(original,contours,  
            -1, // draw all contours  
            cv::Scalar(255,255,255), // in white  
            -1); // with a thickness of 2  
      
        cv::namedWindow("Contours on Animals");  
        cv::imshow("Contours on Animals",original);  
      
        // Let's now draw black contours on white image  
        result.setTo(cv::Scalar(255));  
        cv::drawContours(result,contours,  
            -1, // draw all contours  
            cv::Scalar(0), // in black  
            -1); // with a thickness of 1  
        //image= cv::imread("test.png",0);  
      
      
      
      
        waitKey(0);  
      
        return 0;  
    }