1 /*
2  * GStreamer
3  * Copyright (C) <2017> Philippe Renon <philippe_renon@yahoo.fr>
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-cameraundistort
46  *
47  * This element performs camera calibration.
48  *
49  * Once the calibration procedure is done:
50  *  - An event, containing the camera correction parameters, is sent upstream
51  *    and downstream to be consumed by cameraundistort elements.
52  *  - The _settings_ property is set to the camera correction parameters (as
53  *    an opaque string of serialized OpenCV objects).
54  *    The value of this property can later be used to configure a
55  *    cameraundistort element.
56  *  - The element becomes idle and can later be restarted [TODO].
57  *
58  * Based on this tutorial: https://docs.opencv.org/2.4/doc/tutorials/calib3d/camera_calibration/camera_calibration.html
59  *
60  * <refsect2>
61  * <title>Example pipelines</title>
62  * |[
63  * gst-launch-1.0 -v v4l2src ! videoconvert ! cameraundistort ! cameracalibrate | autovideosink
64  * ]| will correct camera distortion once camera calibration is done.
65  * </refsect2>
66  */
67 
68 /*
69  * TODO
70  * - signal when calibration is done
71  * - action signal to start calibration
72  * - do pattern detection asynchronously
73  * - do final calibration computation asynchronously
74  * - use cairo for drawing overlay
75  * - use overlay
76  * - implement settings query
77  * - validate user settings (see validate() in tutorial)
78  * - save complete state (see saveCameraParams() in tutorial)
79  */
80 
81 #ifdef HAVE_CONFIG_H
82 #  include <config.h>
83 #endif
84 
85 #include "gstcameracalibrate.h"
86 
87 #include <opencv2/imgproc.hpp>
88 #include <opencv2/calib3d.hpp>
89 
90 #include <gst/opencv/gstopencvutils.h>
91 
92 #include "camerautils.hpp"
93 #include "cameraevent.hpp"
94 
95 #include <vector>
96 
97 GST_DEBUG_CATEGORY_STATIC (gst_camera_calibrate_debug);
98 #define GST_CAT_DEFAULT gst_camera_calibrate_debug
99 
100 #define DEFAULT_CALIBRATON_PATTERN GST_CAMERA_CALIBRATION_PATTERN_CHESSBOARD
101 #define DEFAULT_BOARD_WIDTH 9
102 #define DEFAULT_BOARD_HEIGHT 6
103 #define DEFAULT_SQUARE_SIZE 50
104 #define DEFAULT_ASPECT_RATIO 1.0
105 #define DEFAULT_CORNER_SUB_PIXEL true
106 #define DEFAULT_ZERO_TANGENT_DISTORTION FALSE
107 #define DEFAULT_CENTER_PRINCIPAL_POINT FALSE
108 #define DEFAULT_USE_FISHEYE FALSE
109 #define DEFAULT_FRAME_COUNT 25
110 #define DEFAULT_DELAY 350
111 #define DEFAULT_SHOW_CORNERS true
112 
113 enum
114 {
115   PROP_0,
116   PROP_CALIBRATON_PATTERN,
117   PROP_BOARD_WIDTH,
118   PROP_BOARD_HEIGHT,
119   PROP_SQUARE_SIZE,
120   PROP_ASPECT_RATIO,
121   PROP_CORNER_SUB_PIXEL,
122   PROP_ZERO_TANGENT_DISTORTION,
123   PROP_CENTER_PRINCIPAL_POINT,
124   PROP_USE_FISHEYE,
125   PROP_FRAME_COUNT,
126   PROP_DELAY,
127   PROP_SHOW_CORNERS,
128   PROP_SETTINGS
129 };
130 
131 enum
132 {
133   DETECTION = 0,
134   CAPTURING = 1,
135   CALIBRATED = 2
136 };
137 
138 #define GST_TYPE_CAMERA_CALIBRATION_PATTERN (camera_calibration_pattern_get_type ())
139 
140 static GType
camera_calibration_pattern_get_type(void)141 camera_calibration_pattern_get_type (void)
142 {
143   static GType camera_calibration_pattern_type = 0;
144   static const GEnumValue camera_calibration_pattern[] = {
145     {GST_CAMERA_CALIBRATION_PATTERN_CHESSBOARD, "Chessboard", "chessboard"},
146     {GST_CAMERA_CALIBRATION_PATTERN_CIRCLES_GRID, "Circle Grids",
147         "circle_grids"},
148     {GST_CAMERA_CALIBRATION_PATTERN_ASYMMETRIC_CIRCLES_GRID,
149         "Asymmetric Circle Grids", "asymmetric_circle_grids"},
150     {0, NULL, NULL},
151   };
152 
153   if (!camera_calibration_pattern_type) {
154     camera_calibration_pattern_type =
155         g_enum_register_static ("GstCameraCalibrationPattern",
156         camera_calibration_pattern);
157   }
158   return camera_calibration_pattern_type;
159 }
160 
161 G_DEFINE_TYPE (GstCameraCalibrate, gst_camera_calibrate,
162     GST_TYPE_OPENCV_VIDEO_FILTER);
163 
164 static void gst_camera_calibrate_dispose (GObject * object);
165 static void gst_camera_calibrate_set_property (GObject * object, guint prop_id,
166     const GValue * value, GParamSpec * pspec);
167 static void gst_camera_calibrate_get_property (GObject * object, guint prop_id,
168     GValue * value, GParamSpec * pspec);
169 
170 static GstFlowReturn
171 gst_camera_calibrate_transform_frame_ip (GstOpencvVideoFilter * cvfilter,
172     GstBuffer * frame, cv::Mat img);
173 
174 /* clean up */
175 static void
gst_camera_calibrate_finalize(GObject * obj)176 gst_camera_calibrate_finalize (GObject * obj)
177 {
178   G_OBJECT_CLASS (gst_camera_calibrate_parent_class)->finalize (obj);
179 }
180 
181 /* initialize the cameracalibration's class */
182 static void
gst_camera_calibrate_class_init(GstCameraCalibrateClass * klass)183 gst_camera_calibrate_class_init (GstCameraCalibrateClass * klass)
184 {
185   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
186   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
187   GstOpencvVideoFilterClass *opencvfilter_class =
188       GST_OPENCV_VIDEO_FILTER_CLASS (klass);
189   GstCaps *caps;
190   GstPadTemplate *templ;
191 
192   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_camera_calibrate_finalize);
193   gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_camera_calibrate_dispose);
194   gobject_class->set_property = gst_camera_calibrate_set_property;
195   gobject_class->get_property = gst_camera_calibrate_get_property;
196 
197   opencvfilter_class->cv_trans_ip_func =
198       gst_camera_calibrate_transform_frame_ip;
199 
200   g_object_class_install_property (gobject_class, PROP_CALIBRATON_PATTERN,
201       g_param_spec_enum ("pattern", "Calibration Pattern",
202           "One of the chessboard, circles, or asymmetric circle pattern",
203           GST_TYPE_CAMERA_CALIBRATION_PATTERN, DEFAULT_CALIBRATON_PATTERN,
204           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
205 
206   g_object_class_install_property (gobject_class, PROP_BOARD_WIDTH,
207       g_param_spec_int ("board-width", "Board Width",
208           "The board width in number of items",
209           1, G_MAXINT, DEFAULT_BOARD_WIDTH,
210           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
211 
212   g_object_class_install_property (gobject_class, PROP_BOARD_HEIGHT,
213       g_param_spec_int ("board-height", "Board Height",
214           "The board height in number of items",
215           1, G_MAXINT, DEFAULT_BOARD_WIDTH,
216           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
217 
218   g_object_class_install_property (gobject_class, PROP_SQUARE_SIZE,
219       g_param_spec_float ("square-size", "Square Size",
220           "The size of a square in your defined unit (point, millimeter, etc.)",
221           0.0, G_MAXFLOAT, DEFAULT_SQUARE_SIZE,
222           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
223 
224   g_object_class_install_property (gobject_class, PROP_ASPECT_RATIO,
225       g_param_spec_float ("aspect-ratio", "Aspect Ratio",
226           "The aspect ratio",
227           0.0, G_MAXFLOAT, DEFAULT_ASPECT_RATIO,
228           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
229 
230   g_object_class_install_property (gobject_class, PROP_CORNER_SUB_PIXEL,
231       g_param_spec_boolean ("corner-sub-pixel", "Corner Sub Pixel",
232           "Improve corner detection accuracy for chessboard",
233           DEFAULT_CORNER_SUB_PIXEL,
234           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
235 
236   g_object_class_install_property (gobject_class, PROP_ZERO_TANGENT_DISTORTION,
237       g_param_spec_boolean ("zero-tangent-distorsion",
238           "Zero Tangent Distorsion", "Assume zero tangential distortion",
239           DEFAULT_ZERO_TANGENT_DISTORTION,
240           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
241 
242   g_object_class_install_property (gobject_class, PROP_CENTER_PRINCIPAL_POINT,
243       g_param_spec_boolean ("center-principal-point", "Center Principal Point",
244           "Fix the principal point at the center",
245           DEFAULT_CENTER_PRINCIPAL_POINT,
246           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
247 
248   g_object_class_install_property (gobject_class, PROP_USE_FISHEYE,
249       g_param_spec_boolean ("use-fisheye", "Use Fisheye",
250           "Use fisheye camera model for calibration",
251           DEFAULT_USE_FISHEYE,
252           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
253 
254   g_object_class_install_property (gobject_class, PROP_DELAY,
255       g_param_spec_int ("delay", "Delay",
256           "Sampling periodicity in ms", 0, G_MAXINT,
257           DEFAULT_DELAY,
258           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
259 
260   g_object_class_install_property (gobject_class, PROP_FRAME_COUNT,
261       g_param_spec_int ("frame-count", "Frame Count",
262           "The number of frames to use from the input for calibration", 1,
263           G_MAXINT, DEFAULT_FRAME_COUNT,
264           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
265 
266   g_object_class_install_property (gobject_class, PROP_SHOW_CORNERS,
267       g_param_spec_boolean ("show-corners", "Show Corners",
268           "Show corners",
269           DEFAULT_SHOW_CORNERS,
270           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
271 
272   g_object_class_install_property (gobject_class, PROP_SETTINGS,
273       g_param_spec_string ("settings", "Settings",
274           "Camera correction parameters (opaque string of serialized OpenCV objects)",
275           NULL, (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
276 
277   gst_element_class_set_static_metadata (element_class,
278       "cameracalibrate",
279       "Filter/Effect/Video",
280       "Performs camera calibration",
281       "Philippe Renon <philippe_renon@yahoo.fr>");
282 
283   /* add sink and source pad templates */
284   caps = gst_opencv_caps_from_cv_image_type (CV_8UC4);
285   gst_caps_append (caps, gst_opencv_caps_from_cv_image_type (CV_8UC3));
286   gst_caps_append (caps, gst_opencv_caps_from_cv_image_type (CV_8UC1));
287   templ = gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
288       gst_caps_ref (caps));
289   gst_element_class_add_pad_template (element_class, templ);
290   templ = gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS, caps);
291   gst_element_class_add_pad_template (element_class, templ);
292 }
293 
294 /* initialize the new element
295  * initialize instance structure
296  */
297 static void
gst_camera_calibrate_init(GstCameraCalibrate * calib)298 gst_camera_calibrate_init (GstCameraCalibrate * calib)
299 {
300   calib->calibrationPattern = DEFAULT_CALIBRATON_PATTERN;
301   calib->boardSize.width = DEFAULT_BOARD_WIDTH;
302   calib->boardSize.height = DEFAULT_BOARD_HEIGHT;
303   calib->squareSize = DEFAULT_SQUARE_SIZE;
304   calib->aspectRatio = DEFAULT_ASPECT_RATIO;
305   calib->cornerSubPix = DEFAULT_CORNER_SUB_PIXEL;
306   calib->calibZeroTangentDist = DEFAULT_ZERO_TANGENT_DISTORTION;
307   calib->calibFixPrincipalPoint = DEFAULT_CENTER_PRINCIPAL_POINT;
308   calib->useFisheye = DEFAULT_USE_FISHEYE;
309   calib->nrFrames = DEFAULT_FRAME_COUNT;
310   calib->delay = DEFAULT_DELAY;
311   calib->showCorners = DEFAULT_SHOW_CORNERS;
312 
313   calib->flags = cv::CALIB_FIX_K4 | cv::CALIB_FIX_K5;
314   if (calib->calibFixPrincipalPoint)
315     calib->flags |= cv::CALIB_FIX_PRINCIPAL_POINT;
316   if (calib->calibZeroTangentDist)
317     calib->flags |= cv::CALIB_ZERO_TANGENT_DIST;
318   if (calib->aspectRatio)
319     calib->flags |= cv::CALIB_FIX_ASPECT_RATIO;
320 
321   if (calib->useFisheye) {
322     /* the fisheye model has its own enum, so overwrite the flags */
323     calib->flags =
324         cv::fisheye::CALIB_FIX_SKEW | cv::fisheye::CALIB_RECOMPUTE_EXTRINSIC |
325         /*cv::fisheye::CALIB_FIX_K1 | */
326         cv::fisheye::CALIB_FIX_K2 | cv::fisheye::CALIB_FIX_K3 | cv::
327         fisheye::CALIB_FIX_K4;
328   }
329 
330   calib->mode = CAPTURING;      //DETECTION;
331   calib->prevTimestamp = 0;
332 
333   calib->imagePoints.clear ();
334   calib->cameraMatrix = 0;
335   calib->distCoeffs = 0;
336 
337   calib->settings = NULL;
338 
339   gst_opencv_video_filter_set_in_place (GST_OPENCV_VIDEO_FILTER_CAST (calib),
340       TRUE);
341 }
342 
343 static void
gst_camera_calibrate_dispose(GObject * object)344 gst_camera_calibrate_dispose (GObject * object)
345 {
346   GstCameraCalibrate *calib = GST_CAMERA_CALIBRATE (object);
347 
348   g_free (calib->settings);
349   calib->settings = NULL;
350 
351   G_OBJECT_CLASS (gst_camera_calibrate_parent_class)->dispose (object);
352 }
353 
354 static void
gst_camera_calibrate_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)355 gst_camera_calibrate_set_property (GObject * object, guint prop_id,
356     const GValue * value, GParamSpec * pspec)
357 {
358   GstCameraCalibrate *calib = GST_CAMERA_CALIBRATE (object);
359 
360   switch (prop_id) {
361     case PROP_CALIBRATON_PATTERN:
362       calib->calibrationPattern = g_value_get_enum (value);
363       break;
364     case PROP_BOARD_WIDTH:
365       calib->boardSize.width = g_value_get_int (value);
366       break;
367     case PROP_BOARD_HEIGHT:
368       calib->boardSize.height = g_value_get_int (value);
369       break;
370     case PROP_SQUARE_SIZE:
371       calib->squareSize = g_value_get_float (value);
372       break;
373     case PROP_ASPECT_RATIO:
374       calib->aspectRatio = g_value_get_float (value);
375       break;
376     case PROP_CORNER_SUB_PIXEL:
377       calib->cornerSubPix = g_value_get_boolean (value);
378       break;
379     case PROP_ZERO_TANGENT_DISTORTION:
380       calib->calibZeroTangentDist = g_value_get_boolean (value);
381       break;
382     case PROP_CENTER_PRINCIPAL_POINT:
383       calib->calibFixPrincipalPoint = g_value_get_boolean (value);
384       break;
385     case PROP_USE_FISHEYE:
386       calib->useFisheye = g_value_get_boolean (value);
387       break;
388     case PROP_FRAME_COUNT:
389       calib->nrFrames = g_value_get_int (value);
390       break;
391     case PROP_DELAY:
392       calib->delay = g_value_get_int (value);
393       break;
394     case PROP_SHOW_CORNERS:
395       calib->showCorners = g_value_get_boolean (value);
396       break;
397     default:
398       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
399       break;
400   }
401 }
402 
403 static void
gst_camera_calibrate_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)404 gst_camera_calibrate_get_property (GObject * object, guint prop_id,
405     GValue * value, GParamSpec * pspec)
406 {
407   GstCameraCalibrate *calib = GST_CAMERA_CALIBRATE (object);
408 
409   switch (prop_id) {
410     case PROP_CALIBRATON_PATTERN:
411       g_value_set_enum (value, calib->calibrationPattern);
412       break;
413     case PROP_BOARD_WIDTH:
414       g_value_set_int (value, calib->boardSize.width);
415       break;
416     case PROP_BOARD_HEIGHT:
417       g_value_set_int (value, calib->boardSize.height);
418       break;
419     case PROP_SQUARE_SIZE:
420       g_value_set_float (value, calib->squareSize);
421       break;
422     case PROP_ASPECT_RATIO:
423       g_value_set_float (value, calib->aspectRatio);
424       break;
425     case PROP_CORNER_SUB_PIXEL:
426       g_value_set_boolean (value, calib->cornerSubPix);
427       break;
428     case PROP_ZERO_TANGENT_DISTORTION:
429       g_value_set_boolean (value, calib->calibZeroTangentDist);
430       break;
431     case PROP_CENTER_PRINCIPAL_POINT:
432       g_value_set_boolean (value, calib->calibFixPrincipalPoint);
433       break;
434     case PROP_USE_FISHEYE:
435       g_value_set_boolean (value, calib->useFisheye);
436       break;
437     case PROP_FRAME_COUNT:
438       g_value_set_int (value, calib->nrFrames);
439       break;
440     case PROP_DELAY:
441       g_value_set_int (value, calib->delay);
442       break;
443     case PROP_SHOW_CORNERS:
444       g_value_set_boolean (value, calib->showCorners);
445       break;
446     case PROP_SETTINGS:
447       g_value_set_string (value, calib->settings);
448       break;
449     default:
450       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
451       break;
452   }
453 }
454 
455 void camera_calibrate_run (GstCameraCalibrate * calib, cv::Mat img);
456 
457 /*
458  * Performs the camera calibration
459  */
460 static GstFlowReturn
gst_camera_calibrate_transform_frame_ip(GstOpencvVideoFilter * cvfilter,G_GNUC_UNUSED GstBuffer * frame,cv::Mat img)461 gst_camera_calibrate_transform_frame_ip (GstOpencvVideoFilter * cvfilter,
462     G_GNUC_UNUSED GstBuffer * frame, cv::Mat img)
463 {
464   GstCameraCalibrate *calib = GST_CAMERA_CALIBRATE (cvfilter);
465 
466   camera_calibrate_run (calib, img);
467 
468   return GST_FLOW_OK;
469 }
470 
471 bool camera_calibrate_calibrate (GstCameraCalibrate * calib,
472     cv::Size imageSize, cv::Mat & cameraMatrix, cv::Mat & distCoeffs,
473     std::vector < std::vector < cv::Point2f > >imagePoints);
474 
475 void
camera_calibrate_run(GstCameraCalibrate * calib,cv::Mat img)476 camera_calibrate_run (GstCameraCalibrate * calib, cv::Mat img)
477 {
478 
479   // For camera only take new samples after delay time
480   if (calib->mode == CAPTURING) {
481     // get_input
482     cv::Size imageSize = img.size ();
483 
484     /* find_pattern
485      * FIXME find ways to reduce CPU usage
486      * don't do it on all frames ? will it help ? corner display will be affected.
487      * in a separate frame?
488      * in a separate element that gets composited back into the main stream
489      * (video is tee-d into it and can then be decimated, scaled, etc..) */
490 
491     std::vector < cv::Point2f > pointBuf;
492     bool found;
493     int chessBoardFlags =
494         cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_NORMALIZE_IMAGE;
495 
496     if (!calib->useFisheye) {
497       /* fast check erroneously fails with high distortions like fisheye */
498       chessBoardFlags |= cv::CALIB_CB_FAST_CHECK;
499     }
500 
501     /* Find feature points on the input format */
502     switch (calib->calibrationPattern) {
503       case GST_CAMERA_CALIBRATION_PATTERN_CHESSBOARD:
504         found =
505             cv::findChessboardCorners (img, calib->boardSize, pointBuf,
506             chessBoardFlags);
507         break;
508       case GST_CAMERA_CALIBRATION_PATTERN_CIRCLES_GRID:
509         found = cv::findCirclesGrid (img, calib->boardSize, pointBuf);
510         break;
511       case GST_CAMERA_CALIBRATION_PATTERN_ASYMMETRIC_CIRCLES_GRID:
512         found =
513             cv::findCirclesGrid (img, calib->boardSize, pointBuf,
514             cv::CALIB_CB_ASYMMETRIC_GRID);
515         break;
516       default:
517         found = FALSE;
518         break;
519     }
520 
521     bool blinkOutput = FALSE;
522     if (found) {
523       /* improve the found corners' coordinate accuracy for chessboard */
524       if (calib->calibrationPattern == GST_CAMERA_CALIBRATION_PATTERN_CHESSBOARD
525           && calib->cornerSubPix) {
526         /* FIXME findChessboardCorners and alike do a cv::COLOR_BGR2GRAY (and a histogram balance)
527          * the color convert should be done once (if needed) and shared
528          * FIXME keep viewGray around to avoid reallocating it each time... */
529         cv::Mat viewGray;
530         cv::cvtColor (img, viewGray, cv::COLOR_BGR2GRAY);
531         cv::cornerSubPix (viewGray, pointBuf, cv::Size (11, 11), cv::Size (-1,
532                 -1),
533             cv::TermCriteria (cv::TermCriteria::EPS + cv::TermCriteria::COUNT,
534                 30, 0.1));
535       }
536 
537       /* take new samples after delay time */
538       if ((calib->mode == CAPTURING)
539           && ((clock () - calib->prevTimestamp) >
540               calib->delay * 1e-3 * CLOCKS_PER_SEC)) {
541         calib->imagePoints.push_back (pointBuf);
542         calib->prevTimestamp = clock ();
543         blinkOutput = true;
544       }
545 
546       /* draw the corners */
547       if (calib->showCorners) {
548         cv::drawChessboardCorners (img, calib->boardSize, cv::Mat (pointBuf),
549             found);
550       }
551     }
552 
553     /* if got enough frames then stop calibration and show result */
554     if (calib->mode == CAPTURING
555         && calib->imagePoints.size () >= (size_t) calib->nrFrames) {
556 
557       if (camera_calibrate_calibrate (calib, imageSize, calib->cameraMatrix,
558               calib->distCoeffs, calib->imagePoints)) {
559         calib->mode = CALIBRATED;
560 
561         GstPad *sink_pad = GST_BASE_TRANSFORM_SINK_PAD (calib);
562         GstPad *src_pad = GST_BASE_TRANSFORM_SRC_PAD (calib);
563         GstEvent *sink_event;
564         GstEvent *src_event;
565 
566         /* set settings property */
567         g_free (calib->settings);
568         calib->settings =
569             camera_serialize_undistort_settings (calib->cameraMatrix,
570             calib->distCoeffs);
571 
572         /* create calibrated event and send upstream and downstream */
573         sink_event = gst_camera_event_new_calibrated (calib->settings);
574         GST_LOG_OBJECT (sink_pad, "Sending upstream event %s.",
575             GST_EVENT_TYPE_NAME (sink_event));
576         if (!gst_pad_push_event (sink_pad, sink_event)) {
577           GST_WARNING_OBJECT (sink_pad,
578               "Sending upstream event %p (%s) failed.", sink_event,
579               GST_EVENT_TYPE_NAME (sink_event));
580         }
581 
582         src_event = gst_camera_event_new_calibrated (calib->settings);
583         GST_LOG_OBJECT (src_pad, "Sending downstream event %s.",
584             GST_EVENT_TYPE_NAME (src_event));
585         if (!gst_pad_push_event (src_pad, src_event)) {
586           GST_WARNING_OBJECT (src_pad,
587               "Sending downstream event %p (%s) failed.", src_event,
588               GST_EVENT_TYPE_NAME (src_event));
589         }
590       } else {
591         /* failed to calibrate, go back to detection mode */
592         calib->mode = DETECTION;
593       }
594     }
595 
596     if (calib->mode == CAPTURING && blinkOutput) {
597       bitwise_not (img, img);
598     }
599 
600   }
601 
602   /* output text */
603   /* FIXME ll additional rendering (text, corners, ...) should be done with
604    * cairo or another gst framework.
605    * this will relax the conditions on the input format (RBG only at the moment).
606    * the calibration itself accepts more formats... */
607 
608   std::string msg = (calib->mode == CAPTURING) ? "100/100" :
609       (calib->mode == CALIBRATED) ? "Calibrated" : "Waiting...";
610   int baseLine = 0;
611   cv::Size textSize = cv::getTextSize (msg, 1, 1, 1, &baseLine);
612   cv::Point textOrigin (img.cols - 2 * textSize.width - 10,
613       img.rows - 2 * baseLine - 10);
614 
615   if (calib->mode == CAPTURING) {
616     msg =
617         cv::format ("%d/%d", (int) calib->imagePoints.size (), calib->nrFrames);
618   }
619 
620   const cv::Scalar RED (0, 0, 255);
621   const cv::Scalar GREEN (0, 255, 0);
622 
623   cv::putText (img, msg, textOrigin, 1, 1,
624       calib->mode == CALIBRATED ? GREEN : RED);
625 }
626 
627 static double
camera_calibrate_calc_reprojection_errors(const std::vector<std::vector<cv::Point3f>> & objectPoints,const std::vector<std::vector<cv::Point2f>> & imagePoints,const std::vector<cv::Mat> & rvecs,const std::vector<cv::Mat> & tvecs,const cv::Mat & cameraMatrix,const cv::Mat & distCoeffs,std::vector<float> & perViewErrors,bool fisheye)628 camera_calibrate_calc_reprojection_errors (const std::vector < std::vector <
629     cv::Point3f > >&objectPoints,
630     const std::vector < std::vector < cv::Point2f > >&imagePoints,
631     const std::vector < cv::Mat > &rvecs, const std::vector < cv::Mat > &tvecs,
632     const cv::Mat & cameraMatrix, const cv::Mat & distCoeffs,
633     std::vector < float >&perViewErrors, bool fisheye)
634 {
635   std::vector < cv::Point2f > imagePoints2;
636   size_t totalPoints = 0;
637   double totalErr = 0, err;
638   perViewErrors.resize (objectPoints.size ());
639 
640   for (size_t i = 0; i < objectPoints.size (); ++i) {
641     if (fisheye) {
642       cv::fisheye::projectPoints (objectPoints[i], imagePoints2,
643           rvecs[i], tvecs[i], cameraMatrix, distCoeffs);
644     } else {
645       cv::projectPoints (objectPoints[i], rvecs[i], tvecs[i],
646           cameraMatrix, distCoeffs, imagePoints2);
647     }
648     err = cv::norm (imagePoints[i], imagePoints2, cv::NORM_L2);
649 
650     size_t n = objectPoints[i].size ();
651     perViewErrors[i] = (float) std::sqrt (err * err / n);
652     totalErr += err * err;
653     totalPoints += n;
654   }
655 
656   return std::sqrt (totalErr / totalPoints);
657 }
658 
659 static void
camera_calibrate_calc_corners(cv::Size boardSize,float squareSize,std::vector<cv::Point3f> & corners,gint patternType)660 camera_calibrate_calc_corners (cv::Size boardSize, float squareSize,
661     std::vector < cv::Point3f > &corners, gint patternType /*= CHESSBOARD*/ )
662 {
663   corners.clear ();
664 
665   switch (patternType) {
666     case GST_CAMERA_CALIBRATION_PATTERN_CHESSBOARD:
667     case GST_CAMERA_CALIBRATION_PATTERN_CIRCLES_GRID:
668       for (int i = 0; i < boardSize.height; ++i)
669         for (int j = 0; j < boardSize.width; ++j)
670           corners.push_back (cv::Point3f (j * squareSize, i * squareSize, 0));
671       break;
672     case GST_CAMERA_CALIBRATION_PATTERN_ASYMMETRIC_CIRCLES_GRID:
673       for (int i = 0; i < boardSize.height; i++)
674         for (int j = 0; j < boardSize.width; j++)
675           corners.push_back (cv::Point3f ((2 * j + i % 2) * squareSize,
676                   i * squareSize, 0));
677       break;
678     default:
679       break;
680   }
681 }
682 
683 static bool
camera_calibrate_calibrate_full(GstCameraCalibrate * calib,cv::Size & imageSize,cv::Mat & cameraMatrix,cv::Mat & distCoeffs,std::vector<std::vector<cv::Point2f>> imagePoints,std::vector<cv::Mat> & rvecs,std::vector<cv::Mat> & tvecs,std::vector<float> & reprojErrs,double & totalAvgErr)684 camera_calibrate_calibrate_full (GstCameraCalibrate * calib,
685     cv::Size & imageSize, cv::Mat & cameraMatrix, cv::Mat & distCoeffs,
686     std::vector < std::vector < cv::Point2f > >imagePoints,
687     std::vector < cv::Mat > &rvecs, std::vector < cv::Mat > &tvecs,
688     std::vector < float >&reprojErrs, double &totalAvgErr)
689 {
690   cameraMatrix = cv::Mat::eye (3, 3, CV_64F);
691   if (calib->flags & cv::CALIB_FIX_ASPECT_RATIO) {
692     cameraMatrix.at < double >(0, 0) = calib->aspectRatio;
693   }
694   if (calib->useFisheye) {
695     distCoeffs = cv::Mat::zeros (4, 1, CV_64F);
696   } else {
697     distCoeffs = cv::Mat::zeros (8, 1, CV_64F);
698   }
699 
700   std::vector < std::vector < cv::Point3f > >objectPoints (1);
701   camera_calibrate_calc_corners (calib->boardSize, calib->squareSize,
702       objectPoints[0], calib->calibrationPattern);
703 
704   objectPoints.resize (imagePoints.size (), objectPoints[0]);
705 
706   /* Find intrinsic and extrinsic camera parameters */
707   double rms;
708 
709   if (calib->useFisheye) {
710     cv::Mat _rvecs, _tvecs;
711     rms = cv::fisheye::calibrate (objectPoints, imagePoints, imageSize,
712         cameraMatrix, distCoeffs, _rvecs, _tvecs, calib->flags);
713 
714     rvecs.reserve (_rvecs.rows);
715     tvecs.reserve (_tvecs.rows);
716     for (int i = 0; i < int (objectPoints.size ()); i++) {
717       rvecs.push_back (_rvecs.row (i));
718       tvecs.push_back (_tvecs.row (i));
719     }
720   } else {
721     rms = cv::calibrateCamera (objectPoints, imagePoints, imageSize,
722         cameraMatrix, distCoeffs, rvecs, tvecs, calib->flags);
723   }
724 
725   GST_LOG_OBJECT (calib,
726       "Re-projection error reported by calibrateCamera: %f", rms);
727 
728   bool ok = checkRange (cameraMatrix) && checkRange (distCoeffs);
729 
730   totalAvgErr =
731       camera_calibrate_calc_reprojection_errors (objectPoints, imagePoints,
732       rvecs, tvecs, cameraMatrix, distCoeffs, reprojErrs, calib->useFisheye);
733 
734   return ok;
735 }
736 
737 bool
camera_calibrate_calibrate(GstCameraCalibrate * calib,cv::Size imageSize,cv::Mat & cameraMatrix,cv::Mat & distCoeffs,std::vector<std::vector<cv::Point2f>> imagePoints)738 camera_calibrate_calibrate (GstCameraCalibrate * calib,
739     cv::Size imageSize, cv::Mat & cameraMatrix, cv::Mat & distCoeffs,
740     std::vector < std::vector < cv::Point2f > >imagePoints)
741 {
742   std::vector < cv::Mat > rvecs, tvecs;
743   std::vector < float >reprojErrs;
744   double totalAvgErr = 0;
745 
746   bool ok = camera_calibrate_calibrate_full (calib,
747       imageSize, cameraMatrix, distCoeffs, imagePoints,
748       rvecs, tvecs, reprojErrs, totalAvgErr);
749   GST_LOG_OBJECT (calib, (ok ? "Calibration succeeded" : "Calibration failed"));
750   /* + ". avg re projection error = " + totalAvgErr); */
751 
752   return ok;
753 }
754 
755 /* entry point to initialize the plug-in
756  * initialize the plug-in itself
757  * register the element factories and other features
758  */
759 gboolean
gst_camera_calibrate_plugin_init(GstPlugin * plugin)760 gst_camera_calibrate_plugin_init (GstPlugin * plugin)
761 {
762   /* debug category for filtering log messages */
763   GST_DEBUG_CATEGORY_INIT (gst_camera_calibrate_debug, "cameracalibrate",
764       0, "Performs camera calibration");
765 
766   return gst_element_register (plugin, "cameracalibrate", GST_RANK_NONE,
767       GST_TYPE_CAMERA_CALIBRATE);
768 }
769