OpenCV之图像轮廓检测及提取

OpenCV代码功能:检测并画出图像中的轮廓

主要函数:cvFindContours、cvDrawContours

#include <cv.h>
#include <highgui.h>
#include <cxcore.h>
#include <iostream.h>

void main()
{
    int i=0;
    int mode=CV_RETR_CCOMP;          //the mode of contours
    int num_contours=0;
    CvScalar ext_color,inn_color;
   
    CvMemStorage*storage=cvCreateMemStorage(0);
    CvSeq*contour=0;

IplImage*pimg=NULL;
    IplImage*CTImg=NULL;
    IplImage*src=cvLoadImage("test.bmp",-1);

pimg=cvCreateImage(cvGetSize(src),src->depth,1);
    CTImg=cvCreateImage(cvGetSize(pimg),IPL_DEPTH_8U,3);
    cvCvtColor(src,pimg,CV_BGR2GRAY);

cvNamedWindow("source",CV_WINDOW_AUTOSIZE);
    cvNamedWindow("gray",CV_WINDOW_AUTOSIZE);
    cvNamedWindow("contours",CV_WINDOW_AUTOSIZE);

cvShowImage("source",src);
    //cvThreshold(pimg,pimg,200,250,CV_THRESH_BINARY);
    cvErode(pimg,pimg,0,1);
    cvDilate(pimg,pimg,0,1);
    cvCanny(pimg,pimg,2,20,3);
    //cvErode(pimg,pimg,0,2);
    //cvDilate(pimg,pimg,0,1);
    //Find the Contours
    mode=CV_RETR_LIST;
    num_contours=cvFindContours(pimg,storage,&contour,sizeof(CvContour),mode,CV_CHAIN_APPROX_NONE);
    cout<<"The number of the contours is :"<<num_contours<<endl;
    //Draw the Contours
    for (;contour!=0;contour=contour->h_next)
    {
        inn_color=CV_RGB(rand()&255,rand()&255,rand()&255);
        ext_color=CV_RGB(rand()&255,rand()&255,rand()&255);
        cvDrawContours(CTImg,contour,ext_color,inn_color,1,2,8,cvPoint(0,0));
    }

cvShowImage("gray",pimg);
    cvShowImage("contours",CTImg);
    cvWaitKey(0);
    cvSaveImage("Contours.bmp",CTImg);
    cvSaveImage("Canny.bmp",pimg);

cvReleaseImage(&pimg);
    cvReleaseImage(&CTImg);
    cvReleaseImage(&src);
    cvReleaseMemStorage(&storage);

cvDestroyAllWindows();

}

效果图:

OpenCV之图像轮廓检测及提取

 

OpenCV之图像轮廓检测及提取

 

OpenCV之图像轮廓检测及提取

--------------------------------------分割线 --------------------------------------

Ubuntu Linux下安装OpenCV2.4.1所需包

Ubuntu 12.04 安装 OpenCV2.4.2

CentOS下OpenCV无法读取视频文件

Ubuntu 12.04下安装OpenCV 2.4.5总结

Ubuntu 10.04中安装OpenCv2.1九步曲

基于QT和OpenCV的人脸识别系统

[翻译]Ubuntu 14.04, 13.10 下安装 OpenCV 2.4.9 

--------------------------------------分割线 --------------------------------------

OpenCV的详细介绍请点这里
OpenCV的下载地址请点这里

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/c64c0de56f1207089459aa9a8615ea00.html