documentation: fixed a heap o' typos
[platform/upstream/gstreamer.git] / ext / opencv / gstskindetect.cpp
1 /*
2  * GStreamer
3  * Copyright (C) 2013 Miguel Casas-Sanchez <miguelecasassanchez@gmail.com>
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Alternatively, the contents of this file may be used under the
24  * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
25  * which case the following provisions apply instead of the ones
26  * mentioned above:
27  *
28  * This library is free software; you can redistribute it and/or
29  * modify it under the terms of the GNU Library General Public
30  * License as published by the Free Software Foundation; either
31  * version 2 of the License, or (at your option) any later version.
32  *
33  * This library is distributed in the hope that it will be useful,
34  * but WITHOUT ANY WARRANTY; without even the implied warranty of
35  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
36  * Library General Public License for more details.
37  *
38  * You should have received a copy of the GNU Library General Public
39  * License along with this library; if not, write to the
40  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
41  * Boston, MA 02110-1301, USA.
42  */
43
44 /**
45  * SECTION:element-skindetect
46  *
47  * Human skin detection on videos and images
48  *
49  * ## Example launch line
50  *
51  * |[
52  * gst-launch-1.0 videotestsrc ! decodebin ! videoconvert ! skindetect ! videoconvert ! xvimagesink
53  * ]|
54  */
55
56 #ifdef HAVE_CONFIG_H
57 #include <config.h>
58 #endif
59
60 #include "gstskindetect.h"
61 #include <opencv2/imgproc.hpp>
62
63 GST_DEBUG_CATEGORY_STATIC (gst_skin_detect_debug);
64 #define GST_CAT_DEFAULT gst_skin_detect_debug
65
66 /* Filter signals and args */
67 enum
68 {
69   /* FILL ME */
70   LAST_SIGNAL
71 };
72
73 enum
74 {
75   PROP_0,
76   PROP_POSTPROCESS,
77   PROP_METHOD,
78   PROP_MASK
79 };
80 typedef enum
81 {
82   HSV,
83   RGB
84 } GstSkindetectMethod;
85
86 #define GST_TYPE_SKIN_DETECT_METHOD (gst_skin_detect_method_get_type ())
87 static GType
88 gst_skin_detect_method_get_type (void)
89 {
90   static GType etype = 0;
91   if (etype == 0) {
92     static const GEnumValue values[] = {
93       {HSV, "Classic HSV thresholding", "hsv"},
94       {RGB, "Normalised-RGB colorspace thresholding", "rgb"},
95       {0, NULL, NULL},
96     };
97     etype = g_enum_register_static ("GstSkindetectMethod", values);
98   }
99   return etype;
100 }
101
102 G_DEFINE_TYPE (GstSkinDetect, gst_skin_detect, GST_TYPE_OPENCV_VIDEO_FILTER);
103 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
104     GST_PAD_SINK,
105     GST_PAD_ALWAYS,
106     GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE ("RGB")));
107
108 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
109     GST_PAD_SRC,
110     GST_PAD_ALWAYS,
111     GST_STATIC_CAPS (GST_VIDEO_CAPS_MAKE ("RGB")));
112
113
114 static void gst_skin_detect_set_property (GObject * object, guint prop_id,
115     const GValue * value, GParamSpec * pspec);
116 static void gst_skin_detect_get_property (GObject * object, guint prop_id,
117     GValue * value, GParamSpec * pspec);
118
119 static GstFlowReturn gst_skin_detect_transform (GstOpencvVideoFilter * filter,
120     GstBuffer * buf, cv::Mat img, GstBuffer * outbuf, cv::Mat outimg);
121
122 static void gst_skin_detect_finalize (GObject * object);
123 static gboolean
124 gst_skin_detect_set_caps (GstOpencvVideoFilter * transform,
125     gint in_width, gint in_height, int in_cv_type,
126     gint out_width, gint out_height, int out_cv_type);
127
128 /* initialize the skindetect's class */
129 static void
130 gst_skin_detect_class_init (GstSkinDetectClass * klass)
131 {
132   GObjectClass *gobject_class;
133   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
134   GstOpencvVideoFilterClass *gstopencvbasefilter_class;
135
136   gobject_class = (GObjectClass *) klass;
137   gstopencvbasefilter_class = (GstOpencvVideoFilterClass *) klass;
138
139   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_skin_detect_finalize);
140   gobject_class->set_property = gst_skin_detect_set_property;
141   gobject_class->get_property = gst_skin_detect_get_property;
142
143   gstopencvbasefilter_class->cv_trans_func = gst_skin_detect_transform;
144
145   g_object_class_install_property (gobject_class, PROP_POSTPROCESS,
146       g_param_spec_boolean ("postprocess", "Postprocess",
147           "Apply opening-closing to skin detection to extract large, significant blobs ",
148           TRUE, (GParamFlags)
149           (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
150   g_object_class_install_property (gobject_class, PROP_METHOD,
151       g_param_spec_enum ("method",
152           "Method to use",
153           "Method to use",
154           GST_TYPE_SKIN_DETECT_METHOD, HSV,
155           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
156
157   gst_element_class_set_static_metadata (element_class,
158       "skindetect",
159       "Filter/Effect/Video",
160       "Performs non-parametric skin detection on input",
161       "Miguel Casas-Sanchez <miguelecasassanchez@gmail.com>");
162
163   gst_element_class_add_static_pad_template (element_class, &src_factory);
164   gst_element_class_add_static_pad_template (element_class, &sink_factory);
165
166   gstopencvbasefilter_class->cv_set_caps = gst_skin_detect_set_caps;
167 }
168
169 /* initialize the new element
170  * instantiate pads and add them to element
171  * set pad callback functions
172  * initialize instance structure
173  */
174 static void
175 gst_skin_detect_init (GstSkinDetect * filter)
176 {
177   filter->postprocess = TRUE;
178   filter->method = HSV;
179
180   gst_opencv_video_filter_set_in_place (GST_OPENCV_VIDEO_FILTER_CAST (filter),
181       FALSE);
182 }
183
184
185 static void
186 gst_skin_detect_set_property (GObject * object, guint prop_id,
187     const GValue * value, GParamSpec * pspec)
188 {
189   GstSkinDetect *filter = GST_SKIN_DETECT (object);
190
191   switch (prop_id) {
192     case PROP_POSTPROCESS:
193       filter->postprocess = g_value_get_boolean (value);
194       break;
195     case PROP_METHOD:
196       filter->method = g_value_get_enum (value);
197       break;
198     default:
199       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
200       break;
201   }
202 }
203
204 static void
205 gst_skin_detect_get_property (GObject * object, guint prop_id,
206     GValue * value, GParamSpec * pspec)
207 {
208   GstSkinDetect *filter = GST_SKIN_DETECT (object);
209
210   switch (prop_id) {
211     case PROP_POSTPROCESS:
212       g_value_set_boolean (value, filter->postprocess);
213       break;
214     case PROP_METHOD:
215       g_value_set_enum (value, filter->method);
216       break;
217     default:
218       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
219       break;
220   }
221 }
222
223 /* GstElement vmethod implementations */
224 /* this function handles the link with other elements */
225 static gboolean
226 gst_skin_detect_set_caps (GstOpencvVideoFilter * transform,
227     gint in_width, gint in_height, int in_cv_type,
228     gint out_width, gint out_height, int out_cv_type)
229 {
230   GstSkinDetect *filter = GST_SKIN_DETECT (transform);
231   cv::Size size = cv::Size (in_width, in_height);
232
233   filter->cvRGB.create (size, CV_8UC3);
234   filter->cvChA.create (size, CV_8UC1);
235   filter->width = in_width;
236   filter->height = in_height;
237
238   filter->cvHSV.create (size, CV_8UC3);
239   filter->cvH.create (size, CV_8UC1);   /*  Hue component. */
240   filter->cvH2.create (size, CV_8UC1);  /*  Hue component, 2nd threshold */
241   filter->cvS.create (size, CV_8UC1);   /*  Saturation component. */
242   filter->cvV.create (size, CV_8UC1);   /*  Brightness component. */
243   filter->cvSkinPixels1.create (size, CV_8UC1); /*  Greyscale output image */
244
245   filter->cvR.create (size, CV_8UC1);   /*  R component. */
246   filter->cvG.create (size, CV_8UC1);   /*  G component. */
247   filter->cvB.create (size, CV_8UC1);   /*  B component. */
248   filter->cvAll.create (size, CV_32FC1);        /*  (R+G+B) component. */
249   filter->cvR2.create (size, CV_32FC1); /*  R component, 32bits */
250   filter->cvRp.create (size, CV_32FC1); /*  R' and >0.4 */
251   filter->cvGp.create (size, CV_32FC1); /*  G' and > 0.28 */
252   filter->cvRp2.create (size, CV_32FC1);        /*  R' <0.6 */
253   filter->cvGp2.create (size, CV_32FC1);        /*  G' <0.4 */
254   filter->cvSkinPixels2.create (size, CV_32FC1);        /*  Greyscale output image. */
255   filter->cvdraft.create (size, CV_8UC1);       /*  Greyscale output image. */
256
257   return TRUE;
258 }
259
260 /* Clean up */
261 static void
262 gst_skin_detect_finalize (GObject * object)
263 {
264   GstSkinDetect *filter = GST_SKIN_DETECT (object);
265
266   filter->cvRGB.release ();
267   filter->cvChA.release ();
268   filter->cvHSV.release ();
269   filter->cvH.release ();
270   filter->cvH2.release ();
271   filter->cvS.release ();
272   filter->cvV.release ();
273   filter->cvSkinPixels1.release ();
274   filter->cvR.release ();
275   filter->cvG.release ();
276   filter->cvB.release ();
277   filter->cvAll.release ();
278   filter->cvR2.release ();
279   filter->cvRp.release ();
280   filter->cvGp.release ();
281   filter->cvRp2.release ();
282   filter->cvGp2.release ();
283   filter->cvdraft.release ();
284   filter->cvSkinPixels2.release ();
285
286   G_OBJECT_CLASS (gst_skin_detect_parent_class)->finalize (object);
287 }
288
289 static GstFlowReturn
290 gst_skin_detect_transform (GstOpencvVideoFilter * base, GstBuffer * buf,
291     cv::Mat img, GstBuffer * outbuf, cv::Mat outimg)
292 {
293   GstSkinDetect *filter = GST_SKIN_DETECT (base);
294
295   std::vector < cv::Mat > channels (3);
296   filter->cvRGB = cv::Mat (img);
297
298   /* SKIN COLOUR BLOB DETECTION */
299   if (HSV == filter->method) {
300     cv::cvtColor (filter->cvRGB, filter->cvHSV, cv::COLOR_RGB2HSV);
301     cv::split (filter->cvHSV, channels);
302     filter->cvH = channels.at (0);
303     filter->cvS = channels.at (1);
304     filter->cvV = channels.at (2);
305
306     /*  Detect which pixels in each of the H, S and V channels are probably skin pixels.
307        Assume that skin has a Hue between 0 to 18 (out of 180), and Saturation above 50, and Brightness above 80. */
308     cv::threshold (filter->cvH, filter->cvH2, 10, UCHAR_MAX, cv::THRESH_BINARY);        /* (hue > 10) */
309     cv::threshold (filter->cvH, filter->cvH, 20, UCHAR_MAX, cv::THRESH_BINARY_INV);     /* (hue < 20) */
310     cv::threshold (filter->cvS, filter->cvS, 48, UCHAR_MAX, cv::THRESH_BINARY); /* (sat > 48) */
311     cv::threshold (filter->cvV, filter->cvV, 80, UCHAR_MAX, cv::THRESH_BINARY); /* (val > 80) */
312
313     /*  erode the HUE to get rid of noise. */
314     cv::erode (filter->cvH, filter->cvH, cv::Mat (), cv::Point (-1, -1), 1);
315
316     /*  Combine all 3 thresholded color components, so that an output pixel will only
317        be white (255) if the H, S and V pixels were also white.
318        imageSkin = (hue > 10) ^ (hue < 20) ^ (sat > 48) ^ (val > 80), where   ^ mean pixels-wise AND */
319     cv::bitwise_and (filter->cvH, filter->cvS, filter->cvSkinPixels1);
320     cv::bitwise_and (filter->cvSkinPixels1, filter->cvH2,
321         filter->cvSkinPixels1);
322     cv::bitwise_and (filter->cvSkinPixels1, filter->cvV, filter->cvSkinPixels1);
323
324     cv::cvtColor (filter->cvSkinPixels1, filter->cvRGB, cv::COLOR_GRAY2RGB);
325   } else if (RGB == filter->method) {
326     cv::split (filter->cvRGB, channels);
327     filter->cvR = channels.at (0);
328     filter->cvG = channels.at (1);
329     filter->cvB = channels.at (2);
330     cv::add (filter->cvR, filter->cvG, filter->cvAll);
331     cv::add (filter->cvB, filter->cvAll, filter->cvAll);        /*  All = R + G + B */
332     cv::divide (filter->cvR, filter->cvAll, filter->cvRp, 1.0, filter->cvRp.type ());   /*  R' = R / ( R + G + B) */
333     cv::divide (filter->cvG, filter->cvAll, filter->cvGp, 1.0, filter->cvGp.type ());   /*  G' = G / ( R + G + B) */
334
335     filter->cvR.convertTo (filter->cvR2, filter->cvR2.type (), 1.0, 0.0);
336     filter->cvGp.copyTo (filter->cvGp2);
337     filter->cvRp.copyTo (filter->cvRp2);
338
339     cv::threshold (filter->cvR2, filter->cvR2, 60, UCHAR_MAX, cv::THRESH_BINARY);       /* (R > 60) */
340     cv::threshold (filter->cvRp, filter->cvRp, 0.42, UCHAR_MAX, cv::THRESH_BINARY);     /* (R'> 0.4) */
341     cv::threshold (filter->cvRp2, filter->cvRp2, 0.6, UCHAR_MAX, cv::THRESH_BINARY_INV);        /* (R'< 0.6) */
342     cv::threshold (filter->cvGp, filter->cvGp, 0.28, UCHAR_MAX, cv::THRESH_BINARY);     /* (G'> 0.28) */
343     cv::threshold (filter->cvGp2, filter->cvGp2, 0.4, UCHAR_MAX, cv::THRESH_BINARY_INV);        /* (G'< 0.4) */
344
345     /*  Combine all 3 thresholded color components, so that an output pixel will only
346        be white (255) if the H, S and V pixels were also white. */
347
348     cv::bitwise_and (filter->cvR2, filter->cvRp, filter->cvSkinPixels2);
349     cv::bitwise_and (filter->cvRp, filter->cvSkinPixels2,
350         filter->cvSkinPixels2);
351     cv::bitwise_and (filter->cvRp2, filter->cvSkinPixels2,
352         filter->cvSkinPixels2);
353     cv::bitwise_and (filter->cvGp, filter->cvSkinPixels2,
354         filter->cvSkinPixels2);
355     cv::bitwise_and (filter->cvGp2, filter->cvSkinPixels2,
356         filter->cvSkinPixels2);
357
358     filter->cvSkinPixels2.convertTo (filter->cvdraft, filter->cvdraft.type (),
359         1.0, 0.0);
360     cv::cvtColor (filter->cvdraft, filter->cvRGB, cv::COLOR_GRAY2RGB);
361   }
362
363   /* After this we have a RGB Black and white image with the skin, in
364      filter->cvRGB. We can postprocess by applying 1 erode-dilate and 1
365      dilate-erode, or alternatively 1 opening-closing all together, with
366      the goal of removing small (spurious) skin spots and creating large
367      connected areas */
368   if (filter->postprocess) {
369     cv::split (filter->cvRGB, channels);
370     filter->cvChA = channels.at (0);
371
372     cv::Mat element =
373         cv::getStructuringElement (cv::MORPH_RECT, cv::Size (3, 3),
374         cv::Point (1, 1));
375     cv::erode (filter->cvChA, filter->cvChA, element, cv::Point (1, 1), 1);
376     cv::dilate (filter->cvChA, filter->cvChA, element, cv::Point (1, 1), 2);
377     cv::erode (filter->cvChA, filter->cvChA, element, cv::Point (1, 1), 1);
378
379     cv::cvtColor (filter->cvChA, filter->cvRGB, cv::COLOR_GRAY2RGB);
380   }
381
382   filter->cvRGB.copyTo (outimg);
383
384   return GST_FLOW_OK;
385 }
386
387 /* entry point to initialize the plug-in
388  * initialize the plug-in itself
389  * register the element factories and other features
390  */
391 gboolean
392 gst_skin_detect_plugin_init (GstPlugin * plugin)
393 {
394   /* debug category for fltering log messages
395    *
396    */
397   GST_DEBUG_CATEGORY_INIT (gst_skin_detect_debug, "skindetect",
398       0, "Performs skin detection on videos and images");
399
400   return gst_element_register (plugin, "skindetect", GST_RANK_NONE,
401       GST_TYPE_SKIN_DETECT);
402 }