7de576dcd63a6e3fb9d47a07055b4276bc86f151
[platform/upstream/gstreamer.git] / ext / opencv / gstfaceblur.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 Robert Jobbagy <jobbagy.robert@gmail.com>
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a
9  * copy of this software and associated documentation files (the "Software"),
10  * to deal in the Software without restriction, including without limitation
11  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12  * and/or sell copies of the Software, and to permit persons to whom the
13  * Software is furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24  * DEALINGS IN THE SOFTWARE.
25  *
26  * Alternatively, the contents of this file may be used under the
27  * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
28  * which case the following provisions apply instead of the ones
29  * mentioned above:
30  *
31  * This library is free software; you can redistribute it and/or
32  * modify it under the terms of the GNU Library General Public
33  * License as published by the Free Software Foundation; either
34  * version 2 of the License, or (at your option) any later version.
35  *
36  * This library is distributed in the hope that it will be useful,
37  * but WITHOUT ANY WARRANTY; without even the implied warranty of
38  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
39  * Library General Public License for more details.
40  *
41  * You should have received a copy of the GNU Library General Public
42  * License along with this library; if not, write to the
43  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
44  * Boston, MA 02110-1301, USA.
45  */
46
47 /**
48  * SECTION:element-faceblur
49  *
50  * Blurs faces in images and videos.
51  *
52  * ## Example launch line
53  *
54  * |[
55  * gst-launch-1.0 autovideosrc ! videoconvert ! faceblur ! videoconvert ! autovideosink
56  * ]|
57  */
58
59 #ifdef HAVE_CONFIG_H
60 #  include <config.h>
61 #endif
62
63 #include <vector>
64
65 #include "gstfaceblur.h"
66 #include <opencv2/imgproc.hpp>
67
68 GST_DEBUG_CATEGORY_STATIC (gst_face_blur_debug);
69 #define GST_CAT_DEFAULT gst_face_blur_debug
70
71 #define DEFAULT_PROFILE OPENCV_PREFIX G_DIR_SEPARATOR_S "share" \
72     G_DIR_SEPARATOR_S OPENCV_PATH_NAME G_DIR_SEPARATOR_S "haarcascades" \
73     G_DIR_SEPARATOR_S "haarcascade_frontalface_default.xml"
74 #define DEFAULT_SCALE_FACTOR 1.25
75 #if (CV_MAJOR_VERSION >= 4)
76 #define DEFAULT_FLAGS CASCADE_DO_CANNY_PRUNING
77 #else
78 #define DEFAULT_FLAGS CV_HAAR_DO_CANNY_PRUNING
79 #endif
80 #define DEFAULT_MIN_NEIGHBORS 3
81 #define DEFAULT_MIN_SIZE_WIDTH 30
82 #define DEFAULT_MIN_SIZE_HEIGHT 30
83
84 using namespace cv;
85 using namespace std;
86 enum
87 {
88   PROP_0,
89   PROP_PROFILE,
90   PROP_SCALE_FACTOR,
91   PROP_MIN_NEIGHBORS,
92   PROP_FLAGS,
93   PROP_MIN_SIZE_WIDTH,
94   PROP_MIN_SIZE_HEIGHT
95 };
96
97 /**
98  * GstOpencvFaceDetectFlags:
99  * @GST_CAMERABIN_FLAG_SOURCE_RESIZE: enable video crop and scale
100  *   after capture
101  *
102  * Flags parameter to OpenCV's cvHaarDetectObjects function.
103  */
104 typedef enum
105 {
106   GST_OPENCV_FACE_BLUR_HAAR_DO_CANNY_PRUNING = (1 << 0)
107 } GstOpencvFaceBlurFlags;
108
109 #define GST_TYPE_OPENCV_FACE_BLUR_FLAGS (gst_opencv_face_blur_flags_get_type())
110
111 static void
112 register_gst_opencv_face_blur_flags (GType * id)
113 {
114   static const GFlagsValue values[] = {
115     {(guint) GST_OPENCV_FACE_BLUR_HAAR_DO_CANNY_PRUNING,
116         "Do Canny edge detection to discard some regions", "do-canny-pruning"},
117     {0, NULL, NULL}
118   };
119   *id = g_flags_register_static ("GstOpencvFaceBlurFlags", values);
120 }
121
122 static GType
123 gst_opencv_face_blur_flags_get_type (void)
124 {
125   static GType id;
126   static GOnce once = G_ONCE_INIT;
127
128   g_once (&once, (GThreadFunc) register_gst_opencv_face_blur_flags, &id);
129   return id;
130 }
131
132 /* the capabilities of the inputs and outputs.
133  */
134 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
135     GST_PAD_SINK,
136     GST_PAD_ALWAYS,
137     GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE ("RGB"))
138     );
139
140 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
141     GST_PAD_SRC,
142     GST_PAD_ALWAYS,
143     GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE ("RGB"))
144     );
145
146 G_DEFINE_TYPE (GstFaceBlur, gst_face_blur, GST_TYPE_OPENCV_VIDEO_FILTER);
147
148 static void gst_face_blur_set_property (GObject * object, guint prop_id,
149     const GValue * value, GParamSpec * pspec);
150 static void gst_face_blur_get_property (GObject * object, guint prop_id,
151     GValue * value, GParamSpec * pspec);
152
153
154 static gboolean gst_face_blur_set_caps (GstOpencvVideoFilter * transform,
155     gint in_width, gint in_height, int in_cv_type,
156     gint out_width, gint out_height, int out_cv_type);
157 static GstFlowReturn gst_face_blur_transform_ip (GstOpencvVideoFilter *
158     transform, GstBuffer * buffer, Mat img);
159
160 static CascadeClassifier *gst_face_blur_load_profile (GstFaceBlur *
161     filter, gchar * profile);
162
163 /* Clean up */
164 static void
165 gst_face_blur_finalize (GObject * obj)
166 {
167   GstFaceBlur *filter = GST_FACE_BLUR (obj);
168
169   filter->cvGray.release ();
170
171   if (filter->cvCascade)
172     delete filter->cvCascade;
173
174   g_free (filter->profile);
175
176   G_OBJECT_CLASS (gst_face_blur_parent_class)->finalize (obj);
177 }
178
179
180 /* initialize the faceblur's class */
181 static void
182 gst_face_blur_class_init (GstFaceBlurClass * klass)
183 {
184   GObjectClass *gobject_class;
185   GstOpencvVideoFilterClass *gstopencvbasefilter_class;
186
187   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
188   gobject_class = (GObjectClass *) klass;
189   gstopencvbasefilter_class = (GstOpencvVideoFilterClass *) klass;
190
191   gstopencvbasefilter_class->cv_trans_ip_func = gst_face_blur_transform_ip;
192   gstopencvbasefilter_class->cv_set_caps = gst_face_blur_set_caps;
193
194   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_face_blur_finalize);
195   gobject_class->set_property = gst_face_blur_set_property;
196   gobject_class->get_property = gst_face_blur_get_property;
197
198   g_object_class_install_property (gobject_class, PROP_PROFILE,
199       g_param_spec_string ("profile", "Profile",
200           "Location of Haar cascade file to use for face blurion",
201           DEFAULT_PROFILE,
202           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
203   g_object_class_install_property (gobject_class, PROP_FLAGS,
204       g_param_spec_flags ("flags", "Flags", "Flags to cvHaarDetectObjects",
205           GST_TYPE_OPENCV_FACE_BLUR_FLAGS, DEFAULT_FLAGS,
206           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
207   g_object_class_install_property (gobject_class, PROP_SCALE_FACTOR,
208       g_param_spec_double ("scale-factor", "Scale factor",
209           "Factor by which the windows is scaled after each scan", 1.1, 10.0,
210           DEFAULT_SCALE_FACTOR,
211           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
212   g_object_class_install_property (gobject_class, PROP_MIN_NEIGHBORS,
213       g_param_spec_int ("min-neighbors", "Mininum neighbors",
214           "Minimum number (minus 1) of neighbor rectangles that makes up "
215           "an object", 0, G_MAXINT, DEFAULT_MIN_NEIGHBORS,
216           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
217   g_object_class_install_property (gobject_class, PROP_MIN_SIZE_WIDTH,
218       g_param_spec_int ("min-size-width", "Minimum size width",
219           "Minimum window width size", 0, G_MAXINT, DEFAULT_MIN_SIZE_WIDTH,
220           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
221   g_object_class_install_property (gobject_class, PROP_MIN_SIZE_HEIGHT,
222       g_param_spec_int ("min-size-height", "Minimum size height",
223           "Minimum window height size", 0, G_MAXINT, DEFAULT_MIN_SIZE_HEIGHT,
224           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
225
226   gst_element_class_set_static_metadata (element_class,
227       "faceblur",
228       "Filter/Effect/Video",
229       "Blurs faces in images and videos",
230       "Michael Sheldon <mike@mikeasoft.com>,Robert Jobbagy <jobbagy.robert@gmail.com>");
231
232   gst_element_class_add_static_pad_template (element_class, &src_factory);
233   gst_element_class_add_static_pad_template (element_class, &sink_factory);
234 }
235
236 /* initialize the new element
237  * instantiate pads and add them to element
238  * set pad calback functions
239  * initialize instance structure
240  */
241 static void
242 gst_face_blur_init (GstFaceBlur * filter)
243 {
244   filter->profile = g_strdup (DEFAULT_PROFILE);
245   filter->cvCascade = gst_face_blur_load_profile (filter, filter->profile);
246   filter->sent_profile_load_failed_msg = FALSE;
247   filter->scale_factor = DEFAULT_SCALE_FACTOR;
248   filter->min_neighbors = DEFAULT_MIN_NEIGHBORS;
249   filter->flags = DEFAULT_FLAGS;
250   filter->min_size_width = DEFAULT_MIN_SIZE_WIDTH;
251   filter->min_size_height = DEFAULT_MIN_SIZE_HEIGHT;
252
253   gst_opencv_video_filter_set_in_place (GST_OPENCV_VIDEO_FILTER_CAST (filter),
254       TRUE);
255 }
256
257 static void
258 gst_face_blur_set_property (GObject * object, guint prop_id,
259     const GValue * value, GParamSpec * pspec)
260 {
261   GstFaceBlur *filter = GST_FACE_BLUR (object);
262
263   switch (prop_id) {
264     case PROP_PROFILE:
265       g_free (filter->profile);
266       if (filter->cvCascade)
267         delete filter->cvCascade;
268       filter->profile = g_value_dup_string (value);
269       filter->cvCascade = gst_face_blur_load_profile (filter, filter->profile);
270       filter->sent_profile_load_failed_msg = FALSE;
271       break;
272     case PROP_SCALE_FACTOR:
273       filter->scale_factor = g_value_get_double (value);
274       break;
275     case PROP_MIN_NEIGHBORS:
276       filter->min_neighbors = g_value_get_int (value);
277       break;
278     case PROP_MIN_SIZE_WIDTH:
279       filter->min_size_width = g_value_get_int (value);
280       break;
281     case PROP_MIN_SIZE_HEIGHT:
282       filter->min_size_height = g_value_get_int (value);
283       break;
284     case PROP_FLAGS:
285       filter->flags = g_value_get_flags (value);
286       break;
287     default:
288       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
289       break;
290   }
291 }
292
293 static void
294 gst_face_blur_get_property (GObject * object, guint prop_id,
295     GValue * value, GParamSpec * pspec)
296 {
297   GstFaceBlur *filter = GST_FACE_BLUR (object);
298
299   switch (prop_id) {
300     case PROP_PROFILE:
301       g_value_set_string (value, filter->profile);
302       break;
303     case PROP_SCALE_FACTOR:
304       g_value_set_double (value, filter->scale_factor);
305       break;
306     case PROP_MIN_NEIGHBORS:
307       g_value_set_int (value, filter->min_neighbors);
308       break;
309     case PROP_MIN_SIZE_WIDTH:
310       g_value_set_int (value, filter->min_size_width);
311       break;
312     case PROP_MIN_SIZE_HEIGHT:
313       g_value_set_int (value, filter->min_size_height);
314       break;
315     case PROP_FLAGS:
316       g_value_set_flags (value, filter->flags);
317       break;
318     default:
319       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
320       break;
321   }
322 }
323
324 static gboolean
325 gst_face_blur_set_caps (GstOpencvVideoFilter * transform,
326     gint in_width, gint in_height, int in_cv_type,
327     gint out_width, gint out_height, int out_cv_type)
328 {
329   GstFaceBlur *filter = GST_FACE_BLUR (transform);
330
331   filter->cvGray.create (Size (in_width, in_height), CV_8UC1);
332
333   return TRUE;
334 }
335
336 static GstFlowReturn
337 gst_face_blur_transform_ip (GstOpencvVideoFilter * transform,
338     GstBuffer * buffer, Mat img)
339 {
340   GstFaceBlur *filter = GST_FACE_BLUR (transform);
341   vector < Rect > faces;
342   unsigned int i;
343
344   if (!filter->cvCascade) {
345     if (filter->profile != NULL
346         && filter->sent_profile_load_failed_msg == FALSE) {
347       GST_ELEMENT_WARNING (filter, RESOURCE, NOT_FOUND,
348           ("Profile %s is missing.", filter->profile),
349           ("missing faceblur profile file %s", filter->profile));
350       filter->sent_profile_load_failed_msg = TRUE;
351     }
352     return GST_FLOW_OK;
353   }
354
355   cvtColor (img, filter->cvGray, COLOR_RGB2GRAY);
356
357   filter->cvCascade->detectMultiScale (filter->cvGray, faces,
358       filter->scale_factor, filter->min_neighbors, filter->flags,
359       Size (filter->min_size_width, filter->min_size_height), Size (0, 0));
360
361   if (!faces.empty ()) {
362
363     for (i = 0; i < faces.size (); ++i) {
364       Rect *r = &faces[i];
365       Mat roi (img, Rect (r->x, r->y, r->width, r->height));
366       blur (roi, roi, Size (11, 11));
367       GaussianBlur (roi, roi, Size (11, 11), 0, 0);
368     }
369   }
370
371   return GST_FLOW_OK;
372 }
373
374 static CascadeClassifier *
375 gst_face_blur_load_profile (GstFaceBlur * filter, gchar * profile)
376 {
377   CascadeClassifier *cascade;
378
379   cascade = new CascadeClassifier (profile);
380   if (cascade->empty ()) {
381     GST_ERROR_OBJECT (filter, "Invalid profile file: %s", profile);
382     delete cascade;
383     return NULL;
384   }
385   return cascade;
386 }
387
388
389 /* entry point to initialize the plug-in
390  * initialize the plug-in itself
391  * register the element factories and other features
392  */
393 gboolean
394 gst_face_blur_plugin_init (GstPlugin * plugin)
395 {
396   /* debug category for filtering log messages */
397   GST_DEBUG_CATEGORY_INIT (gst_face_blur_debug, "faceblur",
398       0, "Blurs faces in images and videos");
399
400   return gst_element_register (plugin, "faceblur", GST_RANK_NONE,
401       GST_TYPE_FACE_BLUR);
402 }