b6b96c3434c42ef5992098c430ce30e6aee19ef1
[platform/upstream/opencv.git] / samples / c / mser_sample.cpp
1 /* This sample code was originally provided by Liu Liu
2  * Copyright (C) 2009, Liu Liu All rights reserved.
3  */
4
5 #include <opencv2/core/utility.hpp>
6 #include "opencv2/highgui.hpp"
7 #include "opencv2/features2d.hpp"
8 #include "opencv2/imgproc.hpp"
9
10 #include <iostream>
11 #include <stdio.h>
12
13 using namespace cv;
14 using namespace std;
15
16 static void help()
17 {
18     cout << "\nThis program demonstrates the Maximal Extremal Region interest point detector.\n"
19     "It finds the most stable (in size) dark and white regions as a threshold is increased.\n"
20     "\nCall:\n"
21     "./mser_sample <path_and_image_filename, Default is 'puzzle.png'>\n\n";
22 }
23
24 static const Vec3b bcolors[] =
25 {
26     Vec3b(0,0,255),
27     Vec3b(0,128,255),
28     Vec3b(0,255,255),
29     Vec3b(0,255,0),
30     Vec3b(255,128,0),
31     Vec3b(255,255,0),
32     Vec3b(255,0,0),
33     Vec3b(255,0,255),
34     Vec3b(255,255,255)
35 };
36
37 int main( int argc, char** argv )
38 {
39     string path;
40     Mat img0, img, yuv, gray, ellipses;
41     help();
42
43     img0 = imread( argc != 2 ? "puzzle.png" : argv[1], 1 );
44     if( img0.empty() )
45     {
46         if( argc != 2 )
47             cout << "\nUsage: mser_sample <path_to_image>\n";
48         else
49             cout << "Unable to load image " << argv[1] << endl;
50         return 0;
51     }
52
53     cvtColor(img0, yuv, COLOR_BGR2YCrCb);
54     cvtColor(img0, gray, COLOR_BGR2GRAY);
55     cvtColor(gray, img, COLOR_GRAY2BGR);
56     img.copyTo(ellipses);
57
58     vector<vector<Point> > contours;
59     double t = (double)getTickCount();
60     MSER()(yuv, contours);
61     t = (double)getTickCount() - t;
62     printf( "MSER extracted %d contours in %g ms.\n", (int)contours.size(),
63            t*1000./getTickFrequency() );
64
65     // draw mser's with different colors
66     for( int i = (int)contours.size()-1; i >= 0; i-- )
67     {
68         const vector<Point>& r = contours[i];
69         for ( int j = 0; j < (int)r.size(); j++ )
70         {
71             Point pt = r[j];
72             img.at<Vec3b>(pt) = bcolors[i%9];
73         }
74
75         // find ellipse (it seems cvfitellipse2 have error or sth?)
76         RotatedRect box = fitEllipse( r );
77
78         box.angle=(float)CV_PI/2-box.angle;
79         ellipse( ellipses, box, Scalar(196,255,255), 2 );
80     }
81
82     imshow( "original", img0 );
83     imshow( "response", img );
84     imshow( "ellipses", ellipses );
85
86     waitKey(0);
87 }