《學習OpenCV》第八章輪廓課後題

畫一個圓,求輪廓,並用矩形逼近,求周長

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

using namespace std;
using namespace cv;

#define CVX_RED   CV_RGB(0xff, 0x00, 0x00)
#define CVX_GREEN CV_RGB(0x00, 0xff, 0x00)
#define CVX_BLUE  CV_RGB(0x00, 0x00, 0xff)

int main()
{
    /*1、載入一個圖像,傳承灰度圖*/
    const char filename[] = "/Users/linwang/Downloads/Circle/Circle.001.jpeg";
    IplImage * Img = cvLoadImage(filename,CV_LOAD_IMAGE_GRAYSCALE);
    cvShowImage("Gray", Img);
    
    /*2、二值化*/
    cvThreshold(Img, Img, 128, 255, CV_THRESH_BINARY);
    cvShowImage("D-V", Img);
    
    /*3、檢測輪廓*/
    CvMemStorage * storage = cvCreateMemStorage();
    CvSeq * first_contour = NULL;
    IplImage * Img_contour = cvCloneImage(Img);
    cvFindContours(Img_contour, storage, &first_contour);
    cout<<"Total : "<<first_contour->total<<endl;
    
    /*4、繪製輪廓*/
    IplImage * Img_Show = cvCreateImage(cvGetSize(Img), 8, 3);
    cvSetZero(Img_Show);
    cvCvtColor(Img,Img_Show, CV_GRAY2BGR);
 
    for(CvSeq * c = first_contour;c!=NULL;c=c->h_next)
    {
        cvDrawContours(Img_Show, first_contour, CVX_RED, CVX_GREEN, 0,2,8);
    }
    cvShowImage("lunkuo", Img_Show);
    

    /*5、顯示輪廓的點集*/
    CvSeq* seq = cvCreateSeq(CV_SEQ_ELTYPE_POINT | CV_SEQ_KIND_CURVE  | CV_SEQ_FLAG_CLOSED,sizeof(CvContour),sizeof(CvPoint),storage);
    for(CvSeq * c = first_contour;c!=NULL;c=c->h_next)
    {
        for(int i = 0 ;i<first_contour->total;i++)
        {
            CvPoint * pt = CV_GET_SEQ_ELEM(CvPoint, c, i);
            cvSeqPush(seq,pt);
        }
    }
    
    /*6、圓的擬合結果由CvBox2D構成,給出的矩形正好包圍橢圓x*/
    CvBox2D  box;
    box = cvFitEllipse2(seq);
    cout<<"圓心爲 : ("<<box.center.x<<","<<box.center.y<<")"<<endl;
    cout<<"width : "<<box.size.width<<endl;
    cout<<"heigfht : "<<box.size.height<<endl;
    cout<<"Angle : "<<box.angle<<endl;
    cvWaitKey(100000);
    cvReleaseImage(&Img_Show);
    cvReleaseMemStorage(&storage);
    return 1;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章