e6a32df3900504f17d4697e515fe13137a2c8f57
[platform/upstream/gstreamer.git] / ext / opencv / gstfacedetect.cpp
1 /*
2  * GStreamer
3  * Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
4  * Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
5  * Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
6  * Copyright (C) 2011 Stefan Sauer <ensonic@users.sf.net>
7  * Copyright (C) 2014 Robert Jobbagy <jobbagy.robert@gmail.com>
8  * Copyright (C) 2018 Nicola Murino <nicola.murino@gmail.com>
9  *
10  * Permission is hereby granted, free of charge, to any person obtaining a
11  * copy of this software and associated documentation files (the "Software"),
12  * to deal in the Software without restriction, including without limitation
13  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
14  * and/or sell copies of the Software, and to permit persons to whom the
15  * Software is furnished to do so, subject to the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be included in
18  * all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
26  * DEALINGS IN THE SOFTWARE.
27  *
28  * Alternatively, the contents of this file may be used under the
29  * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
30  * which case the following provisions apply instead of the ones
31  * mentioned above:
32  *
33  * This library is free software; you can redistribute it and/or
34  * modify it under the terms of the GNU Library General Public
35  * License as published by the Free Software Foundation; either
36  * version 2 of the License, or (at your option) any later version.
37  *
38  * This library is distributed in the hope that it will be useful,
39  * but WITHOUT ANY WARRANTY; without even the implied warranty of
40  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
41  * Library General Public License for more details.
42  *
43  * You should have received a copy of the GNU Library General Public
44  * License along with this library; if not, write to the
45  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
46  * Boston, MA 02110-1301, USA.
47  */
48
49 /**
50  * SECTION:element-facedetect
51  *
52  * Performs face detection on videos and images.
53  * If you have high cpu load you need to use videoscale with capsfilter and reduce the video resolution.
54  *
55  * The image is scaled down multiple times using the GstFaceDetect::scale-factor
56  * until the size is &lt;= GstFaceDetect::min-size-width or
57  * GstFaceDetect::min-size-height.
58  *
59  * ## Example launch line
60  *
61  * |[
62  * gst-launch-1.0 autovideosrc ! decodebin ! colorspace ! facedetect ! videoconvert ! xvimagesink
63  * ]| Detect and show faces
64  * |[
65  * gst-launch-1.0 autovideosrc ! video/x-raw,width=320,height=240 ! videoconvert ! facedetect min-size-width=60 min-size-height=60 ! colorspace ! xvimagesink
66  * ]| Detect large faces on a smaller image
67  *
68  */
69
70 /* FIXME: development version of OpenCV has CV_HAAR_FIND_BIGGEST_OBJECT which
71  * we might want to use if available
72  * see https://code.ros.org/svn/opencv/trunk/opencv/modules/objdetect/src/haar.cpp
73  */
74
75 #ifdef HAVE_CONFIG_H
76 #  include <config.h>
77 #endif
78
79 #include <vector>
80
81 using namespace std;
82
83 #include "gstfacedetect.h"
84 #include <opencv2/imgproc.hpp>
85
86 GST_DEBUG_CATEGORY_STATIC (gst_face_detect_debug);
87 #define GST_CAT_DEFAULT gst_face_detect_debug
88
89 #define HAAR_CASCADES_DIR OPENCV_PREFIX G_DIR_SEPARATOR_S "share" \
90     G_DIR_SEPARATOR_S OPENCV_PATH_NAME G_DIR_SEPARATOR_S "haarcascades" \
91     G_DIR_SEPARATOR_S
92 #define DEFAULT_FACE_PROFILE HAAR_CASCADES_DIR "haarcascade_frontalface_default.xml"
93 #define DEFAULT_NOSE_PROFILE HAAR_CASCADES_DIR "haarcascade_mcs_nose.xml"
94 #define DEFAULT_MOUTH_PROFILE HAAR_CASCADES_DIR "haarcascade_mcs_mouth.xml"
95 #define DEFAULT_EYES_PROFILE HAAR_CASCADES_DIR "haarcascade_mcs_eyepair_small.xml"
96 #define DEFAULT_SCALE_FACTOR 1.25
97 #if (CV_MAJOR_VERSION >= 4)
98 #define DEFAULT_FLAGS CASCADE_DO_CANNY_PRUNING
99 #else
100 #define DEFAULT_FLAGS CV_HAAR_DO_CANNY_PRUNING
101 #endif
102 #define DEFAULT_MIN_NEIGHBORS 3
103 #define DEFAULT_MIN_SIZE_WIDTH 30
104 #define DEFAULT_MIN_SIZE_HEIGHT 30
105 #define DEFAULT_MIN_STDDEV 0
106
107 using namespace cv;
108 /* Filter signals and args */
109 enum
110 {
111   /* FILL ME */
112   LAST_SIGNAL
113 };
114
115 enum
116 {
117   PROP_0,
118   PROP_DISPLAY,
119   PROP_FACE_PROFILE,
120   PROP_NOSE_PROFILE,
121   PROP_MOUTH_PROFILE,
122   PROP_EYES_PROFILE,
123   PROP_SCALE_FACTOR,
124   PROP_MIN_NEIGHBORS,
125   PROP_FLAGS,
126   PROP_MIN_SIZE_WIDTH,
127   PROP_MIN_SIZE_HEIGHT,
128   PROP_UPDATES,
129   PROP_MIN_STDDEV
130 };
131
132
133 /*
134  * GstOpencvFaceDetectFlags:
135  *
136  * Flags parameter to OpenCV's cvHaarDetectObjects function.
137  */
138 typedef enum
139 {
140   GST_OPENCV_FACE_DETECT_HAAR_DO_CANNY_PRUNING = (1 << 0)
141 } GstOpencvFaceDetectFlags;
142
143 #define GST_TYPE_OPENCV_FACE_DETECT_FLAGS (gst_opencv_face_detect_flags_get_type())
144
145 inline void
146 structure_and_message (const vector < Rect > &rectangles, const gchar * name,
147     guint rx, guint ry, GstFaceDetect * filter, GstStructure * s)
148 {
149   Rect sr = rectangles[0];
150   gchar *nx = g_strconcat (name, "->x", NULL);
151   gchar *ny = g_strconcat (name, "->y", NULL);
152   gchar *nw = g_strconcat (name, "->width", NULL);
153   gchar *nh = g_strconcat (name, "->height", NULL);
154
155   GST_LOG_OBJECT (filter,
156       "%s/%" G_GSIZE_FORMAT ": x,y = %4u,%4u: w.h = %4u,%4u",
157       name, rectangles.size (), rx + sr.x, ry + sr.y, sr.width, sr.height);
158   gst_structure_set (s, nx, G_TYPE_UINT, rx + sr.x, ny, G_TYPE_UINT, ry + sr.y,
159       nw, G_TYPE_UINT, sr.width, nh, G_TYPE_UINT, sr.height, NULL);
160
161   g_free (nx);
162   g_free (ny);
163   g_free (nw);
164   g_free (nh);
165 }
166
167 static void
168 register_gst_opencv_face_detect_flags (GType * id)
169 {
170   static const GFlagsValue values[] = {
171     {(guint) GST_OPENCV_FACE_DETECT_HAAR_DO_CANNY_PRUNING,
172         "Do Canny edge detection to discard some regions", "do-canny-pruning"},
173     {0, NULL, NULL}
174   };
175   *id = g_flags_register_static ("GstOpencvFaceDetectFlags", values);
176 }
177
178 static GType
179 gst_opencv_face_detect_flags_get_type (void)
180 {
181   static GType id;
182   static GOnce once = G_ONCE_INIT;
183
184   g_once (&once, (GThreadFunc) register_gst_opencv_face_detect_flags, &id);
185   return id;
186 }
187
188 #define GST_TYPE_FACE_DETECT_UPDATES (facedetect_update_get_type ())
189
190 static GType
191 facedetect_update_get_type (void)
192 {
193   static GType facedetect_update_type = 0;
194   static const GEnumValue facedetect_update[] = {
195     {GST_FACEDETECT_UPDATES_EVERY_FRAME, "Send update messages on every frame",
196         "every_frame"},
197     {GST_FACEDETECT_UPDATES_ON_CHANGE,
198           "Send messages when a new face is detected or one is not anymore detected",
199         "on_change"},
200     {GST_FACEDETECT_UPDATES_ON_FACE,
201           "Send messages whenever a face is detected",
202         "on_face"},
203     {GST_FACEDETECT_UPDATES_NONE, "Send no messages update", "none"},
204     {0, NULL, NULL},
205   };
206
207   if (!facedetect_update_type) {
208     facedetect_update_type =
209         g_enum_register_static ("GstFaceDetectUpdates", facedetect_update);
210   }
211   return facedetect_update_type;
212 }
213
214 /* the capabilities of the inputs and outputs.
215  */
216 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
217     GST_PAD_SINK,
218     GST_PAD_ALWAYS,
219     GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE ("RGB"))
220     );
221
222 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
223     GST_PAD_SRC,
224     GST_PAD_ALWAYS,
225     GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE ("RGB"))
226     );
227
228 G_DEFINE_TYPE (GstFaceDetect, gst_face_detect, GST_TYPE_OPENCV_VIDEO_FILTER);
229
230 static void gst_face_detect_set_property (GObject * object, guint prop_id,
231     const GValue * value, GParamSpec * pspec);
232 static void gst_face_detect_get_property (GObject * object, guint prop_id,
233     GValue * value, GParamSpec * pspec);
234
235 static gboolean gst_face_detect_set_caps (GstOpencvVideoFilter * transform,
236     gint in_width, gint in_height, int in_cv_type,
237     gint out_width, gint out_height, int out_cv_type);
238 static GstFlowReturn gst_face_detect_transform_ip (GstOpencvVideoFilter * base,
239     GstBuffer * buf, Mat img);
240
241 static CascadeClassifier *gst_face_detect_load_profile (GstFaceDetect *
242     filter, gchar * profile);
243
244 /* Clean up */
245 static void
246 gst_face_detect_finalize (GObject * obj)
247 {
248   GstFaceDetect *filter = GST_FACE_DETECT (obj);
249
250   filter->cvGray.release ();
251
252   g_free (filter->face_profile);
253   g_free (filter->nose_profile);
254   g_free (filter->mouth_profile);
255   g_free (filter->eyes_profile);
256
257   if (filter->cvFaceDetect)
258     delete (filter->cvFaceDetect);
259   if (filter->cvNoseDetect)
260     delete (filter->cvNoseDetect);
261   if (filter->cvMouthDetect)
262     delete (filter->cvMouthDetect);
263   if (filter->cvEyesDetect)
264     delete (filter->cvEyesDetect);
265
266   G_OBJECT_CLASS (gst_face_detect_parent_class)->finalize (obj);
267 }
268
269 /* initialize the facedetect's class */
270 static void
271 gst_face_detect_class_init (GstFaceDetectClass * klass)
272 {
273   GObjectClass *gobject_class;
274   GstOpencvVideoFilterClass *gstopencvbasefilter_class;
275
276   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
277   gobject_class = (GObjectClass *) klass;
278   gstopencvbasefilter_class = (GstOpencvVideoFilterClass *) klass;
279
280   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_face_detect_finalize);
281   gobject_class->set_property = gst_face_detect_set_property;
282   gobject_class->get_property = gst_face_detect_get_property;
283
284   gstopencvbasefilter_class->cv_trans_ip_func = gst_face_detect_transform_ip;
285   gstopencvbasefilter_class->cv_set_caps = gst_face_detect_set_caps;
286
287   g_object_class_install_property (gobject_class, PROP_DISPLAY,
288       g_param_spec_boolean ("display", "Display",
289           "Sets whether the detected faces should be highlighted in the output",
290           TRUE, (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
291
292   g_object_class_install_property (gobject_class, PROP_FACE_PROFILE,
293       g_param_spec_string ("profile", "Face profile",
294           "Location of Haar cascade file to use for face detection",
295           DEFAULT_FACE_PROFILE,
296           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
297   g_object_class_install_property (gobject_class, PROP_NOSE_PROFILE,
298       g_param_spec_string ("nose-profile", "Nose profile",
299           "Location of Haar cascade file to use for nose detection",
300           DEFAULT_NOSE_PROFILE,
301           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
302   g_object_class_install_property (gobject_class, PROP_MOUTH_PROFILE,
303       g_param_spec_string ("mouth-profile", "Mouth profile",
304           "Location of Haar cascade file to use for mouth detection",
305           DEFAULT_MOUTH_PROFILE,
306           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
307   g_object_class_install_property (gobject_class, PROP_EYES_PROFILE,
308       g_param_spec_string ("eyes-profile", "Eyes profile",
309           "Location of Haar cascade file to use for eye-pair detection",
310           DEFAULT_EYES_PROFILE,
311           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
312
313   g_object_class_install_property (gobject_class, PROP_FLAGS,
314       g_param_spec_flags ("flags", "Flags", "Flags to cvHaarDetectObjects",
315           GST_TYPE_OPENCV_FACE_DETECT_FLAGS, DEFAULT_FLAGS,
316           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
317   g_object_class_install_property (gobject_class, PROP_SCALE_FACTOR,
318       g_param_spec_double ("scale-factor", "Scale factor",
319           "Factor by which the frame is scaled after each object scan",
320           1.1, 10.0, DEFAULT_SCALE_FACTOR,
321           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
322   g_object_class_install_property (gobject_class, PROP_MIN_NEIGHBORS,
323       g_param_spec_int ("min-neighbors", "Mininum neighbors",
324           "Minimum number (minus 1) of neighbor rectangles that makes up "
325           "an object", 0, G_MAXINT, DEFAULT_MIN_NEIGHBORS,
326           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
327   g_object_class_install_property (gobject_class, PROP_MIN_SIZE_WIDTH,
328       g_param_spec_int ("min-size-width", "Minimum face width",
329           "Minimum area width to be recognized as a face", 0, G_MAXINT,
330           DEFAULT_MIN_SIZE_WIDTH,
331           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
332   g_object_class_install_property (gobject_class, PROP_MIN_SIZE_HEIGHT,
333       g_param_spec_int ("min-size-height", "Minimum face height",
334           "Minimum area height to be recognized as a face", 0, G_MAXINT,
335           DEFAULT_MIN_SIZE_HEIGHT,
336           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
337   g_object_class_install_property (gobject_class, PROP_UPDATES,
338       g_param_spec_enum ("updates", "Updates",
339           "When send update bus messages, if at all",
340           GST_TYPE_FACE_DETECT_UPDATES, GST_FACEDETECT_UPDATES_EVERY_FRAME,
341           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
342   g_object_class_install_property (gobject_class, PROP_MIN_STDDEV,
343       g_param_spec_int ("min-stddev", "Minimum image standard deviation",
344           "Minimum image average standard deviation: on images with standard "
345           "deviation lesser than this value facedetection will not be "
346           "performed. Setting this property help to save cpu and reduce "
347           "false positives not performing face detection on images with "
348           "little changes", 0, 255, DEFAULT_MIN_STDDEV,
349           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
350
351   gst_element_class_set_static_metadata (element_class,
352       "facedetect",
353       "Filter/Effect/Video",
354       "Performs face detection on videos and images, providing detected positions via bus messages",
355       "Michael Sheldon <mike@mikeasoft.com>");
356
357   gst_element_class_add_static_pad_template (element_class, &src_factory);
358   gst_element_class_add_static_pad_template (element_class, &sink_factory);
359 }
360
361 /* initialize the new element
362  * initialize instance structure
363  */
364 static void
365 gst_face_detect_init (GstFaceDetect * filter)
366 {
367   filter->face_profile = g_strdup (DEFAULT_FACE_PROFILE);
368   filter->nose_profile = g_strdup (DEFAULT_NOSE_PROFILE);
369   filter->mouth_profile = g_strdup (DEFAULT_MOUTH_PROFILE);
370   filter->eyes_profile = g_strdup (DEFAULT_EYES_PROFILE);
371   filter->display = TRUE;
372   filter->face_detected = FALSE;
373   filter->scale_factor = DEFAULT_SCALE_FACTOR;
374   filter->min_neighbors = DEFAULT_MIN_NEIGHBORS;
375   filter->flags = DEFAULT_FLAGS;
376   filter->min_size_width = DEFAULT_MIN_SIZE_WIDTH;
377   filter->min_size_height = DEFAULT_MIN_SIZE_HEIGHT;
378   filter->min_stddev = DEFAULT_MIN_STDDEV;
379   filter->cvFaceDetect =
380       gst_face_detect_load_profile (filter, filter->face_profile);
381   filter->cvNoseDetect =
382       gst_face_detect_load_profile (filter, filter->nose_profile);
383   filter->cvMouthDetect =
384       gst_face_detect_load_profile (filter, filter->mouth_profile);
385   filter->cvEyesDetect =
386       gst_face_detect_load_profile (filter, filter->eyes_profile);
387
388   gst_opencv_video_filter_set_in_place (GST_OPENCV_VIDEO_FILTER_CAST (filter),
389       TRUE);
390   filter->updates = GST_FACEDETECT_UPDATES_EVERY_FRAME;
391 }
392
393 static void
394 gst_face_detect_set_property (GObject * object, guint prop_id,
395     const GValue * value, GParamSpec * pspec)
396 {
397   GstFaceDetect *filter = GST_FACE_DETECT (object);
398
399   switch (prop_id) {
400     case PROP_FACE_PROFILE:
401       g_free (filter->face_profile);
402       if (filter->cvFaceDetect)
403         delete (filter->cvFaceDetect);
404       filter->face_profile = g_value_dup_string (value);
405       filter->cvFaceDetect =
406           gst_face_detect_load_profile (filter, filter->face_profile);
407       break;
408     case PROP_NOSE_PROFILE:
409       g_free (filter->nose_profile);
410       if (filter->cvNoseDetect)
411         delete (filter->cvNoseDetect);
412       filter->nose_profile = g_value_dup_string (value);
413       filter->cvNoseDetect =
414           gst_face_detect_load_profile (filter, filter->nose_profile);
415       break;
416     case PROP_MOUTH_PROFILE:
417       g_free (filter->mouth_profile);
418       if (filter->cvMouthDetect)
419         delete (filter->cvMouthDetect);
420       filter->mouth_profile = g_value_dup_string (value);
421       filter->cvMouthDetect =
422           gst_face_detect_load_profile (filter, filter->mouth_profile);
423       break;
424     case PROP_EYES_PROFILE:
425       g_free (filter->eyes_profile);
426       if (filter->cvEyesDetect)
427         delete (filter->cvEyesDetect);
428       filter->eyes_profile = g_value_dup_string (value);
429       filter->cvEyesDetect =
430           gst_face_detect_load_profile (filter, filter->eyes_profile);
431       break;
432     case PROP_DISPLAY:
433       filter->display = g_value_get_boolean (value);
434       break;
435     case PROP_SCALE_FACTOR:
436       filter->scale_factor = g_value_get_double (value);
437       break;
438     case PROP_MIN_NEIGHBORS:
439       filter->min_neighbors = g_value_get_int (value);
440       break;
441     case PROP_MIN_SIZE_WIDTH:
442       filter->min_size_width = g_value_get_int (value);
443       break;
444     case PROP_MIN_SIZE_HEIGHT:
445       filter->min_size_height = g_value_get_int (value);
446       break;
447     case PROP_MIN_STDDEV:
448       filter->min_stddev = g_value_get_int (value);
449       break;
450     case PROP_FLAGS:
451       filter->flags = g_value_get_flags (value);
452       break;
453     case PROP_UPDATES:
454       filter->updates = g_value_get_enum (value);
455       break;
456     default:
457       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
458       break;
459   }
460 }
461
462 static void
463 gst_face_detect_get_property (GObject * object, guint prop_id,
464     GValue * value, GParamSpec * pspec)
465 {
466   GstFaceDetect *filter = GST_FACE_DETECT (object);
467
468   switch (prop_id) {
469     case PROP_FACE_PROFILE:
470       g_value_set_string (value, filter->face_profile);
471       break;
472     case PROP_NOSE_PROFILE:
473       g_value_set_string (value, filter->nose_profile);
474       break;
475     case PROP_MOUTH_PROFILE:
476       g_value_set_string (value, filter->mouth_profile);
477       break;
478     case PROP_EYES_PROFILE:
479       g_value_set_string (value, filter->eyes_profile);
480       break;
481     case PROP_DISPLAY:
482       g_value_set_boolean (value, filter->display);
483       break;
484     case PROP_SCALE_FACTOR:
485       g_value_set_double (value, filter->scale_factor);
486       break;
487     case PROP_MIN_NEIGHBORS:
488       g_value_set_int (value, filter->min_neighbors);
489       break;
490     case PROP_MIN_SIZE_WIDTH:
491       g_value_set_int (value, filter->min_size_width);
492       break;
493     case PROP_MIN_SIZE_HEIGHT:
494       g_value_set_int (value, filter->min_size_height);
495       break;
496     case PROP_MIN_STDDEV:
497       g_value_set_int (value, filter->min_stddev);
498       break;
499     case PROP_FLAGS:
500       g_value_set_flags (value, filter->flags);
501       break;
502     case PROP_UPDATES:
503       g_value_set_enum (value, filter->updates);
504       break;
505     default:
506       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
507       break;
508   }
509 }
510
511 /* GstElement vmethod implementations */
512
513 /* this function handles the link with other elements */
514 static gboolean
515 gst_face_detect_set_caps (GstOpencvVideoFilter * transform, gint in_width,
516     gint in_height, int in_cv_type,
517     gint out_width, gint out_height, int out_cv_type)
518 {
519   GstFaceDetect *filter;
520
521   filter = GST_FACE_DETECT (transform);
522
523   filter->cvGray.create (Size (in_width, in_height), CV_8UC1);
524
525   return TRUE;
526 }
527
528 static GstMessage *
529 gst_face_detect_message_new (GstFaceDetect * filter, GstBuffer * buf)
530 {
531   GstBaseTransform *trans = GST_BASE_TRANSFORM_CAST (filter);
532   GstStructure *s;
533   GstClockTime running_time, stream_time;
534
535   running_time = gst_segment_to_running_time (&trans->segment, GST_FORMAT_TIME,
536       GST_BUFFER_TIMESTAMP (buf));
537   stream_time = gst_segment_to_stream_time (&trans->segment, GST_FORMAT_TIME,
538       GST_BUFFER_TIMESTAMP (buf));
539
540   s = gst_structure_new ("facedetect",
541       "timestamp", G_TYPE_UINT64, GST_BUFFER_TIMESTAMP (buf),
542       "stream-time", G_TYPE_UINT64, stream_time,
543       "running-time", G_TYPE_UINT64, running_time,
544       "duration", G_TYPE_UINT64, GST_BUFFER_DURATION (buf), NULL);
545
546   return gst_message_new_element (GST_OBJECT (filter), s);
547 }
548
549 static void
550 gst_face_detect_run_detector (GstFaceDetect * filter,
551     CascadeClassifier * detector, gint min_size_width,
552     gint min_size_height, Rect r, vector < Rect > &faces)
553 {
554   double img_stddev = 0;
555   if (filter->min_stddev > 0) {
556     Scalar mean, stddev;
557     meanStdDev (filter->cvGray, mean, stddev);
558     img_stddev = stddev.val[0];
559   }
560   if (img_stddev >= filter->min_stddev) {
561     Mat roi (filter->cvGray, r);
562     detector->detectMultiScale (roi, faces, filter->scale_factor,
563         filter->min_neighbors, filter->flags, Size (min_size_width,
564             min_size_height), Size (0, 0));
565   } else {
566     GST_LOG_OBJECT (filter,
567         "Calculated stddev %f lesser than min_stddev %d, detection not performed",
568         img_stddev, filter->min_stddev);
569   }
570 }
571
572 /*
573  * Performs the face detection
574  */
575 static GstFlowReturn
576 gst_face_detect_transform_ip (GstOpencvVideoFilter * base, GstBuffer * buf,
577     Mat img)
578 {
579   GstFaceDetect *filter = GST_FACE_DETECT (base);
580
581   if (filter->cvFaceDetect) {
582     GstMessage *msg = NULL;
583     GstStructure *s;
584     GValue facelist = { 0 };
585     GValue facedata = { 0 };
586     vector < Rect > faces;
587     vector < Rect > mouth;
588     vector < Rect > nose;
589     vector < Rect > eyes;
590     gboolean post_msg = FALSE;
591
592     cvtColor (img, filter->cvGray, COLOR_RGB2GRAY);
593
594     gst_face_detect_run_detector (filter, filter->cvFaceDetect,
595         filter->min_size_width, filter->min_size_height,
596         Rect (0, 0,
597             filter->cvGray.size ().width, filter->cvGray.size ().height),
598         faces);
599
600     switch (filter->updates) {
601       case GST_FACEDETECT_UPDATES_EVERY_FRAME:
602         post_msg = TRUE;
603         break;
604       case GST_FACEDETECT_UPDATES_ON_CHANGE:
605         if (!faces.empty ()) {
606           if (!filter->face_detected)
607             post_msg = TRUE;
608         } else {
609           if (filter->face_detected) {
610             post_msg = TRUE;
611           }
612         }
613         break;
614       case GST_FACEDETECT_UPDATES_ON_FACE:
615         if (!faces.empty ()) {
616           post_msg = TRUE;
617         } else {
618           post_msg = FALSE;
619         }
620         break;
621       case GST_FACEDETECT_UPDATES_NONE:
622         post_msg = FALSE;
623         break;
624       default:
625         post_msg = TRUE;
626         break;
627     }
628
629     filter->face_detected = !faces.empty ()? TRUE : FALSE;
630
631     if (post_msg) {
632       msg = gst_face_detect_message_new (filter, buf);
633       g_value_init (&facelist, GST_TYPE_LIST);
634     }
635
636     for (unsigned int i = 0; i < faces.size (); ++i) {
637       Rect r = faces[i];
638       guint mw = filter->min_size_width / 8;
639       guint mh = filter->min_size_height / 8;
640       guint rnx = 0, rny = 0, rnw, rnh;
641       guint rmx = 0, rmy = 0, rmw, rmh;
642       guint rex = 0, rey = 0, rew, reh;
643       guint rhh = r.height / 2;
644       gboolean have_nose, have_mouth, have_eyes;
645
646       /* detect face features */
647
648       if (filter->cvNoseDetect) {
649         rnx = r.x + r.width / 4;
650         rny = r.y + r.height / 4;
651         rnw = r.width / 2;
652         rnh = rhh;
653         gst_face_detect_run_detector (filter, filter->cvNoseDetect, mw, mh,
654             Rect (rnx, rny, rnw, rnh), nose);
655         have_nose = !nose.empty ();
656       } else {
657         have_nose = FALSE;
658       }
659
660       if (filter->cvMouthDetect) {
661         rmx = r.x;
662         rmy = r.y + r.height / 2;
663         rmw = r.width;
664         rmh = rhh;
665         gst_face_detect_run_detector (filter, filter->cvMouthDetect, mw,
666             mh, Rect (rmx, rmy, rmw, rmh), mouth);
667         have_mouth = !mouth.empty ();
668       } else {
669         have_mouth = FALSE;
670       }
671
672       if (filter->cvEyesDetect) {
673         rex = r.x;
674         rey = r.y;
675         rew = r.width;
676         reh = rhh;
677         gst_face_detect_run_detector (filter, filter->cvEyesDetect, mw, mh,
678             Rect (rex, rey, rew, reh), eyes);
679         have_eyes = !eyes.empty ();
680       } else {
681         have_eyes = FALSE;
682       }
683
684       GST_LOG_OBJECT (filter,
685           "%2d/%2" G_GSIZE_FORMAT
686           ": x,y = %4u,%4u: w.h = %4u,%4u : features(e,n,m) = %d,%d,%d", i,
687           faces.size (), r.x, r.y, r.width, r.height, have_eyes, have_nose,
688           have_mouth);
689       if (post_msg) {
690         s = gst_structure_new ("face",
691             "x", G_TYPE_UINT, r.x,
692             "y", G_TYPE_UINT, r.y,
693             "width", G_TYPE_UINT, r.width,
694             "height", G_TYPE_UINT, r.height, NULL);
695         if (have_nose)
696           structure_and_message (nose, "nose", rnx, rny, filter, s);
697         if (have_mouth)
698           structure_and_message (mouth, "mouth", rmx, rmy, filter, s);
699         if (have_eyes)
700           structure_and_message (eyes, "eyes", rex, rey, filter, s);
701
702         g_value_init (&facedata, GST_TYPE_STRUCTURE);
703         g_value_take_boxed (&facedata, s);
704         gst_value_list_append_value (&facelist, &facedata);
705         g_value_unset (&facedata);
706         s = NULL;
707       }
708
709       if (filter->display) {
710         Point center;
711         Size axes;
712         gdouble w, h;
713         gint cb = 255 - ((i & 3) << 7);
714         gint cg = 255 - ((i & 12) << 5);
715         gint cr = 255 - ((i & 48) << 3);
716
717         w = r.width / 2;
718         h = r.height / 2;
719         center.x = cvRound ((r.x + w));
720         center.y = cvRound ((r.y + h));
721         axes.width = w;
722         axes.height = h * 1.25; /* tweak for face form */
723         ellipse (img, center, axes, 0, 0, 360, Scalar (cr, cg, cb), 3, 8, 0);
724
725         if (have_nose) {
726           Rect sr = nose[0];
727
728           w = sr.width / 2;
729           h = sr.height / 2;
730           center.x = cvRound ((rnx + sr.x + w));
731           center.y = cvRound ((rny + sr.y + h));
732           axes.width = w;
733           axes.height = h * 1.25;       /* tweak for nose form */
734           ellipse (img, center, axes, 0, 0, 360, Scalar (cr, cg, cb), 1, 8, 0);
735         }
736         if (have_mouth) {
737           Rect sr = mouth[0];
738
739           w = sr.width / 2;
740           h = sr.height / 2;
741           center.x = cvRound ((rmx + sr.x + w));
742           center.y = cvRound ((rmy + sr.y + h));
743           axes.width = w * 1.5; /* tweak for mouth form */
744           axes.height = h;
745           ellipse (img, center, axes, 0, 0, 360, Scalar (cr, cg, cb), 1, 8, 0);
746         }
747         if (have_eyes) {
748           Rect sr = eyes[0];
749
750           w = sr.width / 2;
751           h = sr.height / 2;
752           center.x = cvRound ((rex + sr.x + w));
753           center.y = cvRound ((rey + sr.y + h));
754           axes.width = w * 1.5; /* tweak for eyes form */
755           axes.height = h;
756           ellipse (img, center, axes, 0, 0, 360, Scalar (cr, cg, cb), 1, 8, 0);
757         }
758       }
759       gst_buffer_add_video_region_of_interest_meta (buf, "face",
760           (guint) r.x, (guint) r.y, (guint) r.width, (guint) r.height);
761     }
762
763     if (post_msg) {
764       gst_structure_set_value ((GstStructure *) gst_message_get_structure (msg),
765           "faces", &facelist);
766       g_value_unset (&facelist);
767       gst_element_post_message (GST_ELEMENT (filter), msg);
768     }
769   }
770
771   return GST_FLOW_OK;
772 }
773
774
775 static CascadeClassifier *
776 gst_face_detect_load_profile (GstFaceDetect * filter, gchar * profile)
777 {
778   CascadeClassifier *cascade;
779
780   cascade = new CascadeClassifier (profile);
781   if (cascade->empty ()) {
782     GST_ERROR_OBJECT (filter, "Invalid profile file: %s", profile);
783     delete cascade;
784     return NULL;
785   }
786
787   return cascade;
788 }
789
790
791 /* entry point to initialize the plug-in
792  * initialize the plug-in itself
793  * register the element factories and other features
794  */
795 gboolean
796 gst_face_detect_plugin_init (GstPlugin * plugin)
797 {
798   /* debug category for fltering log messages */
799   GST_DEBUG_CATEGORY_INIT (gst_face_detect_debug, "facedetect",
800       0,
801       "Performs face detection on videos and images, providing detected positions via bus messages");
802
803   return gst_element_register (plugin, "facedetect", GST_RANK_NONE,
804       GST_TYPE_FACE_DETECT);
805 }