1 /* This sample code was originally provided by Liu Liu
2 * Copyright� 2009, Liu Liu All rights reserved.
5 #include "opencv2/highgui/highgui.hpp"
6 #include "opencv2/features2d/features2d.hpp"
7 #include "opencv2/imgproc/imgproc_c.h"
9 static CvScalar colors[] =
24 static uchar bcolors[][3] =
37 int main( int argc, char** argv )
43 strcpy(path,"puzzle.png");
44 img = cvLoadImage( path, CV_LOAD_IMAGE_GRAYSCALE );
47 printf("\nUsage: mser_sample <path_to_image>\n");
54 img = cvLoadImage( path, CV_LOAD_IMAGE_GRAYSCALE );
59 printf("Unable to load image %s\n",path);
62 IplImage* rsp = cvLoadImage( path, CV_LOAD_IMAGE_COLOR );
63 IplImage* ellipses = cvCloneImage(rsp);
64 cvCvtColor(img,ellipses,CV_GRAY2BGR);
66 CvMemStorage* storage= cvCreateMemStorage();
67 IplImage* hsv = cvCreateImage( cvGetSize( rsp ), IPL_DEPTH_8U, 3 );
68 cvCvtColor( rsp, hsv, CV_BGR2YCrCb );
69 CvMSERParams params = cvMSERParams();//cvMSERParams( 5, 60, cvRound(.2*img->width*img->height), .25, .2 );
71 double t = (double)cvGetTickCount();
72 cvExtractMSER( hsv, NULL, &contours, storage, params );
73 t = cvGetTickCount() - t;
74 printf( "MSER extracted %d contours in %g ms.\n", contours->total, t/((double)cvGetTickFrequency()*1000.) );
75 uchar* rsptr = (uchar*)rsp->imageData;
76 // draw mser with different color
77 for ( int i = contours->total-1; i >= 0; i-- )
79 CvSeq* r = *(CvSeq**)cvGetSeqElem( contours, i );
80 for ( int j = 0; j < r->total; j++ )
82 CvPoint* pt = CV_GET_SEQ_ELEM( CvPoint, r, j );
83 rsptr[pt->x*3+pt->y*rsp->widthStep] = bcolors[i%9][2];
84 rsptr[pt->x*3+1+pt->y*rsp->widthStep] = bcolors[i%9][1];
85 rsptr[pt->x*3+2+pt->y*rsp->widthStep] = bcolors[i%9][0];
88 // find ellipse ( it seems cvfitellipse2 have error or sth?
89 for ( int i = 0; i < contours->total; i++ )
91 CvContour* r = *(CvContour**)cvGetSeqElem( contours, i );
92 CvBox2D box = cvFitEllipse2( r );
93 box.angle=(float)CV_PI/2-box.angle;
96 cvEllipseBox( ellipses, box, colors[9], 2 );
98 cvEllipseBox( ellipses, box, colors[2], 2 );
102 cvSaveImage( "rsp.png", rsp );
104 cvNamedWindow( "original", 0 );
105 cvShowImage( "original", img );
107 cvNamedWindow( "response", 0 );
108 cvShowImage( "response", rsp );
110 cvNamedWindow( "ellipses", 0 );
111 cvShowImage( "ellipses", ellipses );
115 cvDestroyWindow( "original" );
116 cvDestroyWindow( "response" );
117 cvDestroyWindow( "ellipses" );
118 cvReleaseImage(&rsp);
119 cvReleaseImage(&img);
120 cvReleaseImage(&ellipses);