Merge pull request #2887 from ilya-lavrenov:ipp_morph_fix
[platform/upstream/opencv.git] / samples / cpp / smiledetect.cpp
1 #include "opencv2/objdetect.hpp"
2 #include "opencv2/highgui.hpp"
3 #include "opencv2/imgproc.hpp"
4 #include "opencv2/core/utility.hpp"
5
6 #include "opencv2/highgui/highgui_c.h"
7
8 #include <cctype>
9 #include <iostream>
10 #include <iterator>
11 #include <stdio.h>
12
13 using namespace std;
14 using namespace cv;
15
16 static void help()
17 {
18     cout << "\nThis program demonstrates the smile detector.\n"
19             "Usage:\n"
20             "./smiledetect [--cascade=<cascade_path> this is the frontal face classifier]\n"
21             "   [--smile-cascade=[<smile_cascade_path>]]\n"
22             "   [--scale=<image scale greater or equal to 1, try 2.0 for example. The larger the faster the processing>]\n"
23             "   [--try-flip]\n"
24             "   [video_filename|camera_index]\n\n"
25             "Example:\n"
26             "./smiledetect --cascade=\"../../data/haarcascades/haarcascade_frontalface_alt.xml\" --smile-cascade=\"../../data/haarcascades/haarcascade_smile.xml\" --scale=2.0\n\n"
27             "During execution:\n\tHit any key to quit.\n"
28             "\tUsing OpenCV version " << CV_VERSION << "\n" << endl;
29 }
30
31 void detectAndDraw( Mat& img, CascadeClassifier& cascade,
32                     CascadeClassifier& nestedCascade,
33                     double scale, bool tryflip );
34
35 string cascadeName = "../../data/haarcascades/haarcascade_frontalface_alt.xml";
36 string nestedCascadeName = "../../data/haarcascades/haarcascade_smile.xml";
37
38
39 int main( int argc, const char** argv )
40 {
41     CvCapture* capture = 0;
42     Mat frame, frameCopy, image;
43     const string scaleOpt = "--scale=";
44     size_t scaleOptLen = scaleOpt.length();
45     const string cascadeOpt = "--cascade=";
46     size_t cascadeOptLen = cascadeOpt.length();
47     const string nestedCascadeOpt = "--smile-cascade";
48     size_t nestedCascadeOptLen = nestedCascadeOpt.length();
49     const string tryFlipOpt = "--try-flip";
50     size_t tryFlipOptLen = tryFlipOpt.length();
51     string inputName;
52     bool tryflip = false;
53
54     help();
55
56     CascadeClassifier cascade, nestedCascade;
57     double scale = 1;
58
59     for( int i = 1; i < argc; i++ )
60     {
61         cout << "Processing " << i << " " <<  argv[i] << endl;
62         if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 )
63         {
64             cascadeName.assign( argv[i] + cascadeOptLen );
65             cout << "  from which we have cascadeName= " << cascadeName << endl;
66         }
67         else if( nestedCascadeOpt.compare( 0, nestedCascadeOptLen, argv[i], nestedCascadeOptLen ) == 0 )
68         {
69             if( argv[i][nestedCascadeOpt.length()] == '=' )
70                 nestedCascadeName.assign( argv[i] + nestedCascadeOpt.length() + 1 );
71         }
72         else if( scaleOpt.compare( 0, scaleOptLen, argv[i], scaleOptLen ) == 0 )
73         {
74             if( !sscanf( argv[i] + scaleOpt.length(), "%lf", &scale ) || scale < 1 )
75                 scale = 1;
76             cout << " from which we read scale = " << scale << endl;
77         }
78         else if( tryFlipOpt.compare( 0, tryFlipOptLen, argv[i], tryFlipOptLen ) == 0 )
79         {
80             tryflip = true;
81             cout << " will try to flip image horizontally to detect assymetric objects\n";
82         }
83         else if( argv[i][0] == '-' )
84         {
85             cerr << "WARNING: Unknown option " << argv[i] << endl;
86         }
87         else
88             inputName.assign( argv[i] );
89     }
90
91     if( !cascade.load( cascadeName ) )
92     {
93         cerr << "ERROR: Could not load face cascade" << endl;
94         help();
95         return -1;
96     }
97     if( !nestedCascade.load( nestedCascadeName ) )
98     {
99         cerr << "ERROR: Could not load smile cascade" << endl;
100         help();
101         return -1;
102     }
103
104     if( inputName.empty() || (isdigit(inputName.c_str()[0]) && inputName.c_str()[1] == '\0') )
105     {
106         capture = cvCaptureFromCAM( inputName.empty() ? 0 : inputName.c_str()[0] - '0' );
107         int c = inputName.empty() ? 0 : inputName.c_str()[0] - '0' ;
108         if(!capture) cout << "Capture from CAM " <<  c << " didn't work" << endl;
109     }
110     else if( inputName.size() )
111     {
112         capture = cvCaptureFromAVI( inputName.c_str() );
113         if(!capture) cout << "Capture from AVI didn't work" << endl;
114     }
115
116     cvNamedWindow( "result", 1 );
117
118     if( capture )
119     {
120         cout << "In capture ..." << endl;
121         cout << endl << "NOTE: Smile intensity will only be valid after a first smile has been detected" << endl;
122
123         for(;;)
124         {
125             IplImage* iplImg = cvQueryFrame( capture );
126             frame = cv::cvarrToMat(iplImg);
127             if( frame.empty() )
128                 break;
129             if( iplImg->origin == IPL_ORIGIN_TL )
130                 frame.copyTo( frameCopy );
131             else
132                 flip( frame, frameCopy, 0 );
133
134             detectAndDraw( frameCopy, cascade, nestedCascade, scale, tryflip );
135
136             if( waitKey( 10 ) >= 0 )
137                 goto _cleanup_;
138         }
139
140         waitKey(0);
141
142 _cleanup_:
143         cvReleaseCapture( &capture );
144     }
145     else
146     {
147         cerr << "ERROR: Could not initiate capture" << endl;
148         help();
149         return -1;
150     }
151
152     cvDestroyWindow("result");
153     return 0;
154 }
155
156 void detectAndDraw( Mat& img, CascadeClassifier& cascade,
157                     CascadeClassifier& nestedCascade,
158                     double scale, bool tryflip)
159 {
160     int i = 0;
161     vector<Rect> faces, faces2;
162     const static Scalar colors[] =  { CV_RGB(0,0,255),
163         CV_RGB(0,128,255),
164         CV_RGB(0,255,255),
165         CV_RGB(0,255,0),
166         CV_RGB(255,128,0),
167         CV_RGB(255,255,0),
168         CV_RGB(255,0,0),
169         CV_RGB(255,0,255)} ;
170     Mat gray, smallImg( cvRound (img.rows/scale), cvRound(img.cols/scale), CV_8UC1 );
171
172     cvtColor( img, gray, COLOR_BGR2GRAY );
173     resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR );
174     equalizeHist( smallImg, smallImg );
175
176     cascade.detectMultiScale( smallImg, faces,
177         1.1, 2, 0
178         //|CASCADE_FIND_BIGGEST_OBJECT
179         //|CASCADE_DO_ROUGH_SEARCH
180         |CASCADE_SCALE_IMAGE
181         ,
182         Size(30, 30) );
183     if( tryflip )
184     {
185         flip(smallImg, smallImg, 1);
186         cascade.detectMultiScale( smallImg, faces2,
187                                  1.1, 2, 0
188                                  //|CASCADE_FIND_BIGGEST_OBJECT
189                                  //|CASCADE_DO_ROUGH_SEARCH
190                                  |CASCADE_SCALE_IMAGE
191                                  ,
192                                  Size(30, 30) );
193         for( vector<Rect>::const_iterator r = faces2.begin(); r != faces2.end(); r++ )
194         {
195             faces.push_back(Rect(smallImg.cols - r->x - r->width, r->y, r->width, r->height));
196         }
197     }
198
199     for( vector<Rect>::iterator r = faces.begin(); r != faces.end(); r++, i++ )
200     {
201         Mat smallImgROI;
202         vector<Rect> nestedObjects;
203         Point center;
204         Scalar color = colors[i%8];
205         int radius;
206
207         double aspect_ratio = (double)r->width/r->height;
208         if( 0.75 < aspect_ratio && aspect_ratio < 1.3 )
209         {
210             center.x = cvRound((r->x + r->width*0.5)*scale);
211             center.y = cvRound((r->y + r->height*0.5)*scale);
212             radius = cvRound((r->width + r->height)*0.25*scale);
213             circle( img, center, radius, color, 3, 8, 0 );
214         }
215         else
216             rectangle( img, cvPoint(cvRound(r->x*scale), cvRound(r->y*scale)),
217                        cvPoint(cvRound((r->x + r->width-1)*scale), cvRound((r->y + r->height-1)*scale)),
218                        color, 3, 8, 0);
219
220         const int half_height=cvRound((float)r->height/2);
221         r->y=r->y + half_height;
222         r->height = half_height;
223         smallImgROI = smallImg(*r);
224         nestedCascade.detectMultiScale( smallImgROI, nestedObjects,
225             1.1, 0, 0
226             //|CASCADE_FIND_BIGGEST_OBJECT
227             //|CASCADE_DO_ROUGH_SEARCH
228             //|CASCADE_DO_CANNY_PRUNING
229             |CASCADE_SCALE_IMAGE
230             ,
231             Size(30, 30) );
232
233         // The number of detected neighbors depends on image size (and also illumination, etc.). The
234         // following steps use a floating minimum and maximum of neighbors. Intensity thus estimated will be
235         //accurate only after a first smile has been displayed by the user.
236         const int smile_neighbors = (int)nestedObjects.size();
237         static int max_neighbors=-1;
238         static int min_neighbors=-1;
239         if (min_neighbors == -1) min_neighbors = smile_neighbors;
240         max_neighbors = MAX(max_neighbors, smile_neighbors);
241
242         // Draw rectangle on the left side of the image reflecting smile intensity
243         float intensityZeroOne = ((float)smile_neighbors - min_neighbors) / (max_neighbors - min_neighbors + 1);
244         int rect_height = cvRound((float)img.rows * intensityZeroOne);
245         CvScalar col = CV_RGB((float)255 * intensityZeroOne, 0, 0);
246         rectangle(img, cvPoint(0, img.rows), cvPoint(img.cols/10, img.rows - rect_height), col, -1);
247     }
248
249     cv::imshow( "result", img );
250 }