1. 程式人生 > >openCV-輪廓

openCV-輪廓

環境:openCV3.4.0,Linux,CMake
1、一般用序列來儲存輪廓資訊;
2、在尋找輪廓前,影象一般已經進行過二值化,或自適應二值化,或者進行了卷積處理,獲得了邊緣資訊,例如canny運算元處理,拉普拉斯處理,sobel運算元處理等獲得影象邊緣資訊的處理方法。
3、序列用於記錄找到的輪廓,當需要一個個處理找到的輪廓時,可以用cvFindContours、cvStartFindContours、cvFindNextContour、cvSubstituteContour、cvEndFindContour、cvApproxChains函式等進行特殊的操作,此處需要注意contour在序列中儲存的順序是根據cvFindContours的引數決定的,儲存的輪廓的壓縮方式,或者說是近似方式也是cvFindContours的引數決定的。
4、繪製輪廓用cvDrawContours函式進行即可,方便使用。
下面舉一個例子。

#include "cv.h"
#include "highgui.h"

int main(int argc,char **argv)
{
    //載入圖片,三通道的,單通道的都可以
    IplImage * g_image = NULL;

    if(argc !=2 || !(g_image = cvLoadImage(argv[1])))
        return -1;
    //顯示圖片的視窗
    cvNamedWindow("Contours",0);
    //對圖片進行灰度處理、二值化處理、尋找輪廓處理
    IplImage * g_gray = NULL
; int g_thresh = 100 ; CvMemStorage * g_storage = NULL; if(g_storage==NULL ) { g_gray = cvCreateImage(cvGetSize(g_image),8,1); g_storage = cvCreateMemStorage(0);//建立儲存空間 }else{ cvClearMemStorage(g_storage); //清除mem的空間 } CvSeq* contours = 0 ; cvCvtColor(g_image,g_gray,CV_BGR2GRAY); cvThreshold(g_gray,g_gray,g_thresh,255
,CV_THRESH_BINARY); cvFindContours(g_gray,g_storage,&contours); //顯示輪廓 cvZero(g_gray); if(contours) cvDrawContours( g_gray, contours, cvScalarAll(255), cvScalarAll(255), 100 ); cvShowImage("Contours",g_gray); cvWaitKey(0); return 0 ; }

原圖及效果圖如下:
這裡寫圖片描述
這裡寫圖片描述