OpenCV: 尋找圖像輪廓並繪制
#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
#include <stdio.h>
#include<windows.h>
//Some defines we left out of the book
#define CVX_RED CV_RGB(0xff,0x00,0x00)
#define CVX_GREEN CV_RGB(0x00,0xff,0x00)
#define CVX_BLUE CV_RGB(0x00,0x00,0xff)
// Example 8-3. Finding and drawing contours on an input image
int main(int argc, char* argv[]) {
cvNamedWindow( "lkjc", 1 );
IplImage* img_8uc1 = NULL;
//Changed this a little for safer image loading and help if not
if( argc != 1 || !(img_8uc1 = cvLoadImage( "T_signs.jpg", CV_LOAD_IMAGE_GRAYSCALE )) ){
printf("\nExample 8_3 Drawing Contours\nCall is:\n./ch8_ex8_3 image\n\n");///* 8 bit unless combined with CV_LOAD_IMAGE_ANYDEPTH, color */
return -1;}
IplImage* img_edge = cvCreateImage( cvGetSize(img_8uc1), 8, 1 );
IplImage* img_8uc3 = cvCreateImage( cvGetSize(img_8uc1), 8, 3 );
cvThreshold( img_8uc1, img_edge, 128, 255, CV_THRESH_BINARY );//對數組元素進行固定阈值操作
CvMemStorage* storage = cvCreateMemStorage();
CvSeq* first_contour = NULL;
int Nc = cvFindContours(//在二值圖像中尋找輪廓
img_edge,
storage,
&first_contour,
sizeof(CvContour),
CV_RETR_LIST // Try all four values and see what happens
);
int n=0,k;
printf("\n\nHit any key to draw the next contour, ESC to quit\n\n");
printf( "Total Contours Detected: %d\n", Nc );
for( CvSeq* c=first_contour; c!=NULL; c=c->h_next ) {
cvCvtColor( img_8uc1, img_8uc3, CV_GRAY2BGR );
cvDrawContours(//在圖像中繪制外部和內部的輪廓
img_8uc3,
c,
CVX_RED, //Yarg, these are defined above, but not in the book. Oops
CVX_BLUE,
0, // 如果等級為0,繪制單獨的輪廓Try different values of max_level, and see what happens
2,
8
);
printf("Contour #%d\n", n );
cvShowImage( "lkjc", img_8uc3 );
printf(" %d elements:\n", c->total );
for( int i=0; i<c->total; ++i ) {
CvPoint* p = CV_GET_SEQ_ELEM( CvPoint, c, i );
printf(" (%d,%d)\n", p->x, p->y );
}
if((k = cvWaitKey()&0x7F) == 27)
break;
n++;
}
printf("Finished all contours. Hit key to finish\n");
cvCvtColor( img_8uc1, img_8uc3, CV_GRAY2BGR );
cvShowImage( "lkjc", img_8uc3 );
cvWaitKey(0);
cvDestroyWindow( "lkjc" );
cvReleaseImage( &img_8uc1 );
cvReleaseImage( &img_8uc3 );
cvReleaseImage( &img_edge );
system("pause");
return 0;
}
--------------------------------------分割線 --------------------------------------
Ubuntu Linux下安裝OpenCV2.4.1所需包 http://www.linuxidc.com/Linux/2012-08/68184.htm
Ubuntu 12.04 安裝 OpenCV2.4.2 http://www.linuxidc.com/Linux/2012-09/70158.htm
CentOS下OpenCV無法讀取視頻文件 http://www.linuxidc.com/Linux/2011-07/39295.htm
Ubuntu 12.04下安裝OpenCV 2.4.5總結 http://www.linuxidc.com/Linux/2013-06/86704.htm
Ubuntu 10.04中安裝OpenCv2.1九步曲 http://www.linuxidc.com/Linux/2010-09/28678.htm
基於QT和OpenCV的人臉識別系統 http://www.linuxidc.com/Linux/2011-11/47806.htm
--------------------------------------分割線 --------------------------------------
OpenCV的詳細介紹:請點這裡
OpenCV的下載地址:請點這裡