2014-07-22 22:22:59 +00:00
/*
2016-07-17 21:57:10 -04:00
Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
2014-08-11 17:00:55 +00:00
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
2014-07-22 22:22:59 +00:00
#include "rtabmap/gui/CalibrationDialog.h"
#include "ui_calibrationDialog.h"
2026-07-29 22:48:39 -07:00
#include <algorithm>
2014-07-22 22:22:59 +00:00
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
2026-07-29 22:48:39 -07:00
#if CV_MAJOR_VERSION >= 5
#include <opencv2/calib.hpp>
#include <opencv2/geometry.hpp>
#else
2014-07-22 22:22:59 +00:00
#include <opencv2/calib3d/calib3d.hpp>
2018-09-18 23:03:40 -04:00
#endif
2014-07-22 22:22:59 +00:00
#include <opencv2/highgui/highgui.hpp>
2026-07-29 22:48:39 -07:00
#if (CV_MAJOR_VERSION > 2 and CV_MAJOR_VERSION < 5) or (CV_MAJOR_VERSION == 2 and (CV_MINOR_VERSION >4 or (CV_MINOR_VERSION == 4 and CV_SUBMINOR_VERSION >=10)))
2020-04-30 00:57:47 -04:00
#include <rtabmap/core/stereo/stereoRectifyFisheye.h>
2019-05-09 19:20:26 -04:00
#endif
2014-07-22 22:22:59 +00:00
2015-03-16 19:51:22 +00:00
#include <QFileDialog>
#include <QMessageBox>
2015-04-06 00:28:04 -04:00
#include <QCloseEvent>
2024-05-31 10:28:14 -07:00
#include <QDateTime>
2024-06-30 17:11:37 -07:00
#include <QTextStream>
#include <QtGlobal>
#if QT_VERSION >= QT_VERSION_CHECK(5,14,0)
#define ENDL Qt::endl
#else
#define ENDL endl
#endif
2015-01-19 16:14:49 -05:00
2024-04-14 19:06:04 -07:00
#include <rtabmap/core/SensorEvent.h>
2015-08-25 10:32:27 -04:00
#include <rtabmap/utilite/UCv2Qt.h>
2014-07-22 22:22:59 +00:00
#include <rtabmap/utilite/ULogger.h>
2024-06-30 19:11:14 -07:00
#ifdef HAVE_CHARUCO
2024-06-30 17:11:37 -07:00
#define kArucoDictNameSize 21
static const char * kArucoDictNames [ kArucoDictNameSize ] = {
"4X4_50" ,
"4X4_100" ,
"4X4_250" ,
"4X4_1000" ,
"5X5_50" ,
"5X5_100" ,
"5X5_250" ,
"5X5_1000" ,
"6X6_50" ,
"6X6_100" ,
"6X6_250" ,
"6X6_1000" ,
"7X7_50" ,
"7X7_100" ,
"7X7_250" ,
"7X7_1000" ,
"ARUCO_ORIGINAL" ,
"APRILTAG_16h5" ,
"APRILTAG_25h9" ,
"APRILTAG_36h10" ,
"APRILTAG_36h11"
};
2024-06-30 19:11:14 -07:00
#endif
2024-06-30 17:11:37 -07:00
2014-07-22 22:22:59 +00:00
namespace rtabmap {
2024-06-30 17:11:37 -07:00
#define COUNT_MIN 70
2014-07-22 22:22:59 +00:00
2015-05-05 19:43:25 -04:00
CalibrationDialog :: CalibrationDialog ( bool stereo , const QString & savingDirectory , bool switchImages , QWidget * parent ) :
2014-07-22 22:22:59 +00:00
QDialog ( parent ),
2015-04-05 16:42:41 -04:00
stereo_ ( stereo ),
2016-09-13 18:26:18 -04:00
leftSuffix_ ( "left" ),
rightSuffix_ ( "right" ),
2015-04-06 00:28:04 -04:00
savingDirectory_ ( savingDirectory ),
processingData_ ( false ),
2024-05-31 10:28:14 -07:00
savedCalibration_ ( false ),
currentId_ ( 0 )
2014-07-22 22:22:59 +00:00
{
2015-04-05 16:42:41 -04:00
imagePoints_ . resize ( 2 );
2024-06-30 17:11:37 -07:00
objectPoints_ . resize ( 2 );
2015-04-05 16:42:41 -04:00
imageParams_ . resize ( 2 );
2024-05-31 10:28:14 -07:00
imageIds_ . resize ( 2 );
2015-04-05 16:42:41 -04:00
imageSize_ . resize ( 2 );
2015-04-07 23:42:38 -04:00
stereoImagePoints_ . resize ( 2 );
models_ . resize ( 2 );
2015-04-05 16:42:41 -04:00
2015-04-08 12:23:10 -04:00
minIrs_ . resize ( 2 );
maxIrs_ . resize ( 2 );
minIrs_ [ 0 ] = 0x0000 ;
maxIrs_ [ 0 ] = 0x7fff ;
minIrs_ [ 1 ] = 0x0000 ;
maxIrs_ [ 1 ] = 0x7fff ;
2014-07-22 22:22:59 +00:00
qRegisterMetaType < cv :: Mat > ( "cv::Mat" );
ui_ = new Ui_calibrationDialog ();
ui_ -> setupUi ( this );
2024-06-30 17:11:37 -07:00
connect ( ui_ -> toolButton_generateBoard , SIGNAL ( clicked ()), this , SLOT ( generateBoard ()));
2014-07-22 22:22:59 +00:00
connect ( ui_ -> pushButton_calibrate , SIGNAL ( clicked ()), this , SLOT ( calibrate ()));
connect ( ui_ -> pushButton_restart , SIGNAL ( clicked ()), this , SLOT ( restart ()));
2015-01-19 16:14:49 -05:00
connect ( ui_ -> pushButton_save , SIGNAL ( clicked ()), this , SLOT ( save ()));
2015-04-08 12:23:10 -04:00
connect ( ui_ -> checkBox_switchImages , SIGNAL ( stateChanged ( int )), this , SLOT ( restart ()));
2016-01-19 17:43:33 -05:00
connect ( ui_ -> checkBox_unlock , SIGNAL ( stateChanged ( int )), SLOT ( unlock ()));
2014-07-26 04:36:00 +00:00
2024-06-30 17:11:37 -07:00
connect ( ui_ -> comboBox_board_type , SIGNAL ( currentIndexChanged ( int )), this , SLOT ( setBoardType ( int )));
connect ( ui_ -> comboBox_marker_dictionary , SIGNAL ( currentIndexChanged ( int )), this , SLOT ( setMarkerDictionary ( int )));
2014-07-26 04:36:00 +00:00
connect ( ui_ -> spinBox_boardWidth , SIGNAL ( valueChanged ( int )), this , SLOT ( setBoardWidth ( int )));
connect ( ui_ -> spinBox_boardHeight , SIGNAL ( valueChanged ( int )), this , SLOT ( setBoardHeight ( int )));
connect ( ui_ -> doubleSpinBox_squareSize , SIGNAL ( valueChanged ( double )), this , SLOT ( setSquareSize ( double )));
2024-06-30 17:11:37 -07:00
connect ( ui_ -> doubleSpinBox_markerLength , SIGNAL ( valueChanged ( double )), this , SLOT ( setMarkerLength ( double )));
connect ( ui_ -> doubleSpinBox_subpixel_error , SIGNAL ( valueChanged ( double )), this , SLOT ( setSubpixelMaxError ( double )));
connect ( ui_ -> checkBox_subpixel_refinement , SIGNAL ( toggled ( bool )), this , SLOT ( setSubpixelRefinement ( bool )));
2024-05-31 10:28:14 -07:00
connect ( ui_ -> checkBox_saveCalibrationData , SIGNAL ( toggled ( bool )), this , SLOT ( setCalibrationDataSaved ( bool )));
2021-02-28 10:31:18 -05:00
connect ( ui_ -> doubleSpinBox_stereoBaseline , SIGNAL ( valueChanged ( double )), this , SLOT ( setExpectedStereoBaseline ( double )));
2016-04-25 17:02:25 -04:00
connect ( ui_ -> spinBox_maxScale , SIGNAL ( valueChanged ( int )), this , SLOT ( setMaxScale ( int )));
2014-07-26 04:36:00 +00:00
2015-04-06 00:28:04 -04:00
connect ( ui_ -> buttonBox , SIGNAL ( rejected ()), this , SLOT ( close ()));
2014-07-26 04:36:00 +00:00
ui_ -> image_view -> setFocus ();
2014-07-22 22:22:59 +00:00
ui_ -> progressBar_count -> setMaximum ( COUNT_MIN );
ui_ -> progressBar_count -> setFormat ( "%v" );
2015-04-07 23:42:38 -04:00
ui_ -> progressBar_count_2 -> setMaximum ( COUNT_MIN );
ui_ -> progressBar_count_2 -> setFormat ( "%v" );
2014-07-22 22:22:59 +00:00
2015-04-08 12:23:10 -04:00
ui_ -> radioButton_raw -> setChecked ( true );
2015-05-05 19:43:25 -04:00
ui_ -> checkBox_switchImages -> setChecked ( switchImages );
2024-05-31 10:28:14 -07:00
ui_ -> comboBox_calib_model -> setCurrentIndex ( 1 );
2018-09-24 15:09:12 -04:00
2015-04-06 00:28:04 -04:00
this -> setStereoMode ( stereo_ );
2024-05-31 10:28:14 -07:00
timestamp_ = QDateTime :: currentDateTime (). toString ( "yyyyMMddhhmmss" );
2024-06-30 18:15:56 -07:00
2024-06-30 19:11:14 -07:00
#ifndef HAVE_CHARUCO
ui_ -> comboBox_board_type -> setItemData ( 1 , 0 , Qt :: UserRole - 1 );
ui_ -> comboBox_board_type -> setItemData ( 2 , 0 , Qt :: UserRole - 1 );
2024-09-01 03:55:29 -07:00
#elif CV_MAJOR_VERSION < 4 || (CV_MAJOR_VERSION == 4 && CV_MINOR_VERSION < 6)
2024-06-30 18:15:56 -07:00
ui_ -> comboBox_board_type -> setItemData ( 2 , 0 , Qt :: UserRole - 1 );
2024-09-01 03:55:29 -07:00
#elif CV_MAJOR_VERSION == 4 && CV_MINOR_VERSION < 8
ui_ -> comboBox_board_type -> setItemData ( 1 , 0 , Qt :: UserRole - 1 );
2024-06-30 18:15:56 -07:00
#endif
2014-07-22 22:22:59 +00:00
}
CalibrationDialog ::~ CalibrationDialog ()
{
this -> unregisterFromEventsManager ();
delete ui_ ;
}
2015-04-06 00:28:04 -04:00
void CalibrationDialog :: saveSettings ( QSettings & settings , const QString & group ) const
{
if ( ! group . isEmpty ())
{
settings . beginGroup ( group );
}
2024-06-30 17:11:37 -07:00
settings . setValue ( "board_type" , ui_ -> comboBox_board_type -> currentIndex ());
2015-04-06 00:28:04 -04:00
settings . setValue ( "board_width" , ui_ -> spinBox_boardWidth -> value ());
settings . setValue ( "board_height" , ui_ -> spinBox_boardHeight -> value ());
settings . setValue ( "board_square_size" , ui_ -> doubleSpinBox_squareSize -> value ());
2024-06-30 17:11:37 -07:00
settings . setValue ( "marker_type" , ui_ -> comboBox_marker_dictionary -> currentIndex ());
settings . setValue ( "marker_length" , ui_ -> doubleSpinBox_markerLength -> value ());
settings . setValue ( "subpixel_refinement" , ui_ -> checkBox_subpixel_refinement -> isChecked ());
settings . setValue ( "subpixel_max_error" , ui_ -> doubleSpinBox_subpixel_error -> value ());
2024-05-31 10:28:14 -07:00
settings . setValue ( "calibration_data_saved" , ui_ -> checkBox_saveCalibrationData -> isChecked ());
2016-04-25 17:02:25 -04:00
settings . setValue ( "max_scale" , ui_ -> spinBox_maxScale -> value ());
2015-04-06 00:28:04 -04:00
settings . setValue ( "geometry" , this -> saveGeometry ());
2024-05-31 10:28:14 -07:00
settings . setValue ( "calibration_model" , ui_ -> comboBox_calib_model -> currentIndex ());
2024-06-30 17:11:37 -07:00
2015-04-06 00:28:04 -04:00
if ( ! group . isEmpty ())
{
settings . endGroup ();
}
}
void CalibrationDialog :: loadSettings ( QSettings & settings , const QString & group )
{
if ( ! group . isEmpty ())
{
settings . beginGroup ( group );
}
2024-06-30 17:11:37 -07:00
this -> setBoardType ( settings . value ( "board_type" , ui_ -> comboBox_board_type -> currentIndex ()). toInt ());
2015-04-06 00:28:04 -04:00
this -> setBoardWidth ( settings . value ( "board_width" , ui_ -> spinBox_boardWidth -> value ()). toInt ());
this -> setBoardHeight ( settings . value ( "board_height" , ui_ -> spinBox_boardHeight -> value ()). toInt ());
this -> setSquareSize ( settings . value ( "board_square_size" , ui_ -> doubleSpinBox_squareSize -> value ()). toDouble ());
2024-06-30 17:11:37 -07:00
this -> setMarkerDictionary ( settings . value ( "marker_type" , ui_ -> comboBox_marker_dictionary -> currentIndex ()). toInt ());
this -> setMarkerLength ( settings . value ( "marker_length" , ui_ -> doubleSpinBox_markerLength -> value ()). toDouble ());
this -> setSubpixelRefinement ( settings . value ( "subpixel_refinement" , ui_ -> checkBox_subpixel_refinement -> isChecked ()). toBool ());
this -> setSubpixelMaxError ( settings . value ( "subpixel_max_error" , ui_ -> doubleSpinBox_subpixel_error -> value ()). toDouble ());
2024-05-31 10:28:14 -07:00
this -> setCalibrationDataSaved ( settings . value ( "calibration_data_saved" , ui_ -> checkBox_saveCalibrationData -> isChecked ()). toBool ());
2016-04-25 17:02:25 -04:00
this -> setMaxScale ( settings . value ( "max_scale" , ui_ -> spinBox_maxScale -> value ()). toDouble ());
2024-05-31 10:28:14 -07:00
int model = settings . value ( "calibration_model" , ui_ -> comboBox_calib_model -> currentIndex ()). toInt ();
if ( model == 0 )
{
this -> setFisheyeModel ();
}
else if ( model == 2 )
{
this -> setRationalModel ();
}
else
{
this -> setPlumbobModel ();
}
2015-04-06 00:28:04 -04:00
QByteArray bytes = settings . value ( "geometry" , QByteArray ()). toByteArray ();
if ( ! bytes . isEmpty ())
{
this -> restoreGeometry ( bytes );
}
if ( ! group . isEmpty ())
{
settings . endGroup ();
}
}
2016-02-18 14:12:12 -05:00
void CalibrationDialog :: resetSettings ()
{
2024-06-30 17:11:37 -07:00
this -> setBoardType ( 0 );
2016-02-18 14:12:12 -05:00
this -> setBoardWidth ( 8 );
this -> setBoardHeight ( 6 );
this -> setSquareSize ( 0.033 );
2024-06-30 17:11:37 -07:00
this -> setMarkerLength ( 0.02475 );
}
cv :: Mat drawChessboard ( int squareSize , int boardWidth , int boardHeight , int borderSize )
{
2025-09-03 15:59:37 -07:00
int imageWidth = squareSize * ( boardWidth + 1 ) + 2 * borderSize ;
int imageHeight = squareSize * ( boardHeight + 1 ) + 2 * borderSize ;
cv :: Mat chessboard ( imageHeight , imageWidth , CV_8UC1 , 255 );
unsigned char rowColor = 0 ;
2024-06-30 17:11:37 -07:00
for ( int i = borderSize ; i < imageHeight - borderSize ; i = i + squareSize ) {
2025-09-03 15:59:37 -07:00
unsigned char colColor = rowColor ;
2024-06-30 17:11:37 -07:00
for ( int j = borderSize ; j < imageWidth - borderSize ; j = j + squareSize ) {
2025-09-03 15:59:37 -07:00
cv :: Mat roi = chessboard ( cv :: Rect ( j , i , squareSize , squareSize ));
roi . setTo ( colColor );
colColor =~ colColor ;
2024-06-30 17:11:37 -07:00
}
2025-09-03 15:59:37 -07:00
rowColor = ~ rowColor ;
2024-06-30 17:11:37 -07:00
}
return chessboard ;
}
void CalibrationDialog :: generateBoard ()
{
int squareSizeInPixels = 200 ;
cv :: Mat image ;
QString filename ;
QTextStream stream ( & filename );
2024-06-30 19:11:14 -07:00
#ifdef HAVE_CHARUCO
2024-06-30 18:15:56 -07:00
if ( ui_ -> comboBox_board_type -> currentIndex () >= 1 )
2024-06-30 17:11:37 -07:00
{
try {
2026-07-29 22:48:39 -07:00
const int marginInPixels = squareSizeInPixels / 4 ;
cv :: Size size (
squareSizeInPixels * ui_ -> spinBox_boardWidth -> value () + 2 * marginInPixels ,
squareSizeInPixels * ui_ -> spinBox_boardHeight -> value () + 2 * marginInPixels );
UINFO ( "Creating board image of %dx%d pixels (%dx%d squares)" ,
size . width , size . height ,
ui_ -> spinBox_boardWidth -> value (), ui_ -> spinBox_boardHeight -> value ());
2024-06-30 18:15:56 -07:00
#if CV_MAJOR_VERSION > 4 || (CV_MAJOR_VERSION == 4 && CV_MINOR_VERSION >= 7)
charucoBoard_ -> generateImage (
2026-07-29 22:48:39 -07:00
size ,
2024-06-30 18:15:56 -07:00
image ,
2026-07-29 22:48:39 -07:00
marginInPixels , 1 );
2024-06-30 18:15:56 -07:00
#else
2024-06-30 17:11:37 -07:00
charucoBoard_ -> draw (
2026-07-29 22:48:39 -07:00
size ,
2024-06-30 17:11:37 -07:00
image ,
2026-07-29 22:48:39 -07:00
marginInPixels , 1 );
2024-06-30 18:15:56 -07:00
#endif
2024-06-30 17:11:37 -07:00
int arucoDict = ui_ -> comboBox_marker_dictionary -> currentIndex ();
stream << "charuco_" << ( arucoDict < kArucoDictNameSize ? kArucoDictNames [ arucoDict ] : "NA" ) << "_"
<< ui_ -> spinBox_boardWidth -> value () << "x" << ui_ -> spinBox_boardHeight -> value ()
<< "_ratio" << float ( ui_ -> doubleSpinBox_markerLength -> value ()) / float ( ui_ -> doubleSpinBox_squareSize -> value ());
}
catch ( const cv :: Exception & e )
{
2026-07-29 22:48:39 -07:00
UERROR ( "%s" , e . what ());
2024-06-30 17:11:37 -07:00
QMessageBox :: critical ( this , tr ( "Generating Board" ),
tr ( "Cannot generate the board. Make sure the dictionary "
"selected is big enough for the board size. Error: \" %1 \" " ). arg ( e . what ()));
return ;
}
}
else
2024-06-30 19:11:14 -07:00
#endif
2024-06-30 17:11:37 -07:00
{
image = drawChessboard (
squareSizeInPixels ,
ui_ -> spinBox_boardWidth -> value (),
ui_ -> spinBox_boardHeight -> value (),
squareSizeInPixels / 4 );
stream << "/chessboard_" << ui_ -> spinBox_boardWidth -> value () << "x" << ui_ -> spinBox_boardHeight -> value ();
}
QString filePath = QFileDialog :: getSaveFileName ( this , tr ( "Save" ), savingDirectory_ + "/" + filename + ".png" , "*.png" );
if ( ! filePath . isEmpty ())
{
cv :: imwrite ( filePath . toStdString (), image );
}
2016-02-18 14:12:12 -05:00
}
2016-09-13 18:26:18 -04:00
void CalibrationDialog :: setCameraName ( const QString & name )
{
cameraName_ = name ;
}
void CalibrationDialog :: setProgressVisibility ( bool visible )
{
ui_ -> groupBox_progress -> setVisible ( visible );
}
2015-05-05 19:43:25 -04:00
void CalibrationDialog :: setSwitchedImages ( bool switched )
{
ui_ -> checkBox_switchImages -> setChecked ( switched );
}
2024-05-31 10:28:14 -07:00
void CalibrationDialog :: setFisheyeModel ()
2019-05-09 19:20:26 -04:00
{
2024-05-31 10:28:14 -07:00
ui_ -> comboBox_calib_model -> setCurrentIndex ( 0 );
}
void CalibrationDialog :: setPlumbobModel ()
{
ui_ -> comboBox_calib_model -> setCurrentIndex ( 1 );
}
void CalibrationDialog :: setRationalModel ()
{
ui_ -> comboBox_calib_model -> setCurrentIndex ( 2 );
2019-05-09 19:20:26 -04:00
}
2016-09-13 18:26:18 -04:00
void CalibrationDialog :: setStereoMode ( bool stereo , const QString & leftSuffix , const QString & rightSuffix )
2015-04-06 00:28:04 -04:00
{
2016-09-13 18:26:18 -04:00
leftSuffix_ = leftSuffix ;
rightSuffix_ = rightSuffix ;
2015-04-06 00:28:04 -04:00
this -> restart ();
2016-09-13 18:26:18 -04:00
ui_ -> groupBox_progress -> setVisible ( true );
2015-04-06 00:28:04 -04:00
stereo_ = stereo ;
ui_ -> progressBar_x_2 -> setVisible ( stereo_ );
ui_ -> progressBar_y_2 -> setVisible ( stereo_ );
ui_ -> progressBar_size_2 -> setVisible ( stereo_ );
ui_ -> progressBar_skew_2 -> setVisible ( stereo_ );
2015-04-07 23:42:38 -04:00
ui_ -> progressBar_count_2 -> setVisible ( stereo_ );
2015-04-08 12:23:10 -04:00
ui_ -> label_right -> setVisible ( stereo_ );
2015-04-06 00:28:04 -04:00
ui_ -> image_view_2 -> setVisible ( stereo_ );
ui_ -> label_fx_2 -> setVisible ( stereo_ );
ui_ -> label_fy_2 -> setVisible ( stereo_ );
ui_ -> label_cx_2 -> setVisible ( stereo_ );
ui_ -> label_cy_2 -> setVisible ( stereo_ );
2024-05-31 10:28:14 -07:00
ui_ -> label_fovx_2 -> setVisible ( stereo_ );
ui_ -> label_fovy_2 -> setVisible ( stereo_ );
2015-04-07 23:42:38 -04:00
ui_ -> label_error_2 -> setVisible ( stereo_ );
2015-04-06 00:28:04 -04:00
ui_ -> label_baseline -> setVisible ( stereo_ );
ui_ -> label_baseline_name -> setVisible ( stereo_ );
2024-06-30 17:11:37 -07:00
ui_ -> label_stereoError -> setVisible ( stereo_ );
2015-04-06 00:28:04 -04:00
ui_ -> lineEdit_K_2 -> setVisible ( stereo_ );
ui_ -> lineEdit_D_2 -> setVisible ( stereo_ );
ui_ -> lineEdit_R_2 -> setVisible ( stereo_ );
ui_ -> lineEdit_P_2 -> setVisible ( stereo_ );
2015-04-08 12:23:10 -04:00
ui_ -> radioButton_stereoRectified -> setVisible ( stereo_ );
2015-06-26 18:21:32 -04:00
ui_ -> checkBox_switchImages -> setVisible ( stereo_ );
2021-02-28 10:31:18 -05:00
ui_ -> doubleSpinBox_stereoBaseline -> setVisible ( stereo_ );
ui_ -> label_stereoBaseline -> setVisible ( stereo_ );
2015-04-06 00:28:04 -04:00
}
2021-05-23 17:21:12 -04:00
int CalibrationDialog :: boardWidth () const
{
return ui_ -> spinBox_boardWidth -> value ();
}
int CalibrationDialog :: boardHeight () const
{
return ui_ -> spinBox_boardHeight -> value ();
}
double CalibrationDialog :: squareSize () const
{
return ui_ -> doubleSpinBox_squareSize -> value ();
}
2024-06-30 17:11:37 -07:00
double CalibrationDialog :: markerLength () const
{
return ui_ -> doubleSpinBox_markerLength -> value ();
}
void CalibrationDialog :: setBoardType ( int type )
{
if ( type != ui_ -> comboBox_board_type -> currentIndex ())
{
ui_ -> comboBox_board_type -> setCurrentIndex ( type );
}
this -> restart ();
}
void CalibrationDialog :: setMarkerDictionary ( int dictionary )
{
if ( dictionary != ui_ -> comboBox_marker_dictionary -> currentIndex ())
{
ui_ -> comboBox_marker_dictionary -> setCurrentIndex ( dictionary );
}
this -> restart ();
}
2021-05-23 17:21:12 -04:00
2014-07-26 04:36:00 +00:00
void CalibrationDialog :: setBoardWidth ( int width )
{
2015-04-06 00:28:04 -04:00
if ( width != ui_ -> spinBox_boardWidth -> value ())
2014-07-26 04:36:00 +00:00
{
2015-04-06 00:28:04 -04:00
ui_ -> spinBox_boardWidth -> setValue ( width );
2014-07-26 04:36:00 +00:00
}
2024-06-30 17:11:37 -07:00
this -> restart ();
2014-07-26 04:36:00 +00:00
}
void CalibrationDialog :: setBoardHeight ( int height )
{
2015-04-06 00:28:04 -04:00
if ( height != ui_ -> spinBox_boardHeight -> value ())
2014-07-26 04:36:00 +00:00
{
2015-04-06 00:28:04 -04:00
ui_ -> spinBox_boardHeight -> setValue ( height );
2014-07-26 04:36:00 +00:00
}
2024-06-30 17:11:37 -07:00
this -> restart ();
2014-07-26 04:36:00 +00:00
}
void CalibrationDialog :: setSquareSize ( double size )
{
2015-04-06 00:28:04 -04:00
if ( size != ui_ -> doubleSpinBox_squareSize -> value ())
2014-07-26 04:36:00 +00:00
{
2015-04-06 00:28:04 -04:00
ui_ -> doubleSpinBox_squareSize -> setValue ( size );
2014-07-26 04:36:00 +00:00
}
2024-06-30 17:11:37 -07:00
if ( ui_ -> doubleSpinBox_markerLength -> value () >= ui_ -> doubleSpinBox_squareSize -> value ())
{
if ( ui_ -> comboBox_board_type -> currentIndex () == 0 )
{
ui_ -> doubleSpinBox_markerLength -> setValue ( ui_ -> doubleSpinBox_squareSize -> value () - 0.000001 );
}
else
{
UWARN ( "Marker length (%f) cannot be larger than square size (%f), setting square size to %f. Decrease marker length first." ,
ui_ -> doubleSpinBox_markerLength -> value (),
ui_ -> doubleSpinBox_squareSize -> value (),
ui_ -> doubleSpinBox_squareSize -> value () + 0.000001 );
ui_ -> doubleSpinBox_squareSize -> setValue ( ui_ -> doubleSpinBox_markerLength -> value () + 0.000001 );
}
}
this -> restart ();
}
void CalibrationDialog :: setMarkerLength ( double length )
{
if ( length != ui_ -> doubleSpinBox_markerLength -> value ())
{
ui_ -> doubleSpinBox_markerLength -> setValue ( length );
}
if ( ui_ -> doubleSpinBox_markerLength -> value () >= ui_ -> doubleSpinBox_squareSize -> value ())
{
UWARN ( "Marker length (%f) cannot be larger than square size (%f), setting marker length to %f. Increase square size first." ,
ui_ -> doubleSpinBox_markerLength -> value (),
ui_ -> doubleSpinBox_squareSize -> value (),
ui_ -> doubleSpinBox_markerLength -> value () - 0.000001 );
ui_ -> doubleSpinBox_markerLength -> setValue ( ui_ -> doubleSpinBox_squareSize -> value () - 0.000001 );
}
this -> restart ();
}
void CalibrationDialog :: setSubpixelRefinement ( bool enabled )
{
if ( enabled != ui_ -> checkBox_subpixel_refinement -> isChecked ())
{
ui_ -> checkBox_subpixel_refinement -> setChecked ( enabled );
}
this -> restart ();
}
void CalibrationDialog :: setSubpixelMaxError ( double value )
{
if ( value != ui_ -> doubleSpinBox_subpixel_error -> value ())
{
ui_ -> doubleSpinBox_subpixel_error -> setValue ( value );
}
this -> restart ();
2014-07-26 04:36:00 +00:00
}
2024-05-31 10:28:14 -07:00
void CalibrationDialog :: setCalibrationDataSaved ( bool enabled )
{
if ( enabled != ui_ -> checkBox_saveCalibrationData -> isChecked ())
{
ui_ -> checkBox_saveCalibrationData -> setChecked ( enabled );
}
2024-06-30 17:11:37 -07:00
this -> restart ();
2024-05-31 10:28:14 -07:00
}
2021-02-28 10:31:18 -05:00
void CalibrationDialog :: setExpectedStereoBaseline ( double length )
{
if ( length != ui_ -> doubleSpinBox_stereoBaseline -> value ())
{
ui_ -> doubleSpinBox_stereoBaseline -> setValue ( length );
}
}
2016-04-25 17:02:25 -04:00
void CalibrationDialog :: setMaxScale ( int scale )
{
if ( scale != ui_ -> spinBox_maxScale -> value ())
{
ui_ -> spinBox_maxScale -> setValue ( scale );
}
}
2014-07-22 22:22:59 +00:00
void CalibrationDialog :: closeEvent ( QCloseEvent * event )
{
2016-01-19 21:01:56 -05:00
if ( ! savedCalibration_ && models_ [ 0 ]. isValidForRectification () &&
2015-07-09 10:01:41 -04:00
( ! stereo_ ||
2016-01-19 21:01:56 -05:00
( stereoModel_ . isValidForRectification () &&
2015-07-09 10:01:41 -04:00
( ! ui_ -> label_baseline -> isVisible () || stereoModel_ . baseline () > 0.0 ))))
2015-04-06 00:28:04 -04:00
{
QMessageBox :: StandardButton b = QMessageBox :: question ( this , tr ( "Save calibration?" ),
tr ( "The camera is calibrated but you didn't "
"save the calibration, do you want to save it?" ),
QMessageBox :: Yes | QMessageBox :: Ignore | QMessageBox :: Cancel , QMessageBox :: Yes );
event -> ignore ();
if ( b == QMessageBox :: Yes )
{
if ( this -> save ())
{
event -> accept ();
}
}
else if ( b == QMessageBox :: Ignore )
{
event -> accept ();
}
}
else
{
event -> accept ();
}
if ( event -> isAccepted ())
{
this -> unregisterFromEventsManager ();
}
2024-06-30 17:11:37 -07:00
cameraName_ . clear ();
2014-07-22 22:22:59 +00:00
}
2017-03-12 21:21:09 -04:00
bool CalibrationDialog :: handleEvent ( UEvent * event )
2014-07-22 22:22:59 +00:00
{
2015-04-05 16:42:41 -04:00
if ( ! processingData_ )
2014-07-22 22:22:59 +00:00
{
2024-04-14 19:06:04 -07:00
if ( event -> getClassName (). compare ( "SensorEvent" ) == 0 )
2014-07-22 22:22:59 +00:00
{
2024-04-14 19:06:04 -07:00
rtabmap :: SensorEvent * e = ( rtabmap :: SensorEvent * ) event ;
if ( e -> getCode () == rtabmap :: SensorEvent :: kCodeData )
2015-04-05 16:42:41 -04:00
{
processingData_ = true ;
QMetaObject :: invokeMethod ( this , "processImages" ,
2015-05-29 14:46:48 -04:00
Q_ARG ( cv :: Mat , e -> data (). imageRaw ()),
Q_ARG ( cv :: Mat , e -> data (). depthOrRightRaw ()),
2015-04-05 16:42:41 -04:00
Q_ARG ( QString , QString ( e -> cameraName (). c_str ())));
}
2014-07-22 22:22:59 +00:00
}
}
2017-03-12 21:21:09 -04:00
return false ;
2014-07-22 22:22:59 +00:00
}
2024-06-30 19:11:14 -07:00
#ifdef HAVE_CHARUCO
2024-06-30 17:11:37 -07:00
void matchCharucoImagePoints (
const cv :: aruco :: CharucoBoard & board ,
const std :: vector < cv :: Point2f > & detectedCorners ,
const std :: vector < int > & detectedIds ,
std :: vector < cv :: Point3f > & objectPoints )
{
UASSERT ( detectedIds . size () == detectedCorners . size ());
objectPoints . clear ();
2024-06-30 18:15:56 -07:00
#if CV_MAJOR_VERSION < 4 || (CV_MAJOR_VERSION == 4 && CV_MINOR_VERSION < 7)
2024-06-30 17:11:37 -07:00
objectPoints . reserve ( detectedIds . size ());
// look for detected markers that belong to the board and get their information
for ( size_t i = 0 ; i < detectedIds . size (); i ++ ) {
int pointId = detectedIds [ i ];
UASSERT ( pointId >= 0 && pointId < ( int ) board . chessboardCorners . size ());
objectPoints . push_back ( board . chessboardCorners [ pointId ]);
}
2024-06-30 18:15:56 -07:00
#else
2024-08-25 19:35:19 -07:00
cv :: Mat imgPts ;
board . matchImagePoints ( detectedCorners , detectedIds , objectPoints , imgPts );
2024-06-30 18:15:56 -07:00
#endif
2024-06-30 17:11:37 -07:00
}
2024-06-30 19:11:14 -07:00
#endif
2024-06-30 17:11:37 -07:00
// Modified from original versoin in opencv_contrib to remove "id="
void drawDetectedCornersCharuco ( cv :: InputOutputArray image , cv :: InputArray charucoCorners ,
cv :: InputArray charucoIds = cv :: noArray (),
cv :: Scalar cornerColor = cv :: Scalar ( 255 , 0 , 0 )) {
CV_Assert ( image . getMat (). total () != 0 &&
( image . getMat (). channels () == 1 || image . getMat (). channels () == 3 ));
CV_Assert (( charucoCorners . getMat (). total () == charucoIds . getMat (). total ()) ||
charucoIds . getMat (). total () == 0 );
unsigned int nCorners = ( unsigned int ) charucoCorners . getMat (). total ();
for ( unsigned int i = 0 ; i < nCorners ; i ++ ) {
cv :: Point2f corner = charucoCorners . getMat (). at < cv :: Point2f > ( i );
// draw first corner mark
cv :: rectangle ( image , corner - cv :: Point2f ( 3 , 3 ), corner + cv :: Point2f ( 3 , 3 ), cornerColor , 1 , cv :: LINE_AA );
// draw ID
if ( charucoIds . total () != 0 ) {
int id = charucoIds . getMat (). at < int > ( i );
std :: stringstream s ;
s << id ;
cv :: putText ( image , s . str (), corner + cv :: Point2f ( 5 , - 5 ), cv :: FONT_HERSHEY_SIMPLEX , 0.5 ,
cornerColor , 2 );
}
}
}
2015-04-05 16:42:41 -04:00
void CalibrationDialog :: processImages ( const cv :: Mat & imageLeft , const cv :: Mat & imageRight , const QString & cameraName )
2014-07-22 22:22:59 +00:00
{
2016-04-25 09:52:03 -04:00
UDEBUG ( "Processing images" );
2015-04-05 16:42:41 -04:00
processingData_ = true ;
2024-06-30 17:11:37 -07:00
if ( cameraName_ . isEmpty () && ! cameraName . isEmpty ())
2014-07-22 22:22:59 +00:00
{
2019-05-09 19:20:26 -04:00
cameraName_ = cameraName ;
2015-04-05 16:42:41 -04:00
}
2021-05-23 17:21:12 -04:00
else if ( cameraName . isEmpty ())
{
cameraName_ = "0000" ;
}
2019-05-09 19:20:26 -04:00
if ( ui_ -> label_serial -> text (). compare ( cameraName_ ) != 0 )
2015-04-05 16:42:41 -04:00
{
ui_ -> label_serial -> setText ( cameraName_ );
}
2024-06-30 17:11:37 -07:00
2015-04-08 12:23:10 -04:00
std :: vector < cv :: Mat > inputRawImages ( 2 );
if ( ui_ -> checkBox_switchImages -> isChecked ())
{
inputRawImages [ 0 ] = imageRight ;
inputRawImages [ 1 ] = imageLeft ;
}
else
{
inputRawImages [ 0 ] = imageLeft ;
inputRawImages [ 1 ] = imageRight ;
}
2015-04-05 16:42:41 -04:00
std :: vector < cv :: Mat > images ( 2 );
2015-04-08 12:23:10 -04:00
images [ 0 ] = inputRawImages [ 0 ];
images [ 1 ] = inputRawImages [ 1 ];
2015-04-07 23:42:38 -04:00
imageSize_ [ 0 ] = images [ 0 ]. size ();
imageSize_ [ 1 ] = images [ 1 ]. size ();
bool boardFound [ 2 ] = { false };
bool boardAccepted [ 2 ] = { false };
bool readyToCalibrate [ 2 ] = { false };
2015-04-05 16:42:41 -04:00
std :: vector < std :: vector < cv :: Point2f > > pointBuf ( 2 );
2024-06-30 17:11:37 -07:00
std :: vector < std :: vector < cv :: Point3f > > objectBuf ( 2 );
std :: vector < std :: vector < int > > pointIds ( 2 );
2015-04-05 16:42:41 -04:00
2015-07-09 10:01:41 -04:00
bool depthDetected = false ;
2015-04-05 16:42:41 -04:00
for ( int id = 0 ; id < ( stereo_ ? 2 : 1 ); ++ id )
{
cv :: Mat viewGray ;
if ( ! images [ id ]. empty ())
{
2015-04-08 12:23:10 -04:00
if ( images [ id ]. type () == CV_16UC1 )
{
2016-04-25 09:52:03 -04:00
double min , max ;
cv :: minMaxLoc ( images [ id ], & min , & max );
UDEBUG ( "Camera IR %d: min=%f max=%f" , id , min , max );
if ( minIrs_ [ id ] == 0 )
{
minIrs_ [ id ] = min ;
}
if ( maxIrs_ [ id ] == 0x7fff )
{
maxIrs_ [ id ] = max ;
}
2015-07-09 10:01:41 -04:00
depthDetected = true ;
2015-04-08 12:23:10 -04:00
//assume IR image: convert to gray scaled
const float factor = 255.0f / float (( maxIrs_ [ id ] - minIrs_ [ id ]));
viewGray = cv :: Mat ( images [ id ]. rows , images [ id ]. cols , CV_8UC1 );
for ( int i = 0 ; i < images [ id ]. rows ; ++ i )
{
for ( int j = 0 ; j < images [ id ]. cols ; ++ j )
{
viewGray . at < unsigned char > ( i , j ) = ( unsigned char ) std :: min ( float ( std :: max ( images [ id ]. at < unsigned short > ( i , j ) - minIrs_ [ id ], 0 )) * factor , 255.0f );
}
}
cvtColor ( viewGray , images [ id ], cv :: COLOR_GRAY2BGR ); // convert to show detected points in color
}
else if ( images [ id ]. channels () == 3 )
2014-07-22 22:22:59 +00:00
{
2015-04-05 16:42:41 -04:00
cvtColor ( images [ id ], viewGray , cv :: COLOR_BGR2GRAY );
}
else
{
viewGray = images [ id ];
cvtColor ( viewGray , images [ id ], cv :: COLOR_GRAY2BGR ); // convert to show detected points in color
}
}
else
{
UERROR ( "Image %d is empty!! Should not!" , id );
}
2015-04-08 12:23:10 -04:00
minIrs_ [ id ] = 0 ;
maxIrs_ [ id ] = 0x7FFF ;
2015-04-07 23:42:38 -04:00
//Dot it only if not yet calibrated
if ( ! ui_ -> pushButton_save -> isEnabled ())
2015-04-05 16:42:41 -04:00
{
2024-06-30 17:11:37 -07:00
std :: vector < int > markerIds ;
std :: vector < std :: vector < cv :: Point2f > > markerCorners ;
2015-04-07 23:42:38 -04:00
cv :: Size boardSize ( ui_ -> spinBox_boardWidth -> value (), ui_ -> spinBox_boardHeight -> value ());
if ( ! viewGray . empty ())
2015-04-05 16:42:41 -04:00
{
2026-07-29 22:48:39 -07:00
int flags = cv :: CALIB_CB_ADAPTIVE_THRESH | cv :: CALIB_CB_NORMALIZE_IMAGE ;
2015-04-08 12:23:10 -04:00
if ( ! viewGray . empty ())
{
2016-04-25 17:02:25 -04:00
int maxScale = ui_ -> spinBox_maxScale -> value ();
2015-04-08 12:23:10 -04:00
for ( int scale = 1 ; scale <= maxScale ; scale ++ )
{
cv :: Mat timg ;
if ( scale == 1 )
timg = viewGray ;
else
2026-07-29 22:48:39 -07:00
cv :: resize ( viewGray , timg , cv :: Size (), scale , scale , cv :: INTER_CUBIC );
2024-06-30 17:11:37 -07:00
2024-06-30 19:11:14 -07:00
#ifdef HAVE_CHARUCO
2024-06-30 18:15:56 -07:00
if ( ui_ -> comboBox_board_type -> currentIndex () >= 1 )
2024-06-30 17:11:37 -07:00
{
std :: vector < std :: vector < cv :: Point2f > > rejected ;
UASSERT ( charucoBoard_ . get ());
// detect markers
2024-08-25 19:35:19 -07:00
UDEBUG ( "Detecting aruco markers..." );
#if CV_MAJOR_VERSION > 4 || (CV_MAJOR_VERSION == 4 && CV_MINOR_VERSION >= 7)
UASSERT ( arucoDetector_ . get ());
arucoDetector_ -> detectMarkers ( timg , markerCorners , markerIds , rejected );
#else
2024-06-30 17:11:37 -07:00
cv :: aruco :: detectMarkers ( timg , markerDictionary_ , markerCorners , markerIds , arucoDetectorParams_ , rejected );
2024-08-25 19:35:19 -07:00
#endif
2024-06-30 17:11:37 -07:00
// refine strategy to detect more markers
2024-08-25 19:35:19 -07:00
UDEBUG ( "Refining aruco markers..." );
#if CV_MAJOR_VERSION > 4 || (CV_MAJOR_VERSION == 4 && CV_MINOR_VERSION >= 7)
arucoDetector_ -> refineDetectedMarkers ( timg , * charucoBoard_ , markerCorners , markerIds , rejected );
#else
2024-06-30 17:11:37 -07:00
cv :: aruco :: refineDetectedMarkers ( timg , charucoBoard_ , markerCorners , markerIds , rejected );
2024-08-25 19:35:19 -07:00
#endif
2024-06-30 17:11:37 -07:00
// interpolate charuco corners
2024-08-25 19:35:19 -07:00
UDEBUG ( "Finding charuco corners (markers=%ld)..." , markerCorners . size ());
2024-06-30 17:11:37 -07:00
if ( markerIds . size () > 0 )
{
UASSERT ( markerIds . size () == markerCorners . size ());
2024-08-25 19:35:19 -07:00
#if CV_MAJOR_VERSION > 4 || (CV_MAJOR_VERSION == 4 && CV_MINOR_VERSION >= 7)
UASSERT ( charucoDetector_ . get ());
charucoDetector_ -> detectBoard ( timg , pointBuf [ id ], pointIds [ id ], markerCorners , markerIds );
#else
2024-06-30 17:11:37 -07:00
cv :: aruco :: interpolateCornersCharuco ( markerCorners , markerIds , timg , charucoBoard_ , pointBuf [ id ], pointIds [ id ], cv :: noArray (), cv :: noArray (), 1 );
2024-08-25 19:35:19 -07:00
#endif
UDEBUG ( "Found %ld charuco corners (requires 12)" , pointBuf [ id ]. size ());
2024-06-30 17:11:37 -07:00
if ( pointBuf [ id ]. size () >= 12 ) {
// Match image points
matchCharucoImagePoints ( * charucoBoard_ , pointBuf [ id ], pointIds [ id ], objectBuf [ id ]);
boardFound [ id ] = ! objectBuf [ id ]. empty () && objectBuf [ id ]. size () == pointBuf [ id ]. size ();
}
}
}
else // standard checkerboard
2024-06-30 19:11:14 -07:00
#endif
2024-06-30 17:11:37 -07:00
{
boardFound [ id ] = cv :: findChessboardCorners ( timg , boardSize , pointBuf [ id ], flags );
objectBuf [ id ] = chessboardPoints_ ;
pointIds [ id ] = chessboardPointIds_ ;
}
2015-04-08 12:23:10 -04:00
if ( boardFound [ id ])
{
if ( scale > 1 )
{
cv :: Mat cornersMat ( pointBuf [ id ]);
cornersMat *= 1. / scale ;
}
2024-06-30 17:11:37 -07:00
2015-04-08 12:23:10 -04:00
break ;
}
}
}
2015-04-07 23:42:38 -04:00
}
if ( boardFound [ id ]) // If done with success,
{
2024-06-30 17:11:37 -07:00
// refine corners?
std :: vector < cv :: Point2f > originalPoints = pointBuf [ id ];
std :: vector < cv :: Point2f > rejectedPoints ;
std :: vector < int > rejectedPointIds ;
if ( ui_ -> checkBox_subpixel_refinement -> isChecked ())
2015-04-05 16:42:41 -04:00
{
2024-06-30 17:11:37 -07:00
// improve the found corners' coordinate accuracy
float minSquareDistance = - 1.0f ;
for ( unsigned int i = 0 ; i < pointBuf [ id ]. size () - 1 ; ++ i )
2015-04-05 16:42:41 -04:00
{
2024-06-30 17:11:37 -07:00
float d = cv :: norm ( pointBuf [ id ][ i ] - pointBuf [ id ][ i + 1 ]);
if ( minSquareDistance == - 1.0f || minSquareDistance > d )
{
minSquareDistance = d ;
}
}
2024-06-30 18:15:56 -07:00
float ratio = ui_ -> comboBox_board_type -> currentIndex () >= 1 ? 6.0f : 2.0f ;
2024-06-30 17:11:37 -07:00
float radius = minSquareDistance ==- 1.0f ? 5.0f : ( minSquareDistance / ratio );
cv :: cornerSubPix ( viewGray , pointBuf [ id ], cv :: Size ( radius , radius ), cv :: Size ( - 1 , - 1 ),
2026-07-29 22:48:39 -07:00
cv :: TermCriteria ( cv :: TermCriteria :: EPS + cv :: TermCriteria :: MAX_ITER , 30 , 0.1 ));
2024-06-30 17:11:37 -07:00
// Filter points that drifted to far (caused by reflection or bad subpixel gradient)
float threshold = ui_ -> doubleSpinBox_subpixel_error -> value ();
if ( threshold > 0 )
{
std :: vector < cv :: Point3f > filteredObjectPts ;
std :: vector < cv :: Point2f > filteredPoints ;
std :: vector < int > filteredPointIds ;
for ( size_t i = 0 ; i < pointBuf [ id ]. size (); ++ i )
{
float d = cv :: norm ( pointBuf [ id ][ i ] - originalPoints [ i ]);
if ( d < threshold )
{
filteredObjectPts . push_back ( objectBuf [ id ][ i ]);
filteredPoints . push_back ( pointBuf [ id ][ i ]);
filteredPointIds . push_back ( pointIds [ id ][ i ]);
}
else
{
UWARN ( "Filtered point: subpix error for image=%d cam=%d pt=%d radius=%f: %f > %f" , currentId_ , id , pointIds [ id ][ i ], radius , d , threshold );
rejectedPoints . push_back ( pointBuf [ id ][ i ]);
rejectedPointIds . push_back ( pointIds [ id ][ i ]);
}
}
objectBuf [ id ] = filteredObjectPts ;
pointBuf [ id ] = filteredPoints ;
pointIds [ id ] = filteredPointIds ;
2015-04-05 16:42:41 -04:00
}
}
2014-07-22 22:22:59 +00:00
2015-04-07 23:42:38 -04:00
// Draw the corners.
2024-05-31 10:28:14 -07:00
images [ id ] = images [ id ]. clone ();
2024-06-30 19:11:14 -07:00
#ifdef HAVE_CHARUCO
2024-06-30 18:15:56 -07:00
if ( ui_ -> comboBox_board_type -> currentIndex () >= 1 ) {
2024-06-30 17:11:37 -07:00
if ( markerIds . size () > 0 )
cv :: aruco :: drawDetectedMarkers ( images [ id ], markerCorners , cv :: noArray (), cv :: Scalar ( 255 , 0 , 0 ));
2014-07-22 22:22:59 +00:00
}
2024-06-30 19:11:14 -07:00
#endif
2024-06-30 17:11:37 -07:00
if ( pointBuf [ id ]. size () > 0 )
drawDetectedCornersCharuco ( images [ id ], pointBuf [ id ], pointIds [ id ], cv :: Scalar ( 0 , 255 , 0 )); // Accepted Green
if ( rejectedPoints . size () > 0 )
drawDetectedCornersCharuco ( images [ id ], rejectedPoints , rejectedPointIds , cv :: Scalar ( 0 , 0 , 255 )); // Rejected Red
2015-04-05 16:42:41 -04:00
2024-06-30 17:11:37 -07:00
if ( pointBuf [ id ]. size () < rejectedPoints . size ())
{
// don't add if more than 50% of valid points were filtered
UWARN ( "Ignoring whole board of image %d cam=%d because too many points were filtered." , currentId_ , id );
boardFound [ id ] = false ;
2015-04-07 23:42:38 -04:00
}
2024-05-31 10:28:14 -07:00
else
{
2024-06-30 17:11:37 -07:00
std :: vector < float > params ( 4 , 0 );
getParams ( originalPoints , boardSize , imageSize_ [ id ], params [ 0 ], params [ 1 ], params [ 2 ], params [ 3 ]);
2024-06-30 18:15:56 -07:00
if ( ui_ -> comboBox_board_type -> currentIndex () >= 1 )
2015-04-07 23:42:38 -04:00
{
2024-06-30 17:11:37 -07:00
//params[2] = float(pointBuf[id].size()) / float(boardSize.width * boardSize.height); // number of markers seen
float area = getArea ( markerCorners [ markerCorners . size () / 2 ], cv :: Size ( 4 , 4 )) * ( boardSize . width * boardSize . height );
params [ 2 ] = std :: sqrt ( area / ( imageSize_ [ id ]. width * imageSize_ [ id ]. height ));
params [ 2 ] = params [ 2 ] > 1 ? 1 : params [ 2 ];
params [ 3 ] = getSkew ( markerCorners [ markerCorners . size () / 2 ]);
2015-04-07 23:42:38 -04:00
}
2024-06-30 17:11:37 -07:00
bool addSample = true ;
if ( ! ui_ -> checkBox_keep_all -> isChecked ())
2015-04-07 23:42:38 -04:00
{
2024-06-30 17:11:37 -07:00
for ( unsigned int i = 0 ; i < imageParams_ [ id ]. size (); ++ i )
{
2024-06-30 18:15:56 -07:00
if ( fabs ( params [ 0 ] - imageParams_ [ id ][ i ]. at ( 0 )) < ( ui_ -> comboBox_board_type -> currentIndex () >= 1 ? 0.2 : 0.1 ) * ui_ -> doubleSpinBox_sample_factor -> value () && // x
fabs ( params [ 1 ] - imageParams_ [ id ][ i ]. at ( 1 )) < ( ui_ -> comboBox_board_type -> currentIndex () >= 1 ? 0.2 : 0.1 ) * ui_ -> doubleSpinBox_sample_factor -> value () && // y
2024-06-30 17:11:37 -07:00
fabs ( params [ 2 ] - imageParams_ [ id ][ i ]. at ( 2 )) < 0.05 * ui_ -> doubleSpinBox_sample_factor -> value () && // size
( params [ 3 ] == 0 || params [ 3 ] == 1.0f || imageParams_ [ id ][ i ]. at ( 3 ) == 0 || imageParams_ [ id ][ i ]. at ( 3 ) == 1.0f || fabs ( params [ 3 ] - imageParams_ [ id ][ i ]. at ( 3 )) < 0.1 * ui_ -> doubleSpinBox_sample_factor -> value ())) // skew
{
addSample = false ;
break ;
}
}
2015-04-07 23:42:38 -04:00
}
2024-06-30 17:11:37 -07:00
if ( addSample )
2015-04-08 12:23:10 -04:00
{
2024-06-30 17:11:37 -07:00
boardAccepted [ id ] = true ;
imageIds_ [ id ]. push_back ( currentId_ );
imagePoints_ [ id ]. push_back ( pointBuf [ id ]);
imageParams_ [ id ]. push_back ( params );
objectPoints_ [ id ]. push_back ( objectBuf [ id ]);
UINFO ( "[%d] Added board %d, total=%d. (x=%f, y=%f, size=%f, skew=%f)" , id , currentId_ , ( int ) imagePoints_ [ id ]. size (), params [ 0 ], params [ 1 ], params [ 2 ], params [ 3 ]);
2015-04-08 12:23:10 -04:00
2024-06-30 17:11:37 -07:00
// update statistics
std :: vector < float > xRange ( 2 , imageParams_ [ id ][ 0 ]. at ( 0 ));
std :: vector < float > yRange ( 2 , imageParams_ [ id ][ 0 ]. at ( 1 ));
std :: vector < float > sizeRange ( 2 , imageParams_ [ id ][ 0 ]. at ( 2 ));
std :: vector < float > skewRange ( 2 , imageParams_ [ id ][ 0 ]. at ( 3 ));
for ( unsigned int i = 1 ; i < imageParams_ [ id ]. size (); ++ i )
{
xRange [ 0 ] = imageParams_ [ id ][ i ]. at ( 0 ) < xRange [ 0 ] ? imageParams_ [ id ][ i ]. at ( 0 ) : xRange [ 0 ];
xRange [ 1 ] = imageParams_ [ id ][ i ]. at ( 0 ) > xRange [ 1 ] ? imageParams_ [ id ][ i ]. at ( 0 ) : xRange [ 1 ];
yRange [ 0 ] = imageParams_ [ id ][ i ]. at ( 1 ) < yRange [ 0 ] ? imageParams_ [ id ][ i ]. at ( 1 ) : yRange [ 0 ];
yRange [ 1 ] = imageParams_ [ id ][ i ]. at ( 1 ) > yRange [ 1 ] ? imageParams_ [ id ][ i ]. at ( 1 ) : yRange [ 1 ];
sizeRange [ 0 ] = imageParams_ [ id ][ i ]. at ( 2 ) < sizeRange [ 0 ] ? imageParams_ [ id ][ i ]. at ( 2 ) : sizeRange [ 0 ];
sizeRange [ 1 ] = imageParams_ [ id ][ i ]. at ( 2 ) > sizeRange [ 1 ] ? imageParams_ [ id ][ i ]. at ( 2 ) : sizeRange [ 1 ];
if ( imageParams_ [ id ][ i ]. at ( 3 ) != 0 && imageParams_ [ id ][ i ]. at ( 3 ) != 1 ) {
if ( skewRange [ 0 ] == 0 || skewRange [ 0 ] == 1 )
{
skewRange [ 0 ] = imageParams_ [ id ][ i ]. at ( 3 );
skewRange [ 1 ] = imageParams_ [ id ][ i ]. at ( 3 );
}
else
{
skewRange [ 0 ] = imageParams_ [ id ][ i ]. at ( 3 ) < skewRange [ 0 ] ? imageParams_ [ id ][ i ]. at ( 3 ) : skewRange [ 0 ];
skewRange [ 1 ] = imageParams_ [ id ][ i ]. at ( 3 ) > skewRange [ 1 ] ? imageParams_ [ id ][ i ]. at ( 3 ) : skewRange [ 1 ];
}
}
}
//UINFO("Stats [%d]:", id);
//UINFO(" Count = %d", (int)imagePoints_[id].size());
//UINFO(" x = [%f -> %f]", xRange[0], xRange[1]);
//UINFO(" y = [%f -> %f]", yRange[0], yRange[1]);
//UINFO(" size = [%f -> %f]", sizeRange[0], sizeRange[1]);
//UINFO(" skew = [%f -> %f]", skewRange[0], skewRange[1]);
2015-04-08 12:23:10 -04:00
2024-06-30 17:11:37 -07:00
float xGood = xRange [ 1 ] - xRange [ 0 ];
float yGood = yRange [ 1 ] - yRange [ 0 ];
float sizeGood = sizeRange [ 1 ] - sizeRange [ 0 ];
float skewGood = skewRange [ 1 ] - skewRange [ 0 ];
if ( id == 0 )
2015-04-08 12:23:10 -04:00
{
2024-06-30 17:11:37 -07:00
ui_ -> progressBar_x -> setValue ( xGood * 100 );
ui_ -> progressBar_y -> setValue ( yGood * 100 );
ui_ -> progressBar_size -> setValue ( sizeGood * 100 );
ui_ -> progressBar_skew -> setValue ( skewGood * 100 );
if (( int ) imagePoints_ [ id ]. size () > ui_ -> progressBar_count -> maximum ())
{
ui_ -> progressBar_count -> setMaximum (( int ) imagePoints_ [ id ]. size ());
}
ui_ -> progressBar_count -> setValue (( int ) imagePoints_ [ id ]. size ());
2015-04-08 12:23:10 -04:00
}
2024-06-30 17:11:37 -07:00
else
2015-04-08 12:23:10 -04:00
{
2024-06-30 17:11:37 -07:00
ui_ -> progressBar_x_2 -> setValue ( xGood * 100 );
ui_ -> progressBar_y_2 -> setValue ( yGood * 100 );
ui_ -> progressBar_size_2 -> setValue ( sizeGood * 100 );
ui_ -> progressBar_skew_2 -> setValue ( skewGood * 100 );
if (( int ) imagePoints_ [ id ]. size () > ui_ -> progressBar_count_2 -> maximum ())
{
ui_ -> progressBar_count_2 -> setMaximum (( int ) imagePoints_ [ id ]. size ());
}
ui_ -> progressBar_count_2 -> setValue (( int ) imagePoints_ [ id ]. size ());
2015-04-08 12:23:10 -04:00
}
2024-06-30 17:11:37 -07:00
if ( imagePoints_ [ id ]. size () >= COUNT_MIN / 2 &&
xGood > 0.5 &&
yGood > 0.5 &&
( sizeGood > 0.4 || ( ui_ -> comboBox_calib_model -> currentIndex () == 0 && sizeGood > 0.25 )) &&
skewGood > 0.5 )
{
readyToCalibrate [ id ] = true ;
}
//update IR values
if ( inputRawImages [ id ]. type () == CV_16UC1 )
{
//update min max IR if the chessboard was found
minIrs_ [ id ] = 0xFFFF ;
maxIrs_ [ id ] = 0 ;
for ( size_t i = 0 ; i < pointBuf [ id ]. size (); ++ i )
{
const cv :: Point2f & p = pointBuf [ id ][ i ];
cv :: Rect roi ( std :: max ( 0 , ( int ) p . x - 3 ), std :: max ( 0 , ( int ) p . y - 3 ), 6 , 6 );
roi . width = std :: min ( roi . width , inputRawImages [ id ]. cols - roi . x );
roi . height = std :: min ( roi . height , inputRawImages [ id ]. rows - roi . y );
//find minMax in the roi
double min , max ;
cv :: minMaxLoc ( inputRawImages [ id ]( roi ), & min , & max );
if ( min < minIrs_ [ id ])
{
minIrs_ [ id ] = min ;
}
if ( max > maxIrs_ [ id ])
{
maxIrs_ [ id ] = max ;
}
}
}
}
else
{
//break;
2015-04-08 12:23:10 -04:00
}
}
2014-07-22 22:22:59 +00:00
}
2015-04-05 16:42:41 -04:00
}
}
2015-07-09 10:01:41 -04:00
ui_ -> label_baseline -> setVisible ( ! depthDetected );
ui_ -> label_baseline_name -> setVisible ( ! depthDetected );
2024-06-30 17:11:37 -07:00
ui_ -> label_stereoError -> setVisible ( ! depthDetected );
2015-04-05 16:42:41 -04:00
2024-05-31 10:28:14 -07:00
if ( ui_ -> checkBox_saveCalibrationData -> isChecked () && ( boardAccepted [ 0 ] || boardAccepted [ 1 ]))
{
for ( int id = 0 ; id < ( stereo_ ? 2 : 1 ); ++ id )
{
QString rawImagesDir = savingDirectory_ + "/" + cameraName_ + "_" + timestamp_ + ( stereo_ ? "/" + ( id == 0 ? leftSuffix_ : rightSuffix_ ) : "images" );
QString imagesWithBoardDir = rawImagesDir + "_board_detection" ;
if ( ! QDir ( rawImagesDir ). exists ())
{
UINFO ( "Creating dir %s" , rawImagesDir . toStdString (). c_str ());
QDir (). mkpath ( rawImagesDir );
}
if ( ! QDir ( imagesWithBoardDir ). exists ())
{
UINFO ( "Creating dir %s" , imagesWithBoardDir . toStdString (). c_str ());
QDir (). mkpath ( imagesWithBoardDir );
}
cv :: imwrite (( rawImagesDir + "/" + QString :: number ( currentId_ ) + ".png" ). toStdString (), inputRawImages [ id ]);
2024-06-30 17:11:37 -07:00
cv :: imwrite (( imagesWithBoardDir + "/" + QString :: number ( currentId_ ) + ".jpg" ). toStdString (), images [ id ]);
2024-05-31 10:28:14 -07:00
}
}
2024-06-30 17:11:37 -07:00
if ( stereo_ && boardFound [ 0 ] && boardFound [ 1 ] && ( boardAccepted [ 0 ] || boardAccepted [ 1 ]))
2015-04-07 23:42:38 -04:00
{
2024-06-30 17:11:37 -07:00
// Find same corners detected in both boards
std :: vector < int > combinedIds ;
std :: vector < cv :: Point2f > leftCorners ;
std :: vector < cv :: Point2f > rightCorners ;
std :: vector < cv :: Point3f > objectPoints ;
for ( size_t i = 0 ; i < pointIds [ 0 ]. size (); ++ i )
{
for ( size_t j = 0 ; j < pointIds [ 1 ]. size (); ++ j )
{
if ( pointIds [ 0 ][ i ] == pointIds [ 1 ][ j ])
{
leftCorners . push_back ( pointBuf [ 0 ][ i ]);
rightCorners . push_back ( pointBuf [ 1 ][ j ]);
objectPoints . push_back ( objectBuf [ 0 ][ i ]);
combinedIds . push_back ( pointIds [ 0 ][ i ]);
break ;
}
}
}
if ( objectPoints . size () >= 6 )
{
stereoImagePoints_ [ 0 ]. push_back ( leftCorners );
stereoImagePoints_ [ 1 ]. push_back ( rightCorners );
stereoObjectPoints_ . push_back ( objectPoints );
stereoImageIds_ . push_back ( currentId_ );
UINFO ( "Added board %d for stereo image points (size=%d)" , currentId_ , ( int ) stereoImagePoints_ [ 0 ]. size ());
}
2015-04-07 23:42:38 -04:00
}
2015-04-05 16:42:41 -04:00
if ( ! stereo_ && readyToCalibrate [ 0 ])
{
2016-01-19 17:43:33 -05:00
unlock ();
2015-04-05 16:42:41 -04:00
}
2015-04-07 23:42:38 -04:00
else if ( stereo_ && readyToCalibrate [ 0 ] && readyToCalibrate [ 1 ] && stereoImagePoints_ [ 0 ]. size ())
2015-04-05 16:42:41 -04:00
{
2016-01-19 17:43:33 -05:00
unlock ();
2014-07-22 22:22:59 +00:00
}
2015-04-08 12:23:10 -04:00
if ( ui_ -> radioButton_rectified -> isChecked ())
2014-07-22 22:22:59 +00:00
{
2016-01-19 17:43:33 -05:00
if ( models_ [ 0 ]. isValidForRectification ())
2015-04-05 16:42:41 -04:00
{
2015-04-07 23:42:38 -04:00
images [ 0 ] = models_ [ 0 ]. rectifyImage ( images [ 0 ]);
2015-04-05 16:42:41 -04:00
}
2016-01-19 17:43:33 -05:00
if ( models_ [ 1 ]. isValidForRectification ())
2015-04-05 16:42:41 -04:00
{
2015-04-08 12:23:10 -04:00
images [ 1 ] = models_ [ 1 ]. rectifyImage ( images [ 1 ]);
2015-04-05 16:42:41 -04:00
}
}
2015-07-09 10:01:41 -04:00
else if ( ui_ -> radioButton_stereoRectified -> isChecked () &&
2016-01-19 17:43:33 -05:00
( stereoModel_ . left (). isValidForRectification () &&
stereoModel_ . right (). isValidForRectification () &&
2015-07-09 10:01:41 -04:00
( ! ui_ -> label_baseline -> isVisible () || stereoModel_ . baseline () > 0.0 )))
2015-04-08 12:23:10 -04:00
{
images [ 0 ] = stereoModel_ . left (). rectifyImage ( images [ 0 ]);
images [ 1 ] = stereoModel_ . right (). rectifyImage ( images [ 1 ]);
}
2015-04-05 16:42:41 -04:00
if ( ui_ -> checkBox_showHorizontalLines -> isChecked ())
{
for ( int id = 0 ; id < ( stereo_ ? 2 : 1 ); ++ id )
{
2015-04-07 12:00:10 -04:00
int step = imageSize_ [ id ]. height / 16 ;
2015-04-05 16:42:41 -04:00
for ( int i = step ; i < imageSize_ [ id ]. height ; i += step )
{
cv :: line ( images [ id ], cv :: Point ( 0 , i ), cv :: Point ( imageSize_ [ id ]. width , i ), CV_RGB ( 0 , 255 , 0 ));
}
}
2014-07-22 22:22:59 +00:00
}
2015-04-07 23:42:38 -04:00
ui_ -> label_left -> setText ( tr ( "%1x%2" ). arg ( images [ 0 ]. cols ). arg ( images [ 0 ]. rows ));
2014-07-22 22:22:59 +00:00
//show frame
2015-04-05 16:42:41 -04:00
ui_ -> image_view -> setImage ( uCvMat2QImage ( images [ 0 ]). mirrored ( ui_ -> checkBox_mirror -> isChecked (), false ));
if ( stereo_ )
{
2015-04-07 23:42:38 -04:00
ui_ -> label_right -> setText ( tr ( "%1x%2" ). arg ( images [ 1 ]. cols ). arg ( images [ 1 ]. rows ));
2015-04-05 16:42:41 -04:00
ui_ -> image_view_2 -> setImage ( uCvMat2QImage ( images [ 1 ]). mirrored ( ui_ -> checkBox_mirror -> isChecked (), false ));
}
processingData_ = false ;
2024-06-30 17:11:37 -07:00
++ currentId_ ;
2014-07-22 22:22:59 +00:00
}
void CalibrationDialog :: restart ()
{
// restart
2024-06-30 17:11:37 -07:00
if ( ! savingDirectory_ . isEmpty () && ! cameraName_ . isEmpty () && ! savedCalibration_ && ui_ -> comboBox_board_type -> isEnabled ())
{
//overwrite previous data not used.
QDir ( savingDirectory_ + "/" + cameraName_ + "_" + timestamp_ ). removeRecursively ();
}
else
{
timestamp_ = QDateTime :: currentDateTime (). toString ( "yyyyMMddhhmmss" );
}
2015-04-06 00:28:04 -04:00
savedCalibration_ = false ;
2024-05-31 10:28:14 -07:00
currentId_ = 0 ;
2015-04-05 16:42:41 -04:00
imagePoints_ [ 0 ]. clear ();
imagePoints_ [ 1 ]. clear ();
2024-06-30 17:11:37 -07:00
objectPoints_ [ 0 ]. clear ();
objectPoints_ [ 1 ]. clear ();
2015-04-05 16:42:41 -04:00
imageParams_ [ 0 ]. clear ();
imageParams_ [ 1 ]. clear ();
2024-05-31 10:28:14 -07:00
imageIds_ [ 0 ]. clear ();
imageIds_ [ 1 ]. clear ();
2015-04-07 23:42:38 -04:00
stereoImagePoints_ [ 0 ]. clear ();
stereoImagePoints_ [ 1 ]. clear ();
2024-05-31 10:28:14 -07:00
stereoImageIds_ . clear ();
2024-06-30 17:11:37 -07:00
stereoObjectPoints_ . clear ();
2015-04-07 23:42:38 -04:00
models_ [ 0 ] = CameraModel ();
models_ [ 1 ] = CameraModel ();
2015-04-05 16:42:41 -04:00
stereoModel_ = StereoCameraModel ();
2015-04-08 12:23:10 -04:00
minIrs_ [ 0 ] = 0x0000 ;
maxIrs_ [ 0 ] = 0x7fff ;
minIrs_ [ 1 ] = 0x0000 ;
maxIrs_ [ 1 ] = 0x7fff ;
2014-07-22 22:22:59 +00:00
2024-06-30 17:11:37 -07:00
ui_ -> comboBox_board_type -> setEnabled ( true );
ui_ -> comboBox_marker_dictionary -> setEnabled ( true );
ui_ -> spinBox_boardWidth -> setEnabled ( true );
ui_ -> spinBox_boardHeight -> setEnabled ( true );
ui_ -> doubleSpinBox_squareSize -> setEnabled ( true );
ui_ -> doubleSpinBox_markerLength -> setEnabled ( true );
ui_ -> checkBox_subpixel_refinement -> setEnabled ( true );
ui_ -> doubleSpinBox_subpixel_error -> setEnabled ( true );
ui_ -> checkBox_saveCalibrationData -> setEnabled ( true );
2016-01-19 17:43:33 -05:00
ui_ -> pushButton_calibrate -> setEnabled ( ui_ -> checkBox_unlock -> isChecked ());
2015-04-05 16:42:41 -04:00
ui_ -> pushButton_save -> setEnabled ( false );
2015-04-08 12:23:10 -04:00
ui_ -> radioButton_raw -> setChecked ( true );
ui_ -> radioButton_rectified -> setEnabled ( false );
ui_ -> radioButton_stereoRectified -> setEnabled ( false );
2014-07-22 22:22:59 +00:00
ui_ -> progressBar_count -> reset ();
ui_ -> progressBar_count -> setMaximum ( COUNT_MIN );
ui_ -> progressBar_x -> reset ();
ui_ -> progressBar_y -> reset ();
ui_ -> progressBar_size -> reset ();
ui_ -> progressBar_skew -> reset ();
2015-04-07 23:42:38 -04:00
ui_ -> progressBar_count_2 -> reset ();
ui_ -> progressBar_count_2 -> setMaximum ( COUNT_MIN );
2015-04-05 16:42:41 -04:00
ui_ -> progressBar_x_2 -> reset ();
ui_ -> progressBar_y_2 -> reset ();
ui_ -> progressBar_size_2 -> reset ();
ui_ -> progressBar_skew_2 -> reset ();
ui_ -> label_serial -> clear ();
2014-07-22 22:22:59 +00:00
ui_ -> label_fx -> setNum ( 0 );
ui_ -> label_fy -> setNum ( 0 );
ui_ -> label_cx -> setNum ( 0 );
ui_ -> label_cy -> setNum ( 0 );
2024-05-31 10:28:14 -07:00
ui_ -> label_fovx -> setNum ( 0 );
ui_ -> label_fovy -> setNum ( 0 );
2015-04-05 16:42:41 -04:00
ui_ -> label_baseline -> setNum ( 0 );
2024-06-30 17:11:37 -07:00
ui_ -> label_stereoError -> setNum ( 0 );
2014-07-22 22:22:59 +00:00
ui_ -> label_error -> setNum ( 0 );
2024-05-31 10:28:14 -07:00
ui_ -> label_error_2 -> setNum ( 0 );
2014-07-22 22:22:59 +00:00
ui_ -> lineEdit_K -> clear ();
ui_ -> lineEdit_D -> clear ();
2015-04-05 16:42:41 -04:00
ui_ -> lineEdit_R -> clear ();
ui_ -> lineEdit_P -> clear ();
ui_ -> label_fx_2 -> setNum ( 0 );
ui_ -> label_fy_2 -> setNum ( 0 );
ui_ -> label_cx_2 -> setNum ( 0 );
ui_ -> label_cy_2 -> setNum ( 0 );
2024-06-30 17:11:37 -07:00
ui_ -> label_fovx_2 -> setNum ( 0 );
ui_ -> label_fovy_2 -> setNum ( 0 );
2015-04-05 16:42:41 -04:00
ui_ -> lineEdit_K_2 -> clear ();
ui_ -> lineEdit_D_2 -> clear ();
ui_ -> lineEdit_R_2 -> clear ();
ui_ -> lineEdit_P_2 -> clear ();
2024-06-30 17:11:37 -07:00
chessboardPoints_ . clear ();
chessboardPointIds_ . clear ();
2024-06-30 19:11:14 -07:00
#ifdef HAVE_CHARUCO
markerDictionary_ . release ();
arucoDetectorParams_ . release ();
charucoBoard_ . release ();
2024-06-30 18:15:56 -07:00
if ( ui_ -> comboBox_board_type -> currentIndex () >= 1 )
2024-06-30 17:11:37 -07:00
{
2024-06-30 18:15:56 -07:00
#if CV_MAJOR_VERSION > 4 || (CV_MAJOR_VERSION == 4 && CV_MINOR_VERSION >= 7)
arucoDetectorParams_ . reset ( new cv :: aruco :: DetectorParameters ());
#else
2024-06-30 17:11:37 -07:00
arucoDetectorParams_ = cv :: aruco :: DetectorParameters :: create ();
2024-06-30 18:15:56 -07:00
#endif
2024-06-30 19:11:14 -07:00
#if CV_MAJOR_VERSION > 3 || (CV_MAJOR_VERSION == 3 && CV_MINOR_VERSION >=3)
2024-06-30 17:11:37 -07:00
arucoDetectorParams_ -> cornerRefinementMethod = cv :: aruco :: CORNER_REFINE_CONTOUR ;
2024-06-30 19:11:14 -07:00
#else
arucoDetectorParams_ -> doCornerRefinement = true ;
#endif
2024-06-30 17:11:37 -07:00
int arucoDictionary = ui_ -> comboBox_marker_dictionary -> currentIndex ();
if ( arucoDictionary >= 17 )
{
2024-06-30 19:11:14 -07:00
#if CV_MAJOR_VERSION < 3 || (CV_MAJOR_VERSION == 3 && (CV_MINOR_VERSION <4 || (CV_MINOR_VERSION ==4 && CV_SUBMINOR_VERSION<2)))
2024-06-30 17:11:37 -07:00
UERROR ( "Cannot set AprilTag dictionary. OpenCV version should be at least 3.4.2, "
"current version is %s." , CV_VERSION );
// Dictionary to use:
// DICT_ARUCO_4X4_50=0, DICT_ARUCO_4X4_100=1, DICT_ARUCO_4X4_250=2, DICT_ARUCO_4X4_1000=3,
// DICT_ARUCO_5X5_50=4, DICT_ARUCO_5X5_100=5, DICT_ARUCO_5X5_250=6, DICT_ARUCO_5X5_1000=7,
// DICT_ARUCO_6X6_50=8, DICT_ARUCO_6X6_100=9, DICT_ARUCO_6X6_250=10, DICT_ARUCO_6X6_1000=11,
// DICT_ARUCO_7X7_50=12, DICT_ARUCO_7X7_100=13, DICT_ARUCO_7X7_250=14, DICT_ARUCO_7X7_1000=15,
// DICT_ARUCO_ORIGINAL = 16, DICT_APRILTAG_16h5=17, DICT_APRILTAG_25h9=18, DICT_APRILTAG_36h10=19,
// DICT_APRILTAG_36h11=20
//
arucoDictionary = 0 ;
2024-06-30 19:11:14 -07:00
#else
2024-06-30 17:11:37 -07:00
arucoDetectorParams_ -> cornerRefinementMethod = cv :: aruco :: CORNER_REFINE_APRILTAG ;
#endif
2024-06-30 19:11:14 -07:00
}
2024-06-30 17:11:37 -07:00
#if CV_MAJOR_VERSION > 4 || (CV_MAJOR_VERSION == 4 && CV_MINOR_VERSION >= 7)
2024-06-30 18:15:56 -07:00
markerDictionary_ . reset ( new cv :: aruco :: Dictionary ());
* markerDictionary_ = cv :: aruco :: getPredefinedDictionary ( cv :: aruco :: PredefinedDictionaryType ( arucoDictionary ));
2024-06-30 17:11:37 -07:00
#elif CV_MAJOR_VERSION > 3 || (CV_MAJOR_VERSION == 3 && CV_MINOR_VERSION >=2)
markerDictionary_ = cv :: aruco :: getPredefinedDictionary ( cv :: aruco :: PREDEFINED_DICTIONARY_NAME ( arucoDictionary ));
#else
markerDictionary_ = cv :: aruco :: getPredefinedDictionary ( cv :: aruco :: PREDEFINED_DICTIONARY_NAME ( arucoDictionary ));
#endif
UDEBUG ( "Creating charuco board: %dx%d square=%f marker=%f aruco dict=%d" ,
ui_ -> spinBox_boardWidth -> value (),
ui_ -> spinBox_boardHeight -> value (),
ui_ -> doubleSpinBox_squareSize -> value (),
ui_ -> doubleSpinBox_markerLength -> value (),
arucoDictionary );
2024-06-30 18:15:56 -07:00
#if CV_MAJOR_VERSION > 4 || (CV_MAJOR_VERSION == 4 && CV_MINOR_VERSION >= 7)
charucoBoard_ . reset ( new cv :: aruco :: CharucoBoard (
cv :: Size ( ui_ -> spinBox_boardWidth -> value (), ui_ -> spinBox_boardHeight -> value ()),
ui_ -> doubleSpinBox_squareSize -> value (),
ui_ -> doubleSpinBox_markerLength -> value (),
* markerDictionary_ ));
2024-09-01 03:55:29 -07:00
#if CV_MAJOR_VERSION > 4 || (CV_MAJOR_VERSION == 4 && CV_MINOR_VERSION >= 8)
2024-06-30 18:15:56 -07:00
charucoBoard_ -> setLegacyPattern ( ui_ -> comboBox_board_type -> currentIndex () == 1 );
2024-09-01 03:55:29 -07:00
#endif
2024-08-25 19:35:19 -07:00
arucoDetector_ . reset ( new cv :: aruco :: ArucoDetector ( * markerDictionary_ , * arucoDetectorParams_ ));
charucoDetector_ . reset ( new cv :: aruco :: CharucoDetector ( * charucoBoard_ , cv :: aruco :: CharucoParameters (), * arucoDetectorParams_ ));
2024-06-30 18:15:56 -07:00
#else
2024-06-30 17:11:37 -07:00
charucoBoard_ = cv :: aruco :: CharucoBoard :: create (
ui_ -> spinBox_boardWidth -> value (),
ui_ -> spinBox_boardHeight -> value (),
ui_ -> doubleSpinBox_squareSize -> value (),
ui_ -> doubleSpinBox_markerLength -> value (),
markerDictionary_ );
2024-06-30 18:15:56 -07:00
#endif
2024-06-30 17:11:37 -07:00
}
else //checkerboard
2024-06-30 19:11:14 -07:00
#endif
2024-06-30 17:11:37 -07:00
{
for ( int i = 0 ; i < ui_ -> spinBox_boardHeight -> value (); ++ i ) {
for ( int j = 0 ; j < ui_ -> spinBox_boardWidth -> value (); ++ j ) {
chessboardPoints_ . push_back ( cv :: Point3f ( float ( j * ui_ -> doubleSpinBox_squareSize -> value () ), float ( i * ui_ -> doubleSpinBox_squareSize -> value () ), 0 ));
chessboardPointIds_ . push_back ( i * ui_ -> spinBox_boardWidth -> value () + j );
}
}
}
2024-06-30 18:15:56 -07:00
ui_ -> comboBox_marker_dictionary -> setVisible ( ui_ -> comboBox_board_type -> currentIndex () >= 1 );
ui_ -> doubleSpinBox_markerLength -> setVisible ( ui_ -> comboBox_board_type -> currentIndex () >= 1 );
ui_ -> label_markerDictionary -> setVisible ( ui_ -> comboBox_board_type -> currentIndex () >= 1 );
ui_ -> label_markerLength -> setVisible ( ui_ -> comboBox_board_type -> currentIndex () >= 1 );
2014-07-22 22:22:59 +00:00
}
2016-01-19 17:43:33 -05:00
void CalibrationDialog :: unlock ()
{
ui_ -> pushButton_calibrate -> setEnabled ( true );
}
2014-07-22 22:22:59 +00:00
void CalibrationDialog :: calibrate ()
{
2015-04-05 16:42:41 -04:00
processingData_ = true ;
2015-04-06 00:28:04 -04:00
savedCalibration_ = false ;
2024-06-30 17:11:37 -07:00
ui_ -> comboBox_board_type -> setEnabled ( false );
ui_ -> comboBox_marker_dictionary -> setEnabled ( false );
ui_ -> spinBox_boardWidth -> setEnabled ( false );
ui_ -> spinBox_boardHeight -> setEnabled ( false );
ui_ -> doubleSpinBox_squareSize -> setEnabled ( false );
ui_ -> doubleSpinBox_markerLength -> setEnabled ( false );
ui_ -> checkBox_subpixel_refinement -> setEnabled ( false );
ui_ -> doubleSpinBox_subpixel_error -> setEnabled ( false );
ui_ -> checkBox_saveCalibrationData -> setEnabled ( false );
2015-04-06 00:28:04 -04:00
QMessageBox mb ( QMessageBox :: Information ,
tr ( "Calibrating..." ),
2015-04-07 23:42:38 -04:00
tr ( "Operation in progress..." ));
2015-04-06 00:28:04 -04:00
mb . show ();
QApplication :: processEvents ();
uSleep ( 100 ); // hack make sure the text in the QMessageBox is shown...
QApplication :: processEvents ();
2024-06-30 17:11:37 -07:00
// Logging
QFile logFile ;
QString dummyOutput ;
QTextStream logStream ( & dummyOutput );
if ( ui_ -> checkBox_saveCalibrationData -> isChecked ())
{
logFile . setFileName ( savingDirectory_ + "/" + cameraName_ + "_" + timestamp_ + "/" + "log.txt" );
if ( logFile . open ( QIODevice :: WriteOnly | QIODevice :: Text )) {
logStream . setDevice ( & logFile );
}
}
2015-04-06 00:28:04 -04:00
2024-06-30 17:11:37 -07:00
std :: cout << "Board type = " << ui_ -> comboBox_board_type -> currentIndex () << std :: endl ;
std :: cout << "Board width = " << ui_ -> spinBox_boardWidth -> value () << std :: endl ;
std :: cout << "Board height = " << ui_ -> spinBox_boardHeight -> value () << std :: endl ;
std :: cout << "Square size = " << ui_ -> doubleSpinBox_squareSize -> value () << std :: endl ;
std :: cout << "Subpixel refinement = " << ui_ -> checkBox_subpixel_refinement -> isChecked () << std :: endl ;
std :: cout << "Subpixel max error = " << ui_ -> doubleSpinBox_subpixel_error -> value () << std :: endl ;
logStream << "Board type = " << ui_ -> comboBox_board_type -> currentIndex () << ENDL ;
logStream << "Board width = " << ui_ -> spinBox_boardWidth -> value () << ENDL ;
logStream << "Board height = " << ui_ -> spinBox_boardHeight -> value () << ENDL ;
logStream << "Square size = " << ui_ -> doubleSpinBox_squareSize -> value () << ENDL ;
logStream << "Subpixel refinement = " << ui_ -> checkBox_subpixel_refinement -> isChecked () << ENDL ;
logStream << "Subpixel max error = " << ui_ -> doubleSpinBox_subpixel_error -> value () << ENDL ;
2024-06-30 18:15:56 -07:00
if ( ui_ -> comboBox_board_type -> currentIndex () >= 1 )
2024-06-30 17:11:37 -07:00
{
std :: cout << "Marker dictionary = " << ui_ -> comboBox_marker_dictionary -> currentIndex () << std :: endl ;
std :: cout << "Marker length = " << ui_ -> doubleSpinBox_markerLength -> value () << std :: endl ;
logStream << "Marker dictionary = " << ui_ -> comboBox_marker_dictionary -> currentIndex () << ENDL ;
logStream << "Marker length = " << ui_ -> doubleSpinBox_markerLength -> value () << ENDL ;
}
2014-07-22 22:22:59 +00:00
2015-04-07 23:42:38 -04:00
for ( int id = 0 ; id < ( stereo_ ? 2 : 1 ); ++ id )
2014-07-22 22:22:59 +00:00
{
2015-04-07 23:42:38 -04:00
UINFO ( "Calibrating camera %d (samples=%d)" , id , ( int ) imagePoints_ [ id ]. size ());
2024-06-30 17:11:37 -07:00
logStream << "Calibrating camera " << id << " (samples=" << imagePoints_ [ id ]. size () << ")" << ENDL ;
2015-04-07 23:42:38 -04:00
2026-07-29 22:48:39 -07:00
// Work on local copies: the fisheye auto-prune below removes ill-conditioned views,
// and we must NOT mutate the persistent buffers, otherwise clicking Calibrate again
// would run on a smaller (already-pruned) sample set and give different results.
std :: vector < std :: vector < cv :: Point3f > > objectPoints = objectPoints_ [ id ];
std :: vector < std :: vector < cv :: Point2f > > imagePoints = imagePoints_ [ id ];
std :: vector < int > imageIds = imageIds_ [ id ];
2015-04-05 16:42:41 -04:00
//calibrate
std :: vector < cv :: Mat > rvecs , tvecs ;
std :: vector < float > reprojErrs ;
cv :: Mat K , D ;
K = cv :: Mat :: eye ( 3 , 3 , CV_64FC1 );
2015-04-07 23:42:38 -04:00
UINFO ( "calibrate!" );
2015-04-05 16:42:41 -04:00
//Find intrinsic and extrinsic camera parameters
2018-09-24 14:36:54 -04:00
double rms = 0.0 ;
2018-09-24 15:09:12 -04:00
#if CV_MAJOR_VERSION > 2 or (CV_MAJOR_VERSION == 2 and (CV_MINOR_VERSION >4 or (CV_MINOR_VERSION == 4 and CV_SUBMINOR_VERSION >=10)))
2024-05-31 10:28:14 -07:00
bool fishEye = ui_ -> comboBox_calib_model -> currentIndex () == 0 ;
2018-09-24 15:09:12 -04:00
2018-09-24 14:36:54 -04:00
if ( fishEye )
{
2026-07-29 22:48:39 -07:00
// cv::fisheye::calibrate() with CALIB_CHECK_COND throws as soon as a single
// view is ill-conditioned (e.g. too few / poorly spread ChArUco corners),
// aborting the whole calibration. Auto-prune the offending view (its index is
// reported in the exception message) and retry until it succeeds, keeping the
// CHECK_COND safety without discarding every good view.
const int minFisheyeViews = COUNT_MIN / 2 ;
bool calibrated = false ;
while ( ! calibrated )
2018-09-26 20:51:12 -04:00
{
2026-07-29 22:48:39 -07:00
try
{
rms = cv :: fisheye :: calibrate (
objectPoints ,
imagePoints ,
imageSize_ [ id ],
K ,
D ,
rvecs ,
tvecs ,
cv :: fisheye :: CALIB_RECOMPUTE_EXTRINSIC |
cv :: fisheye :: CALIB_CHECK_COND |
cv :: fisheye :: CALIB_FIX_SKEW );
calibrated = true ;
}
catch ( const cv :: Exception & e )
{
// Parse the ill-conditioned view index, e.g.
// "CALIB_CHECK_COND - Ill-conditioned matrix for input array 43"
int badIndex = - 1 ;
const QString token = "input array " ;
QString msg = e . what ();
int tokenPos = msg . indexOf ( token );
if ( tokenPos >= 0 )
{
bool ok = false ;
int v = msg . mid ( tokenPos + token . length ()). section ( ' ' , 0 , 0 ). toInt ( & ok );
if ( ok )
{
badIndex = v ;
}
}
if ( badIndex >= 0 && badIndex < ( int ) objectPoints . size () &&
( int ) objectPoints . size () > minFisheyeViews )
{
int removedImageId = badIndex < ( int ) imageIds . size () ? imageIds [ badIndex ] : - 1 ;
UWARN ( "Fisheye calibration: view %d (image %d) is ill-conditioned, "
"removing it and retrying (%d views left)." ,
badIndex , removedImageId , ( int ) objectPoints . size () - 1 );
logStream << "Fisheye calibration: removed ill-conditioned view " << badIndex
<< " (image " << removedImageId << "), "
<< ( int ) objectPoints . size () - 1 << " views left" << ENDL ;
// Prune the local copies only (never the persistent buffers). Keep them
// aligned: the per-view reprojection loop below indexes them together
// with rvecs/tvecs.
objectPoints . erase ( objectPoints . begin () + badIndex );
imagePoints . erase ( imagePoints . begin () + badIndex );
if ( badIndex < ( int ) imageIds . size ())
{
imageIds . erase ( imageIds . begin () + badIndex );
}
// loop and retry with the pruned set
}
else
{
UERROR ( "Error: %s (try restarting the calibration)" , e . what ());
QMessageBox :: warning ( this , tr ( "Calibration failed!" ), tr ( "Error: %1 (try restarting the calibration)" ). arg ( e . what ()));
processingData_ = false ;
return ;
}
}
2018-09-26 20:51:12 -04:00
}
2018-09-24 14:36:54 -04:00
}
2018-09-24 15:09:12 -04:00
else
#endif
{
2024-05-31 10:28:14 -07:00
cv :: Mat stdDevsMatInt , stdDevsMatExt ;
cv :: Mat perViewErrorsMat ;
2024-06-30 17:11:37 -07:00
rms = cv :: calibrateCamera (
2026-07-29 22:48:39 -07:00
objectPoints ,
imagePoints ,
2018-09-24 15:09:12 -04:00
imageSize_ [ id ],
K ,
D ,
rvecs ,
2024-05-31 10:28:14 -07:00
tvecs ,
stdDevsMatInt ,
stdDevsMatExt ,
perViewErrorsMat ,
ui_ -> comboBox_calib_model -> currentIndex () == 2 ? cv :: CALIB_RATIONAL_MODEL : 0 );
2026-07-29 22:48:39 -07:00
if (( int ) imageIds . size () == perViewErrorsMat . rows )
2024-05-31 10:28:14 -07:00
{
UINFO ( "Per view errors:" );
2024-06-30 17:11:37 -07:00
logStream << "Per view errors:" << ENDL ;
2024-05-31 10:28:14 -07:00
for ( int i = 0 ; i < perViewErrorsMat . rows ; ++ i )
{
2026-07-29 22:48:39 -07:00
UINFO ( "Image %d: %f" , imageIds [ i ], perViewErrorsMat . at < double > ( i , 0 ));
logStream << "Image " << imageIds [ i ] << ": " << perViewErrorsMat . at < double > ( i , 0 ) << ENDL ;
2024-05-31 10:28:14 -07:00
}
}
2018-09-24 15:09:12 -04:00
}
2015-04-05 16:42:41 -04:00
UINFO ( "Re-projection error reported by calibrateCamera: %f" , rms );
2024-06-30 17:11:37 -07:00
logStream << "Re-projection error reported by calibrateCamera: " << rms << ENDL ;
2015-04-05 16:42:41 -04:00
// compute reprojection errors
std :: vector < cv :: Point2f > imagePoints2 ;
int i , totalPoints = 0 ;
double totalErr = 0 , err ;
2026-07-29 22:48:39 -07:00
reprojErrs . resize ( objectPoints . size ());
2015-04-05 16:42:41 -04:00
2026-07-29 22:48:39 -07:00
for ( i = 0 ; i < ( int ) objectPoints . size (); ++ i )
2015-04-05 16:42:41 -04:00
{
2018-09-24 15:09:12 -04:00
#if CV_MAJOR_VERSION > 2 or (CV_MAJOR_VERSION == 2 and (CV_MINOR_VERSION >4 or (CV_MINOR_VERSION == 4 and CV_SUBMINOR_VERSION >=10)))
2018-09-24 14:36:54 -04:00
if ( fishEye )
{
2026-07-29 22:48:39 -07:00
cv :: fisheye :: projectPoints ( cv :: Mat ( objectPoints [ i ]), imagePoints2 , rvecs [ i ], tvecs [ i ], K , D );
2018-09-24 14:36:54 -04:00
}
else
2018-09-24 15:09:12 -04:00
#endif
2018-09-24 14:36:54 -04:00
{
2026-07-29 22:48:39 -07:00
cv :: projectPoints ( cv :: Mat ( objectPoints [ i ]), rvecs [ i ], tvecs [ i ], K , D , imagePoints2 );
2018-09-24 14:36:54 -04:00
}
2026-07-29 22:48:39 -07:00
err = cv :: norm ( cv :: Mat ( imagePoints [ i ]), cv :: Mat ( imagePoints2 ), cv :: NORM_L2 );
2015-04-05 16:42:41 -04:00
2026-07-29 22:48:39 -07:00
int n = ( int ) objectPoints [ i ]. size ();
2015-04-05 16:42:41 -04:00
reprojErrs [ i ] = ( float ) std :: sqrt ( err * err / n );
totalErr += err * err ;
totalPoints += n ;
}
double totalAvgErr = std :: sqrt ( totalErr / totalPoints );
2015-04-07 23:42:38 -04:00
UINFO ( "avg re projection error = %f" , totalAvgErr );
2024-06-30 17:11:37 -07:00
logStream << "avg re projection error = " << totalAvgErr << ENDL ;
2015-04-05 16:42:41 -04:00
2015-04-07 23:42:38 -04:00
cv :: Mat P ( 3 , 4 , CV_64FC1 );
P . at < double > ( 2 , 3 ) = 1 ;
K . copyTo ( P . colRange ( 0 , 3 ). rowRange ( 0 , 3 ));
2018-09-24 15:09:12 -04:00
#if CV_MAJOR_VERSION > 2 or (CV_MAJOR_VERSION == 2 and (CV_MINOR_VERSION >4 or (CV_MINOR_VERSION == 4 and CV_SUBMINOR_VERSION >=10)))
2018-09-24 14:36:54 -04:00
if ( fishEye )
{
// Convert to unified distortion model (k1,k2,p1,p2,k3,k4)
cv :: Mat newD = cv :: Mat :: zeros ( 1 , 6 , CV_64FC1 );
newD . at < double > ( 0 , 0 ) = D . at < double > ( 0 , 0 );
newD . at < double > ( 0 , 1 ) = D . at < double > ( 0 , 1 );
newD . at < double > ( 0 , 4 ) = D . at < double > ( 0 , 2 );
newD . at < double > ( 0 , 5 ) = D . at < double > ( 0 , 3 );
2018-09-24 15:09:12 -04:00
D = newD ;
2018-09-24 14:36:54 -04:00
}
2018-09-24 15:09:12 -04:00
#endif
2018-09-24 14:36:54 -04:00
2024-06-30 17:11:37 -07:00
models_ [ id ] = CameraModel ( cameraName_ . toStdString (), imageSize_ [ id ], K , D , cv :: Mat :: eye ( 3 , 3 , CV_64FC1 ), P );
2016-05-19 11:40:48 -04:00
std :: cout << "K = " << K << std :: endl ;
std :: cout << "D = " << D << std :: endl ;
2015-04-07 23:42:38 -04:00
std :: cout << "width = " << imageSize_ [ id ]. width << std :: endl ;
std :: cout << "height = " << imageSize_ [ id ]. height << std :: endl ;
2024-06-30 17:11:37 -07:00
UINFO ( "FOV horizontal=%f vertical=%f" , models_ [ id ]. horizontalFOV (), models_ [ id ]. verticalFOV ());
2015-04-07 23:42:38 -04:00
2024-06-30 19:11:14 -07:00
#if CV_MAJOR_VERSION > 3 || (CV_MAJOR_VERSION == 3 && CV_MINOR_VERSION > 2)
2024-06-30 17:11:37 -07:00
std :: string strStream ;
logStream << "K = " << ( strStream << K ). c_str () << ENDL ;
strStream . clear ();
logStream << "D = " << ( strStream << D ). c_str () << ENDL ;
2024-06-30 19:11:14 -07:00
#endif
2024-06-30 17:11:37 -07:00
logStream << "width = " << imageSize_ [ id ]. width << ENDL ;
logStream << "height = " << imageSize_ [ id ]. height << ENDL ;
logStream << "FOV horizontal=" << models_ [ id ]. horizontalFOV () << " vertical=" << models_ [ id ]. verticalFOV () << ENDL ;
2015-04-07 23:42:38 -04:00
if ( id == 0 )
2015-04-05 16:42:41 -04:00
{
2015-04-07 23:42:38 -04:00
ui_ -> label_fx -> setNum ( models_ [ id ]. fx ());
ui_ -> label_fy -> setNum ( models_ [ id ]. fy ());
ui_ -> label_cx -> setNum ( models_ [ id ]. cx ());
ui_ -> label_cy -> setNum ( models_ [ id ]. cy ());
2024-05-31 10:28:14 -07:00
ui_ -> label_fovx -> setNum ( models_ [ id ]. horizontalFOV ());
ui_ -> label_fovy -> setNum ( models_ [ id ]. verticalFOV ());
2015-04-05 16:42:41 -04:00
ui_ -> label_error -> setNum ( totalAvgErr );
std :: stringstream strK , strD , strR , strP ;
2016-05-19 11:40:48 -04:00
strK << models_ [ id ]. K_raw ();
strD << models_ [ id ]. D_raw ();
2015-04-07 23:42:38 -04:00
strR << models_ [ id ]. R ();
strP << models_ [ id ]. P ();
2015-04-05 16:42:41 -04:00
ui_ -> lineEdit_K -> setText ( strK . str (). c_str ());
ui_ -> lineEdit_D -> setText ( strD . str (). c_str ());
ui_ -> lineEdit_R -> setText ( strR . str (). c_str ());
ui_ -> lineEdit_P -> setText ( strP . str (). c_str ());
2015-04-07 23:42:38 -04:00
}
else
{
ui_ -> label_fx_2 -> setNum ( models_ [ id ]. fx ());
ui_ -> label_fy_2 -> setNum ( models_ [ id ]. fy ());
ui_ -> label_cx_2 -> setNum ( models_ [ id ]. cx ());
ui_ -> label_cy_2 -> setNum ( models_ [ id ]. cy ());
2024-05-31 10:28:14 -07:00
ui_ -> label_fovx_2 -> setNum ( models_ [ id ]. horizontalFOV ());
ui_ -> label_fovy_2 -> setNum ( models_ [ id ]. verticalFOV ());
2015-04-07 23:42:38 -04:00
ui_ -> label_error_2 -> setNum ( totalAvgErr );
2015-04-05 16:42:41 -04:00
2015-04-07 23:42:38 -04:00
std :: stringstream strK , strD , strR , strP ;
2016-05-19 11:40:48 -04:00
strK << models_ [ id ]. K_raw ();
strD << models_ [ id ]. D_raw ();
2015-04-07 23:42:38 -04:00
strR << models_ [ id ]. R ();
strP << models_ [ id ]. P ();
ui_ -> lineEdit_K_2 -> setText ( strK . str (). c_str ());
ui_ -> lineEdit_D_2 -> setText ( strD . str (). c_str ());
ui_ -> lineEdit_R_2 -> setText ( strR . str (). c_str ());
ui_ -> lineEdit_P_2 -> setText ( strP . str (). c_str ());
2015-04-05 16:42:41 -04:00
}
}
2015-04-07 23:42:38 -04:00
2016-01-19 21:01:56 -05:00
if ( stereo_ && models_ [ 0 ]. isValidForRectification () && models_ [ 1 ]. isValidForRectification ())
2015-04-05 16:42:41 -04:00
{
2024-06-30 17:11:37 -07:00
stereoModel_ = stereoCalibration ( models_ [ 0 ], models_ [ 1 ], false , & logStream );
2021-02-28 10:31:18 -05:00
if ( stereoModel_ . isValidForProjection () &&
ui_ -> doubleSpinBox_stereoBaseline -> value () > 0 &&
stereoModel_ . baseline () != ui_ -> doubleSpinBox_stereoBaseline -> value ())
{
UWARN ( "Expected stereo baseline is set to %f m, but computed baseline is %f m. Rescaling baseline..." ,
2024-05-31 10:28:14 -07:00
ui_ -> doubleSpinBox_stereoBaseline -> value (), stereoModel_ . baseline ());
2021-02-28 10:31:18 -05:00
cv :: Mat P = stereoModel_ . right (). P (). clone ();
P . at < double > ( 0 , 3 ) = - P . at < double > ( 0 , 0 ) * ui_ -> doubleSpinBox_stereoBaseline -> value ();
2021-03-07 12:27:21 -05:00
double scale = ui_ -> doubleSpinBox_stereoBaseline -> value () / stereoModel_ . baseline ();
2026-07-29 22:48:39 -07:00
UWARN ( "Scale %f applied to stereo baseline (computed %f m -> expected %f m). "
"If the mismatch is caused by the measured square size, it would be %f m instead of %f m." ,
scale , stereoModel_ . baseline (), ui_ -> doubleSpinBox_stereoBaseline -> value (),
ui_ -> doubleSpinBox_squareSize -> value () * scale , ui_ -> doubleSpinBox_squareSize -> value ());
logStream << "Baseline rescaled from " << stereoModel_ . baseline () << " to " << ui_ -> doubleSpinBox_stereoBaseline -> value ()
<< " scale=" << scale << " (implied square size " << ui_ -> doubleSpinBox_squareSize -> value () * scale
<< " m instead of " << ui_ -> doubleSpinBox_squareSize -> value () << " m)" << ENDL ;
UASSERT ( ! stereoModel_ . T (). empty ());
2021-02-28 10:31:18 -05:00
stereoModel_ = StereoCameraModel (
stereoModel_ . name (),
stereoModel_ . left (). imageSize (), stereoModel_ . left (). K_raw (), stereoModel_ . left (). D_raw (), stereoModel_ . left (). R (), stereoModel_ . left (). P (),
stereoModel_ . right (). imageSize (), stereoModel_ . right (). K_raw (), stereoModel_ . right (). D_raw (), stereoModel_ . right (). R (), P ,
2021-03-07 12:27:21 -05:00
stereoModel_ . R (), stereoModel_ . T () * scale , stereoModel_ . E (), stereoModel_ . F (), stereoModel_ . localTransform ());
2021-02-28 10:31:18 -05:00
}
2015-04-07 23:42:38 -04:00
std :: stringstream strR1 , strP1 , strR2 , strP2 ;
strR1 << stereoModel_ . left (). R ();
strP1 << stereoModel_ . left (). P ();
strR2 << stereoModel_ . right (). R ();
strP2 << stereoModel_ . right (). P ();
ui_ -> lineEdit_R -> setText ( strR1 . str (). c_str ());
ui_ -> lineEdit_P -> setText ( strP1 . str (). c_str ());
ui_ -> lineEdit_R_2 -> setText ( strR2 . str (). c_str ());
ui_ -> lineEdit_P_2 -> setText ( strP2 . str (). c_str ());
2015-04-05 16:42:41 -04:00
2024-05-31 10:28:14 -07:00
ui_ -> label_fovx -> setNum ( stereoModel_ . left (). horizontalFOV ());
ui_ -> label_fovx_2 -> setNum ( stereoModel_ . right (). horizontalFOV ());
ui_ -> label_fovy -> setNum ( stereoModel_ . left (). verticalFOV ());
ui_ -> label_fovy_2 -> setNum ( stereoModel_ . right (). verticalFOV ());
2015-04-07 23:42:38 -04:00
ui_ -> label_baseline -> setNum ( stereoModel_ . baseline ());
//ui_->label_error_stereo->setNum(totalAvgErr);
2024-06-30 17:11:37 -07:00
UINFO ( "Baseline=%f FOV horizontal=%f vertical=%f" , stereoModel_ . baseline (), stereoModel_ . left (). horizontalFOV (), stereoModel_ . left (). verticalFOV ());
logStream << "Baseline = " << stereoModel_ . baseline () << ENDL ;
logStream << "Stereo horizontal FOV = " << stereoModel_ . left (). horizontalFOV () << ENDL ;
logStream << "Stereo vertical FOV = " << stereoModel_ . left (). verticalFOV () << ENDL ;
2015-04-07 23:42:38 -04:00
}
2015-04-05 16:42:41 -04:00
2019-05-09 19:20:26 -04:00
if ( stereo_ )
2015-04-07 23:42:38 -04:00
{
2019-05-09 19:20:26 -04:00
if ( models_ [ 0 ]. isValidForRectification ())
{
models_ [ 0 ]. initRectificationMap ();
}
if ( models_ [ 1 ]. isValidForRectification ())
{
models_ [ 1 ]. initRectificationMap ();
}
if ( models_ [ 0 ]. isValidForRectification () || models_ [ 1 ]. isValidForRectification ())
{
ui_ -> radioButton_rectified -> setEnabled ( true );
}
if ( stereoModel_ . isValidForRectification ())
{
stereoModel_ . initRectificationMap ();
ui_ -> radioButton_stereoRectified -> setEnabled ( true );
ui_ -> radioButton_stereoRectified -> setChecked ( true );
ui_ -> pushButton_save -> setEnabled ( true );
2024-06-30 17:11:37 -07:00
if ( ui_ -> checkBox_saveCalibrationData -> isChecked ())
{
stereoModel_ . save (( savingDirectory_ + "/" + cameraName_ + "_" + timestamp_ ). toStdString (), false );
}
2019-05-09 19:20:26 -04:00
}
else
{
ui_ -> radioButton_rectified -> setChecked ( ui_ -> radioButton_rectified -> isEnabled ());
}
2014-07-22 22:22:59 +00:00
}
2016-01-19 17:43:33 -05:00
else if ( models_ [ 0 ]. isValidForRectification ())
2015-04-08 12:23:10 -04:00
{
2016-01-19 17:43:33 -05:00
models_ [ 0 ]. initRectificationMap ();
2015-04-08 12:23:10 -04:00
ui_ -> radioButton_rectified -> setEnabled ( true );
ui_ -> radioButton_rectified -> setChecked ( true );
2019-05-09 19:20:26 -04:00
ui_ -> pushButton_save -> setEnabled ( true );
2024-06-30 17:11:37 -07:00
if ( ui_ -> checkBox_saveCalibrationData -> isChecked ())
{
models_ [ 0 ]. save (( savingDirectory_ + "/" + cameraName_ + "_" + timestamp_ ). toStdString ());
}
2015-04-08 12:23:10 -04:00
}
2014-07-22 22:22:59 +00:00
2015-04-05 16:42:41 -04:00
UINFO ( "End calibration" );
processingData_ = false ;
2024-06-30 17:11:37 -07:00
logFile . close ();
2015-01-19 16:14:49 -05:00
}
2024-06-30 17:11:37 -07:00
StereoCameraModel CalibrationDialog :: stereoCalibration ( const CameraModel & left , const CameraModel & right , bool ignoreStereoRectification , QTextStream * logStream ) const
2016-09-13 18:26:18 -04:00
{
StereoCameraModel output ;
2016-09-30 14:38:45 -04:00
if ( stereoImagePoints_ [ 0 ]. empty ())
2016-09-13 18:26:18 -04:00
{
UERROR ( "No stereo correspondences!" );
return output ;
}
UINFO ( "stereo calibration (samples=%d)..." , ( int ) stereoImagePoints_ [ 0 ]. size ());
2024-06-30 17:11:37 -07:00
if ( logStream ) ( * logStream ) << "stereo calibration (samples=" << stereoImagePoints_ [ 0 ]. size () << ")..." << ENDL ;
2016-09-13 18:26:18 -04:00
2016-09-30 14:38:45 -04:00
if ( left . K_raw (). empty () || left . D_raw (). empty ())
2016-09-13 18:26:18 -04:00
{
2016-09-30 14:38:45 -04:00
UERROR ( "Empty intrinsic parameters (K, D) for the %s camera! Aborting stereo calibration..." , leftSuffix_ . toStdString (). c_str ());
return output ;
2016-09-13 18:26:18 -04:00
}
2016-09-30 14:38:45 -04:00
if ( right . K_raw (). empty () || right . D_raw (). empty ())
2016-09-13 18:26:18 -04:00
{
2016-09-30 14:38:45 -04:00
UERROR ( "Empty intrinsic parameters (K, D) for the %s camera! Aborting stereo calibration..." , rightSuffix_ . toStdString (). c_str ());
return output ;
2016-09-13 18:26:18 -04:00
}
2016-09-30 14:38:45 -04:00
if ( left . imageSize () != imageSize_ [ 0 ])
{
UERROR ( "left model (%dx%d) has not the same size as the processed images (%dx%d)" ,
left . imageSize (). width , left . imageSize (). height ,
imageSize_ [ 0 ]. width , imageSize_ [ 0 ]. height );
return output ;
}
if ( right . imageSize () != imageSize_ [ 1 ])
{
UERROR ( "right model (%dx%d) has not the same size as the processed images (%dx%d)" ,
right . imageSize (). width , right . imageSize (). height ,
imageSize_ [ 1 ]. width , imageSize_ [ 1 ]. height );
return output ;
}
cv :: Size imageSize = imageSize_ [ 0 ]. width > imageSize_ [ 1 ]. width ? imageSize_ [ 0 ] : imageSize_ [ 1 ];
2016-09-13 18:26:18 -04:00
cv :: Mat R , T , E , F ;
2018-09-24 14:36:54 -04:00
double rms = 0.0 ;
2018-09-24 15:09:12 -04:00
#if CV_MAJOR_VERSION > 2 or (CV_MAJOR_VERSION == 2 and (CV_MINOR_VERSION >4 or (CV_MINOR_VERSION == 4 and CV_SUBMINOR_VERSION >=10)))
2018-09-24 14:36:54 -04:00
bool fishEye = left . D_raw (). cols == 6 ;
2016-09-13 18:26:18 -04:00
// calibrate extrinsic
2018-09-24 14:36:54 -04:00
if ( fishEye )
{
2019-05-09 19:20:26 -04:00
cv :: Vec3d Tvec ;
cv :: Vec4d D_left ( left . D_raw (). at < double > ( 0 , 0 ), left . D_raw (). at < double > ( 0 , 1 ), left . D_raw (). at < double > ( 0 , 4 ), left . D_raw (). at < double > ( 0 , 5 ));
cv :: Vec4d D_right ( right . D_raw (). at < double > ( 0 , 0 ), right . D_raw (). at < double > ( 0 , 1 ), right . D_raw (). at < double > ( 0 , 4 ), right . D_raw (). at < double > ( 0 , 5 ));
UASSERT ( stereoImagePoints_ [ 0 ]. size () == stereoImagePoints_ [ 1 ]. size ());
2026-07-29 22:48:39 -07:00
UASSERT ( stereoObjectPoints_ . size () == stereoImagePoints_ [ 0 ]. size ());
// cv::fisheye::stereoCalibrate() reads the number of points from the first view and
// lays out its Jacobian assuming EVERY view has that same count (fisheye.cpp
// "reshape(1, n_points*2)"). ChArUco detects a variable number of corners per view,
// so we make the counts uniform by evenly subsampling every view down to the common
// minimum count (kept spatially spread, not just the first N).
size_t minPoints = stereoImagePoints_ [ 0 ][ 0 ]. size ();
for ( unsigned int i = 0 ; i < stereoImagePoints_ [ 0 ]. size (); ++ i )
{
minPoints = std :: min ( minPoints , stereoImagePoints_ [ 0 ][ i ]. size ());
}
std :: vector < std :: vector < cv :: Point3d > > objectPoints ( stereoObjectPoints_ . size ());
2019-05-09 19:20:26 -04:00
std :: vector < std :: vector < cv :: Point2d > > leftPoints ( stereoImagePoints_ [ 0 ]. size ());
std :: vector < std :: vector < cv :: Point2d > > rightPoints ( stereoImagePoints_ [ 1 ]. size ());
2026-07-29 22:48:39 -07:00
bool subsampled = false ;
2019-05-09 19:20:26 -04:00
for ( unsigned int i = 0 ; i < stereoImagePoints_ [ 0 ]. size (); ++ i )
{
UASSERT ( stereoImagePoints_ [ 0 ][ i ]. size () == stereoImagePoints_ [ 1 ][ i ]. size ());
2026-07-29 22:48:39 -07:00
UASSERT ( stereoObjectPoints_ [ i ]. size () == stereoImagePoints_ [ 0 ][ i ]. size ());
const size_t n = stereoImagePoints_ [ 0 ][ i ]. size ();
if ( n != minPoints )
2019-05-09 19:20:26 -04:00
{
2026-07-29 22:48:39 -07:00
subsampled = true ;
2019-05-09 19:20:26 -04:00
}
2026-07-29 22:48:39 -07:00
objectPoints [ i ]. resize ( minPoints );
leftPoints [ i ]. resize ( minPoints );
rightPoints [ i ]. resize ( minPoints );
for ( size_t k = 0 ; k < minPoints ; ++ k )
{
// evenly spread the kept indices over [0, n-1]
size_t j = minPoints > 1 ? ( size_t )(( k * ( n - 1 )) / ( minPoints - 1 )) : 0 ;
objectPoints [ i ][ k ]. x = stereoObjectPoints_ [ i ][ j ]. x ;
objectPoints [ i ][ k ]. y = stereoObjectPoints_ [ i ][ j ]. y ;
objectPoints [ i ][ k ]. z = stereoObjectPoints_ [ i ][ j ]. z ;
leftPoints [ i ][ k ]. x = stereoImagePoints_ [ 0 ][ i ][ j ]. x ;
leftPoints [ i ][ k ]. y = stereoImagePoints_ [ 0 ][ i ][ j ]. y ;
rightPoints [ i ][ k ]. x = stereoImagePoints_ [ 1 ][ i ][ j ]. x ;
rightPoints [ i ][ k ]. y = stereoImagePoints_ [ 1 ][ i ][ j ]. y ;
}
}
if ( subsampled )
{
UWARN ( "Fisheye stereo calibration requires the same number of points in every "
"view; sub-sampled all %d views to the common minimum of %d points." ,
( int ) stereoImagePoints_ [ 0 ]. size (), ( int ) minPoints );
if ( logStream ) ( * logStream ) << "Fisheye stereo: sub-sampled all views to " << ( int ) minPoints << " points" << ENDL ;
2019-05-09 19:20:26 -04:00
}
try
{
rms = cv :: fisheye :: stereoCalibrate (
2026-07-29 22:48:39 -07:00
objectPoints ,
2019-05-09 19:20:26 -04:00
leftPoints ,
rightPoints ,
left . K_raw (), D_left , right . K_raw (), D_right ,
imageSize , R , Tvec ,
cv :: fisheye :: CALIB_FIX_INTRINSIC ,
cv :: TermCriteria ( cv :: TermCriteria :: COUNT + cv :: TermCriteria :: EPS , 100 , 1e-5 ));
UINFO ( "stereo calibration... done with RMS error=%f" , rms );
}
catch ( const cv :: Exception & e )
{
UERROR ( "Error: %s (try restarting the calibration)" , e . what ());
2026-07-29 22:48:39 -07:00
QMessageBox :: warning ( const_cast < CalibrationDialog *> ( this ), tr ( "Calibration failed!" ), tr ( "Error: %1 (try restarting the calibration)" ). arg ( e . what ()));
2019-05-09 19:20:26 -04:00
return output ;
}
std :: cout << "R = " << R << std :: endl ;
std :: cout << "T = " << Tvec << std :: endl ;
2026-07-29 22:48:39 -07:00
// cv::fisheye::stereoCalibrate() returns the translation as a Vec3d (Tvec) and does
// not fill the cv::Mat T; populate it here so the returned model always carries a
// valid 3x1 extrinsic translation (used e.g. by the baseline rescaling below).
T = cv :: Mat ( 3 , 1 , CV_64FC1 );
T . at < double > ( 0 , 0 ) = Tvec [ 0 ];
T . at < double > ( 1 , 0 ) = Tvec [ 1 ];
T . at < double > ( 2 , 0 ) = Tvec [ 2 ];
2019-05-09 19:20:26 -04:00
if ( imageSize_ [ 0 ] == imageSize_ [ 1 ] && ! ignoreStereoRectification )
{
UINFO ( "Compute stereo rectification" );
cv :: Mat R1 , R2 , P1 , P2 , Q ;
2026-07-29 22:48:39 -07:00
#if CV_MAJOR_VERSION < 5
2019-05-09 19:20:26 -04:00
stereoRectifyFisheye (
left . K_raw (), D_left ,
right . K_raw (), D_right ,
imageSize , R , Tvec , R1 , R2 , P1 , P2 , Q ,
cv :: CALIB_ZERO_DISPARITY , 0 , imageSize );
2026-07-29 22:48:39 -07:00
#else
// Very hard to get good results with this one, however we cannot use the previous one anymore in opencv5
double balance = 0.0 , fov_scale = 1.0 ;
2019-05-09 19:20:26 -04:00
cv :: fisheye :: stereoRectify (
left . K_raw (), D_left ,
right . K_raw (), D_right ,
imageSize , R , Tvec , R1 , R2 , P1 , P2 , Q ,
2026-07-29 22:48:39 -07:00
cv :: CALIB_ZERO_DISPARITY , imageSize , balance , fov_scale );
#endif
2019-05-09 19:20:26 -04:00
std :: cout << "R1 = " << R1 << std :: endl ;
std :: cout << "R2 = " << R2 << std :: endl ;
std :: cout << "P1 = " << P1 << std :: endl ;
std :: cout << "P2 = " << P2 << std :: endl ;
// Re-zoom to original focal distance
if ( P1 . at < double > ( 0 , 0 ) < 0 )
{
P1 . at < double > ( 0 , 0 ) *= - 1 ;
P1 . at < double > ( 1 , 1 ) *= - 1 ;
}
if ( P2 . at < double > ( 0 , 0 ) < 0 )
{
P2 . at < double > ( 0 , 0 ) *= - 1 ;
P2 . at < double > ( 1 , 1 ) *= - 1 ;
}
if ( P2 . at < double > ( 0 , 3 ) > 0 )
{
P2 . at < double > ( 0 , 3 ) *= - 1 ;
}
P2 . at < double > ( 0 , 3 ) = P2 . at < double > ( 0 , 3 ) * left . K_raw (). at < double > ( 0 , 0 ) / P2 . at < double > ( 0 , 0 );
P1 . at < double > ( 0 , 0 ) = P1 . at < double > ( 1 , 1 ) = left . K_raw (). at < double > ( 0 , 0 );
P2 . at < double > ( 0 , 0 ) = P2 . at < double > ( 1 , 1 ) = left . K_raw (). at < double > ( 0 , 0 );
std :: cout << "P1n = " << P1 << std :: endl ;
std :: cout << "P2n = " << P2 << std :: endl ;
output = StereoCameraModel (
cameraName_ . toStdString (),
imageSize_ [ 0 ], left . K_raw (), left . D_raw (), R1 , P1 ,
imageSize_ [ 1 ], right . K_raw (), right . D_raw (), R2 , P2 ,
R , T , E , F );
}
else
{
UDEBUG ( "%s" , cameraName_ . toStdString (). c_str ());
//Kinect, ignore the stereo rectification
output = StereoCameraModel (
cameraName_ . toStdString (),
imageSize_ [ 0 ], left . K_raw (), left . D_raw (), left . R (), left . P (),
imageSize_ [ 1 ], right . K_raw (), right . D_raw (), right . R (), right . P (),
R , T , E , F );
}
2018-09-24 14:36:54 -04:00
}
else
2018-09-24 15:09:12 -04:00
#endif
2018-09-24 14:36:54 -04:00
{
#if CV_MAJOR_VERSION < 3
rms = cv :: stereoCalibrate (
2024-06-30 17:11:37 -07:00
stereoObjectPoints_ ,
2018-09-24 14:36:54 -04:00
stereoImagePoints_ [ 0 ],
stereoImagePoints_ [ 1 ],
left . K_raw (), left . D_raw (),
right . K_raw (), right . D_raw (),
imageSize , R , T , E , F ,
cv :: TermCriteria ( cv :: TermCriteria :: COUNT + cv :: TermCriteria :: EPS , 100 , 1e-5 ),
2024-05-31 10:28:14 -07:00
cv :: CALIB_FIX_INTRINSIC | ( ui_ -> comboBox_calib_model -> currentIndex () == 2 ? cv :: CALIB_RATIONAL_MODEL : 0 ));
2024-06-30 19:11:14 -07:00
#elif CV_MAJOR_VERSION == 3 and (CV_MINOR_VERSION < 4 or (CV_MINOR_VERSION == 4 and CV_SUBMINOR_VERSION < 1))
//OpenCV < 3.4.1
rms = cv :: stereoCalibrate (
stereoObjectPoints_ ,
stereoImagePoints_ [ 0 ],
stereoImagePoints_ [ 1 ],
left . K_raw (), left . D_raw (),
right . K_raw (), right . D_raw (),
imageSize , R , T , E , F ,
cv :: CALIB_FIX_INTRINSIC | ( ui_ -> comboBox_calib_model -> currentIndex () == 2 ? cv :: CALIB_RATIONAL_MODEL : 0 ),
cv :: TermCriteria ( cv :: TermCriteria :: COUNT + cv :: TermCriteria :: EPS , 100 , 1e-5 ));
2018-09-24 14:36:54 -04:00
#else
2024-06-30 17:11:37 -07:00
cv :: Mat perViewErrorsMat ;
2018-09-24 14:36:54 -04:00
rms = cv :: stereoCalibrate (
2024-06-30 17:11:37 -07:00
stereoObjectPoints_ ,
2018-09-24 14:36:54 -04:00
stereoImagePoints_ [ 0 ],
stereoImagePoints_ [ 1 ],
left . K_raw (), left . D_raw (),
right . K_raw (), right . D_raw (),
imageSize , R , T , E , F ,
2024-06-30 17:11:37 -07:00
perViewErrorsMat ,
2024-05-31 10:28:14 -07:00
cv :: CALIB_FIX_INTRINSIC | ( ui_ -> comboBox_calib_model -> currentIndex () == 2 ? cv :: CALIB_RATIONAL_MODEL : 0 ),
2018-09-24 14:36:54 -04:00
cv :: TermCriteria ( cv :: TermCriteria :: COUNT + cv :: TermCriteria :: EPS , 100 , 1e-5 ));
2024-06-30 17:11:37 -07:00
if (( int ) stereoImageIds_ . size () == perViewErrorsMat . rows )
{
UINFO ( "Per stereo view errors: %dx%d" , perViewErrorsMat . rows , perViewErrorsMat . cols );
if ( logStream ) ( * logStream ) << "Per stereo view errors:" << ENDL ;
for ( int i = 0 ; i < perViewErrorsMat . rows ; ++ i )
{
UINFO ( "Image %d: %f <-> %f" , stereoImageIds_ [ i ], perViewErrorsMat . at < double > ( i , 0 ), perViewErrorsMat . at < double > ( i , 1 ));
if ( logStream ) ( * logStream ) << "Image " << stereoImageIds_ [ i ] << ": " << perViewErrorsMat . at < double > ( i , 0 ) << " <-> " << perViewErrorsMat . at < double > ( i , 0 ) << ENDL ;
}
}
2018-09-24 14:36:54 -04:00
#endif
2019-05-09 19:20:26 -04:00
UINFO ( "stereo calibration... done with RMS error=%f" , rms );
2024-06-30 17:11:37 -07:00
if ( logStream ) ( * logStream ) << "stereo calibration... done with RMS error=" << rms << ENDL ;
ui_ -> label_stereoError -> setNum ( rms );
2016-09-13 18:26:18 -04:00
2019-05-09 19:20:26 -04:00
std :: cout << "R = " << R << std :: endl ;
std :: cout << "T = " << T << std :: endl ;
std :: cout << "E = " << E << std :: endl ;
std :: cout << "F = " << F << std :: endl ;
2016-09-13 18:26:18 -04:00
2024-06-30 19:11:14 -07:00
#if CV_MAJOR_VERSION > 3 || (CV_MAJOR_VERSION == 3 && CV_MINOR_VERSION > 2)
2024-06-30 17:11:37 -07:00
std :: string strStream ;
if ( logStream ) ( * logStream ) << "R = " << ( strStream << R ). c_str () << ENDL ;
strStream . clear ();
if ( logStream ) ( * logStream ) << "T = " << ( strStream << T ). c_str () << ENDL ;
strStream . clear ();
if ( logStream ) ( * logStream ) << "E = " << ( strStream << E ). c_str () << ENDL ;
strStream . clear ();
if ( logStream ) ( * logStream ) << "F = " << ( strStream << F ). c_str () << ENDL ;
strStream . clear ();
2024-06-30 19:11:14 -07:00
#endif
2024-06-30 17:11:37 -07:00
2019-05-09 19:20:26 -04:00
if ( imageSize_ [ 0 ] == imageSize_ [ 1 ] && ! ignoreStereoRectification )
2016-09-13 18:26:18 -04:00
{
2019-05-09 19:20:26 -04:00
UINFO ( "Compute stereo rectification" );
cv :: Mat R1 , R2 , P1 , P2 , Q ;
cv :: stereoRectify ( left . K_raw (), left . D_raw (),
right . K_raw (), right . D_raw (),
imageSize , R , T , R1 , R2 , P1 , P2 , Q ,
cv :: CALIB_ZERO_DISPARITY , 0 , imageSize );
std :: cout << "R1 = " << R1 << std :: endl ;
std :: cout << "P1 = " << P1 << std :: endl ;
std :: cout << "R2 = " << R2 << std :: endl ;
std :: cout << "P2 = " << P2 << std :: endl ;
2024-06-30 19:11:14 -07:00
#if CV_MAJOR_VERSION > 3 || (CV_MAJOR_VERSION == 3 && CV_MINOR_VERSION > 2)
2024-06-30 17:11:37 -07:00
if ( logStream ) ( * logStream ) << "R1 = " << ( strStream << R1 ). c_str () << ENDL ;
strStream . clear ();
if ( logStream ) ( * logStream ) << "P1 = " << ( strStream << P1 ). c_str () << ENDL ;
strStream . clear ();
if ( logStream ) ( * logStream ) << "R2 = " << ( strStream << R2 ). c_str () << ENDL ;
strStream . clear ();
if ( logStream ) ( * logStream ) << "P2 = " << ( strStream << P2 ). c_str () << ENDL ;
2024-06-30 19:11:14 -07:00
#endif
2024-06-30 17:11:37 -07:00
2019-05-09 19:20:26 -04:00
double err = 0 ;
int npoints = 0 ;
std :: vector < cv :: Vec3f > lines [ 2 ];
2024-05-31 10:28:14 -07:00
UINFO ( "Computing re-projection errors..." );
2024-06-30 17:11:37 -07:00
if ( logStream ) ( * logStream ) << "Computing re-projection epipolar errors..." << ENDL ;
2019-05-09 19:20:26 -04:00
for ( unsigned int i = 0 ; i < stereoImagePoints_ [ 0 ]. size (); i ++ )
{
int npt = ( int ) stereoImagePoints_ [ 0 ][ i ]. size ();
2016-09-13 18:26:18 -04:00
2026-07-29 22:48:39 -07:00
std :: vector < cv :: Point2f > imgpt0 = stereoImagePoints_ [ 0 ][ i ];
std :: vector < cv :: Point2f > imgpt1 = stereoImagePoints_ [ 1 ][ i ];
2016-09-13 18:26:18 -04:00
cv :: undistortPoints ( imgpt0 , imgpt0 , left . K_raw (), left . D_raw (), R1 , P1 );
cv :: undistortPoints ( imgpt1 , imgpt1 , right . K_raw (), right . D_raw (), R2 , P2 );
computeCorrespondEpilines ( imgpt0 , 1 , F , lines [ 0 ]);
computeCorrespondEpilines ( imgpt1 , 2 , F , lines [ 1 ]);
2024-05-31 10:28:14 -07:00
double sampleErr = 0.0 ;
2019-05-09 19:20:26 -04:00
for ( int j = 0 ; j < npt ; j ++ )
{
2026-07-29 22:48:39 -07:00
double errij = fabs ( imgpt0 [ j ]. x * lines [ 1 ][ j ][ 0 ] +
imgpt0 [ j ]. y * lines [ 1 ][ j ][ 1 ] + lines [ 1 ][ j ][ 2 ]) +
fabs ( imgpt1 [ j ]. x * lines [ 0 ][ j ][ 0 ] +
imgpt1 [ j ]. y * lines [ 0 ][ j ][ 1 ] + lines [ 0 ][ j ][ 2 ]);
2024-05-31 10:28:14 -07:00
sampleErr += errij ;
2019-05-09 19:20:26 -04:00
}
2024-05-31 10:28:14 -07:00
UINFO ( "Stereo image %d: %f" , stereoImageIds_ [ i ], sampleErr / npt );
2024-06-30 17:11:37 -07:00
if ( logStream ) ( * logStream ) << "Stereo image " << stereoImageIds_ [ i ] << ": " << sampleErr / npt << ENDL ;
2024-05-31 10:28:14 -07:00
err += sampleErr ;
2019-05-09 19:20:26 -04:00
npoints += npt ;
2016-09-13 18:26:18 -04:00
}
2019-05-09 19:20:26 -04:00
double totalAvgErr = err / ( double ) npoints ;
UINFO ( "stereo avg re projection error = %f" , totalAvgErr );
2024-06-30 17:11:37 -07:00
if ( logStream ) ( * logStream ) << "stereo avg re projection error = " << totalAvgErr << ENDL ;
2016-09-13 18:26:18 -04:00
2019-05-09 19:20:26 -04:00
output = StereoCameraModel (
cameraName_ . toStdString (),
imageSize_ [ 0 ], left . K_raw (), left . D_raw (), R1 , P1 ,
imageSize_ [ 1 ], right . K_raw (), right . D_raw (), R2 , P2 ,
R , T , E , F );
}
else
{
UDEBUG ( "%s" , cameraName_ . toStdString (). c_str ());
//Kinect, ignore the stereo rectification
output = StereoCameraModel (
cameraName_ . toStdString (),
imageSize_ [ 0 ], left . K_raw (), left . D_raw (), left . R (), left . P (),
imageSize_ [ 1 ], right . K_raw (), right . D_raw (), right . R (), right . P (),
R , T , E , F );
}
2016-09-13 18:26:18 -04:00
}
return output ;
}
2015-04-06 00:28:04 -04:00
bool CalibrationDialog :: save ()
2015-01-19 16:14:49 -05:00
{
2015-04-06 00:28:04 -04:00
bool saved = false ;
2015-04-05 16:42:41 -04:00
processingData_ = true ;
if ( ! stereo_ )
2015-01-19 16:14:49 -05:00
{
2016-01-19 21:01:56 -05:00
UASSERT ( models_ [ 0 ]. isValidForRectification ());
2015-04-07 23:42:38 -04:00
QString cameraName = models_ [ 0 ]. name (). c_str ();
2015-04-06 00:28:04 -04:00
QString filePath = QFileDialog :: getSaveFileName ( this , tr ( "Export" ), savingDirectory_ + "/" + cameraName + ".yaml" , "*.yaml" );
2015-01-19 16:14:49 -05:00
2015-04-05 16:42:41 -04:00
if ( ! filePath . isEmpty ())
{
2015-07-30 14:17:29 -04:00
QString name = QFileInfo ( filePath ). baseName ();
QString dir = QFileInfo ( filePath ). absoluteDir (). absolutePath ();
models_ [ 0 ]. setName ( name . toStdString ());
if ( models_ [ 0 ]. save ( dir . toStdString ()))
2015-04-05 16:42:41 -04:00
{
QMessageBox :: information ( this , tr ( "Export" ), tr ( "Calibration file saved to \" %1 \" ." ). arg ( filePath ));
UINFO ( "Saved \" %s \" !" , filePath . toStdString (). c_str ());
2015-04-06 00:28:04 -04:00
savedCalibration_ = true ;
saved = true ;
2015-04-05 16:42:41 -04:00
}
else
{
UERROR ( "Error saving \" %s \" " , filePath . toStdString (). c_str ());
}
}
2014-07-26 04:36:00 +00:00
}
2015-04-05 16:42:41 -04:00
else
{
2016-01-19 21:01:56 -05:00
UASSERT ( stereoModel_ . left (). isValidForRectification () &&
2018-09-26 20:51:12 -04:00
stereoModel_ . right (). isValidForRectification ());
2015-04-05 16:42:41 -04:00
QString cameraName = stereoModel_ . name (). c_str ();
2015-04-06 00:28:04 -04:00
QString filePath = QFileDialog :: getSaveFileName ( this , tr ( "Export" ), savingDirectory_ + "/" + cameraName , "*.yaml" );
2015-04-06 15:54:19 -04:00
QString name = QFileInfo ( filePath ). baseName ();
QString dir = QFileInfo ( filePath ). absoluteDir (). absolutePath ();
if ( ! name . isEmpty ())
2015-04-05 16:42:41 -04:00
{
2016-09-13 18:26:18 -04:00
bool switched = ui_ -> checkBox_switchImages -> isChecked ();
stereoModel_ . setName ( name . toStdString (), switched ? rightSuffix_ . toStdString () : leftSuffix_ . toStdString (), switched ? leftSuffix_ . toStdString () : rightSuffix_ . toStdString ());
2015-04-06 15:54:19 -04:00
std :: string base = ( dir + QDir :: separator () + name ). toStdString ();
2016-09-13 18:26:18 -04:00
std :: string leftPath = base + "_" + stereoModel_ . getLeftSuffix () + ".yaml" ;
std :: string rightPath = base + "_" + stereoModel_ . getRightSuffix () + ".yaml" ;
2015-04-08 12:23:10 -04:00
std :: string posePath = base + "_pose.yaml" ;
2015-07-30 14:17:29 -04:00
if ( stereoModel_ . save ( dir . toStdString (), false ))
2015-04-05 16:42:41 -04:00
{
2015-04-08 12:23:10 -04:00
QMessageBox :: information ( this , tr ( "Export" ), tr ( "Calibration files saved: \n \" %1 \"\n \" %2 \"\n \" %3 \" ." ).
arg ( leftPath . c_str ()). arg ( rightPath . c_str ()). arg ( posePath . c_str ()));
2015-04-05 16:42:41 -04:00
UINFO ( "Saved \" %s \" and \" %s \" !" , leftPath . c_str (), rightPath . c_str ());
2015-04-06 00:28:04 -04:00
savedCalibration_ = true ;
saved = true ;
2015-04-05 16:42:41 -04:00
}
else
{
UERROR ( "Error saving \" %s \" and \" %s \" " , leftPath . c_str (), rightPath . c_str ());
}
}
}
processingData_ = false ;
2015-04-06 00:28:04 -04:00
return saved ;
2014-07-22 22:22:59 +00:00
}
float CalibrationDialog :: getArea ( const std :: vector < cv :: Point2f > & corners , const cv :: Size & boardSize )
{
//Get 2d image area of the detected checkerboard.
//The projected checkerboard is assumed to be a convex quadrilateral, and the area computed as
//|p X q|/2; see http://mathworld.wolfram.com/Quadrilateral.html.
2024-06-30 17:11:37 -07:00
cv :: Point2f up_left ;
cv :: Point2f up_right ;
cv :: Point2f down_right ;
cv :: Point2f down_left ;
if (( int ) corners . size () == ( boardSize . width * boardSize . height ))
{
up_left = corners [ 0 ];
up_right = corners [ boardSize . width - 1 ];
down_right = corners [ corners . size () - 1 ];
down_left = corners [ corners . size () - boardSize . width ];
}
else
{
cv :: Rect rect = cv :: boundingRect ( corners );
up_left = cv :: Point2f ( rect . x , rect . y );
up_right = cv :: Point2f ( rect . x + rect . width , rect . y );
down_right = cv :: Point2f ( rect . x + rect . width , rect . y + rect . height );
down_left = cv :: Point2f ( rect . x , rect . y + rect . height );
}
2014-07-22 22:22:59 +00:00
cv :: Point2f a = up_right - up_left ;
cv :: Point2f b = down_right - up_right ;
cv :: Point2f c = down_left - down_right ;
cv :: Point2f p = b + c ;
cv :: Point2f q = a + b ;
return std :: fabs ( p . x * q . y - p . y * q . x ) / 2.0f ;
}
2024-06-30 17:11:37 -07:00
float CalibrationDialog :: getSkew ( const std :: vector < cv :: Point2f > & fourCorners )
{
UASSERT ( fourCorners . size () == 4 );
std :: vector < cv :: Point2f > corners = fourCorners ;
corners . resize ( 3 );
return getSkew ( corners , cv :: Size ( 2 , 1 ));
}
2014-07-22 22:22:59 +00:00
float CalibrationDialog :: getSkew ( const std :: vector < cv :: Point2f > & corners , const cv :: Size & boardSize )
{
// Get skew for given checkerboard detection.
// Scaled to [0,1], which 0 = no skew, 1 = high skew
// Skew is proportional to the divergence of three outside corners from 90 degrees.
cv :: Point2f up_left = corners [ 0 ];
cv :: Point2f up_right = corners [ boardSize . width - 1 ];
cv :: Point2f down_right = corners [ corners . size () - 1 ];
// Return angle between lines ab, bc
cv :: Point2f ab = up_left - up_right ;
cv :: Point2f cb = down_right - up_right ;
float angle = std :: acos ( ab . dot ( cb ) / ( cv :: norm ( ab ) * cv :: norm ( cb )));
float r = 2.0f * std :: fabs (( CV_PI / 2.0f ) - angle );
return r > 1.0f ? 1.0f : r ;
}
// x -> [0, 1] (left, right)
// y -> [0, 1] (top, bottom)
// size -> [0, 1] (small -> big)
// skew -> [0, 1] (low, high)
void CalibrationDialog :: getParams ( const std :: vector < cv :: Point2f > & corners , const cv :: Size & boardSize , const cv :: Size & imageSize ,
float & x , float & y , float & size , float & skew )
{
float area = getArea ( corners , boardSize );
size = std :: sqrt ( area / ( imageSize . width * imageSize . height ));
skew = getSkew ( corners , boardSize );
float meanX = 0.0f ;
float meanY = 0.0f ;
for ( unsigned int i = 0 ; i < corners . size (); ++ i )
{
meanX += corners [ i ]. x ;
meanY += corners [ i ]. y ;
}
meanX /= corners . size ();
meanY /= corners . size ();
x = meanX / imageSize . width ;
y = meanY / imageSize . height ;
}
} /* namespace rtabmap */