#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;
}