SLProject  4.2.000
A platform independent 3D computer graphics framework for desktop OS, Android, iOS and online in web browsers
CVCalibration Class Reference

Live video camera calibration class with OpenCV an OpenCV calibration. More...

#include <CVCalibration.h>

Public Member Functions

 CVCalibration (CVCameraType camType, string computerInfos)
 
 CVCalibration (const cv::Mat &cameraMat, const cv::Mat &distortion, cv::Size imageSize, cv::Size boardSize, float boardSquareMM, float reprojectionError, int numCaptured, const string &calibrationTime, int camSizeIndex, bool mirroredH, bool mirroredV, CVCameraType camType, string computerInfos, int calibFlags, bool calcUndistortionMaps)
 
 CVCalibration (const cv::Size &imageSize, float fovH, bool mirroredH, bool mirroredV, CVCameraType camType, string computerInfos)
 
 CVCalibration (float sensorWMM, float sensorHMM, float focalLengthMM, const cv::Size &imageSize, bool mirroredH, bool mirroredV, CVCameraType camType, string computerInfos)
 
bool load (const string &calibDir, const string &calibFileName, bool calcUndistortionMaps)
 Loads the calibration information from the config file. More...
 
bool save (const string &calibDir, const string &calibFileName)
 Saves the camera calibration parameters to the config file. More...
 
void remap (CVMat &inDistorted, CVMat &outUndistorted)
 Undistorts the inDistorted image into the outUndistorted. More...
 
void adaptForNewResolution (const CVSize &newSize, bool calcUndistortionMaps)
 Adapts an already calibrated camera to a new resolution (cropping and scaling) More...
 
void buildUndistortionMaps ()
 Builds undistortion maps after calibration or loading. More...
 
CVSize imageSize () const
 
CVSize imageSizeOriginal () const
 
float imageAspectRatio () const
 
const CVMatcameraMat () const
 
const CVMatcameraMatUndistorted () const
 
const CVMatdistortion () const
 
float cameraFovVDeg () const
 
float cameraFovHDeg () const
 
int calibrationFlags ()
 
bool calibFixPrincipalPoint ()
 
bool calibFixAspectRatio ()
 
bool calibZeroTangentDist ()
 
bool calibRationalModel ()
 
bool calibTiltedModel ()
 
bool calibThinPrismModel ()
 
bool isMirroredH ()
 
bool isMirroredV ()
 
float fx () const
 
float fy () const
 
float cx () const
 
float cy () const
 
float k1 () const
 
float k2 () const
 
float p1 () const
 
float p2 () const
 
float k3 () const
 
float k4 () const
 
float k5 () const
 
float k6 () const
 
float s1 () const
 
float s2 () const
 
float s3 () const
 
float s4 () const
 
float tauX () const
 
float tauY () const
 
CVCameraType camType () const
 
CVCalibState state () const
 
int numCapturedImgs () const
 
float reprojectionError () const
 
CVSize boardSize () const
 
float boardSquareMM () const
 
float boardSquareM () const
 
string calibrationTime () const
 
string calibFileName () const
 
string computerInfos () const
 
string stateStr () const
 

Private Member Functions

void calcCameraFovFromUndistortedCameraMat ()
 Calculates the vertical field of view angle in degrees. More...
 
void calculateUndistortedCameraMat ()
 Calculate a camera matrix that we use for the scene graph and for the reprojection of the undistorted image. More...
 
void createFromGuessedFOV (int imageWidthPX, int imageHeightPX, float fovH)
 Calculates camera intrinsics from a guessed FOV angle. More...
 

Private Attributes

CVMat _cameraMat
 3x3 Matrix for intrinsic camera matrix More...
 
CVMat _distortion
 4x1 Matrix for intrinsic distortion More...
 
CVMat _cameraMatOrig
 3x3 Matrix for intrinsic camera matrix (original from loading or calibration estimation) More...
 
CVSize _imageSizeOrig
 original image size (original from loading or calibration estimation) More...
 
CVCalibState _state = CS_uncalibrated
 calibration state enumeration More...
 
float _cameraFovVDeg = 0.0f
 Vertical field of view in degrees. More...
 
float _cameraFovHDeg = 0.0f
 Horizontal field of view in degrees. More...
 
string _calibFileName
 name for calibration file More...
 
int _calibFlags = 0
 OpenCV calibration flags. More...
 
bool _isMirroredH = false
 Flag if image must be horizontally mirrored. More...
 
bool _isMirroredV = false
 Flag if image must be vertically mirrored. More...
 
int _numCaptured = 0
 NO. of images captured. More...
 
CVSize _boardSize
 NO. of inner chessboard corners. More...
 
float _boardSquareMM = 20.f
 Size of chessboard square in mm. More...
 
float _reprojectionError = -1.0f
 Reprojection error after calibration. More...
 
CVSize _imageSize
 Input image size in pixels (after cropping) More...
 
int _camSizeIndex = -1
 The requested camera size index. More...
 
CVMat _undistortMapX
 Undistortion float map in x-direction. More...
 
CVMat _undistortMapY
 Undistortion float map in y-direction. More...
 
CVMat _cameraMatUndistorted
 Camera matrix that defines scene camera and may also be used for reprojection of undistorted image. More...
 
string _calibrationTime = "-"
 Time stamp string of calibration. More...
 
string _computerInfos
 
CVCameraType _camType = CVCameraType::FRONTFACING
 

Static Private Attributes

static const int _CALIBFILEVERSION = 6
 Global const file format version. More...
 

Detailed Description

Live video camera calibration class with OpenCV an OpenCV calibration.

The camera calibration can determine the inner or intrinsic parameters such as the focal length and the lens distortion and external or extrinsic parameter such as the camera pose towards a known geometry.
For a good calibration we have to make 15-20 images from a chessboard pattern. The chessboard pattern can be printed from the CalibrationChessboard_8x5_A4.pdf in the folder data/calibration. It is important that one side has an odd number of inner corners. Like this it is unambiguous and can be rotated in any direction.
The different calibration states are handled within AppDemoTracking::onUpdateTracking:

  • CS_uncalibrated: The camera is not calibrated (no calibration found found)
  • CS_calibrated: The camera is calibrated
  • CS_guessed
    The core of the intrinsic calibration is stored in the members _cameraMat and _distortion. For the calibration internals see the OpenCV documentation: http://docs.opencv.org/3.1.0/dc/dbb/tutorial_py_calibration.html After a successfully calibration the parameters are stored in a config file on the SL::configPath. If it exists, it is loaded from there at startup. If doesn't exist a simple calibration from a default field of view angle is estimated.
    The CVCapture instance has two video camera calibrations, one for a main camera (CVCapture::mainCam) and one for the selfie camera on mobile devices (CVCapture::scndCam). The member CVCapture::activeCamera points to the active one and is set by the CVCapture::videoType (VT_NONE, VT_MAIN, VT_SCND) during the scene assembly in AppDemoLoad. On mobile devices the front camera is the selfie camera (our secondary) and the back camera is the our main camera.

Definition at line 70 of file CVCalibration.h.

Constructor & Destructor Documentation

◆ CVCalibration() [1/4]

CVCalibration::CVCalibration ( CVCameraType  camType,
string  computerInfos 
)

Definition at line 30 of file CVCalibration.cpp.

32  _cameraFovHDeg(0.0f),
33  _cameraFovVDeg(0.0f),
34  _calibFileName(""), // is set in load
35  _boardSize(0, 0),
36  _boardSquareMM(0.0f),
37  _numCaptured(0),
38  _reprojectionError(-1.0f),
39  _camSizeIndex(-1),
40  _calibrationTime("-"),
41  _isMirroredH(false),
42  _isMirroredV(false),
43  _camType(type),
44  _computerInfos(std::move(computerInfos))
45 {
46 }
@ CS_uncalibrated
The camera is not calibrated (no calibration found)
Definition: CVCalibration.h:32
float _boardSquareMM
Size of chessboard square in mm.
float _cameraFovVDeg
Vertical field of view in degrees.
bool _isMirroredV
Flag if image must be vertically mirrored.
float _reprojectionError
Reprojection error after calibration.
CVCameraType _camType
CVCalibState _state
calibration state enumeration
string _calibFileName
name for calibration file
string _computerInfos
float _cameraFovHDeg
Horizontal field of view in degrees.
string _calibrationTime
Time stamp string of calibration.
int _camSizeIndex
The requested camera size index.
string computerInfos() const
int _numCaptured
NO. of images captured.
bool _isMirroredH
Flag if image must be horizontally mirrored.
CVSize _boardSize
NO. of inner chessboard corners.

◆ CVCalibration() [2/4]

CVCalibration::CVCalibration ( const cv::Mat &  cameraMat,
const cv::Mat &  distortion,
cv::Size  imageSize,
cv::Size  boardSize,
float  boardSquareMM,
float  reprojectionError,
int  numCaptured,
const string &  calibrationTime,
int  camSizeIndex,
bool  mirroredH,
bool  mirroredV,
CVCameraType  camType,
string  computerInfos,
int  calibFlags,
bool  calcUndistortionMaps 
)

Definition at line 49 of file CVCalibration.cpp.

64  : _cameraMat(cameraMat.clone()),
65  _distortion(distortion.clone()),
66  _imageSize(std::move(imageSize)),
67  _boardSize(std::move(boardSize)),
70  _numCaptured(numCaptured),
72  _camSizeIndex(camSizeIndex),
73  _isMirroredH(mirroredH),
74  _isMirroredV(mirroredV),
76  _computerInfos(std::move(computerInfos)),
77  _calibFlags(calibFlags)
78 {
79  _cameraMatOrig = _cameraMat.clone();
81 
86 }
@ CS_calibrated
The camera is calibrated.
Definition: CVCalibration.h:33
void calculateUndistortedCameraMat()
Calculate a camera matrix that we use for the scene graph and for the reprojection of the undistorted...
CVSize boardSize() const
void calcCameraFovFromUndistortedCameraMat()
Calculates the vertical field of view angle in degrees.
CVSize imageSize() const
const CVMat & cameraMat() const
float boardSquareMM() const
const CVMat & distortion() const
CVCameraType camType() const
CVSize _imageSize
Input image size in pixels (after cropping)
float reprojectionError() const
CVMat _distortion
4x1 Matrix for intrinsic distortion
CVMat _cameraMat
3x3 Matrix for intrinsic camera matrix
CVSize _imageSizeOrig
original image size (original from loading or calibration estimation)
string calibrationTime() const
CVMat _cameraMatOrig
3x3 Matrix for intrinsic camera matrix (original from loading or calibration estimation)
void buildUndistortionMaps()
Builds undistortion maps after calibration or loading.
int _calibFlags
OpenCV calibration flags.

◆ CVCalibration() [3/4]

CVCalibration::CVCalibration ( const cv::Size &  imageSize,
float  fovH,
bool  mirroredH,
bool  mirroredV,
CVCameraType  camType,
string  computerInfos 
)

Definition at line 89 of file CVCalibration.cpp.

95  : _isMirroredH(mirroredH),
96  _isMirroredV(mirroredV),
98  _computerInfos(std::move(computerInfos))
99 {
100  createFromGuessedFOV(imageSize.width, imageSize.height, fovH);
101  _cameraMatOrig = _cameraMat.clone();
103 }
void createFromGuessedFOV(int imageWidthPX, int imageHeightPX, float fovH)
Calculates camera intrinsics from a guessed FOV angle.

◆ CVCalibration() [4/4]

CVCalibration::CVCalibration ( float  sensorWMM,
float  sensorHMM,
float  focalLengthMM,
const cv::Size &  imageSize,
bool  mirroredH,
bool  mirroredV,
CVCameraType  camType,
string  computerInfos 
)

Definition at line 106 of file CVCalibration.cpp.

114  : _isMirroredH(mirroredH),
115  _isMirroredV(mirroredV),
116  _camType(camType),
117  _computerInfos(std::move(computerInfos))
118 {
119  // aspect ratio
120  float devFovH = 2.0f * atan(sensorWMM / (2.0f * focalLengthMM)) * Utils::RAD2DEG;
121  if (devFovH > 60.0f && devFovH < 70.0f)
122  {
123  createFromGuessedFOV(imageSize.width, imageSize.height, devFovH);
124  }
125  else
126  {
127  // if not between
128  createFromGuessedFOV(imageSize.width, imageSize.height, 65.0);
129  }
130  _cameraMatOrig = _cameraMat.clone();
132 }
static const float RAD2DEG
Definition: Utils.h:238

Member Function Documentation

◆ adaptForNewResolution()

void CVCalibration::adaptForNewResolution ( const CVSize newSize,
bool  calcUndistortionMaps 
)

Adapts an already calibrated camera to a new resolution (cropping and scaling)

Definition at line 438 of file CVCalibration.cpp.

439 {
440  if (_state == CS_uncalibrated)
441  return;
442 
443  // new center and focal length in pixels not mm
444  float fx, fy, cy, cx;
445 
446  // use original camera matrix for adaptions.
447  // Otherwise we get rounding errors after too many adaptions.
448  float fxOrig = (float)_cameraMatOrig.at<double>(0, 0);
449  float fyOrig = (float)_cameraMatOrig.at<double>(1, 1);
450  float cxOrig = (float)_cameraMatOrig.at<double>(0, 2);
451  float cyOrig = (float)_cameraMatOrig.at<double>(1, 2);
452 
453  if (((float)newSize.width / (float)newSize.height) >
454  ((float)_imageSizeOrig.width / (float)_imageSizeOrig.height))
455  {
456  float scaleFactor = (float)newSize.width / (float)_imageSizeOrig.width;
457 
458  fx = fxOrig * scaleFactor;
459  fy = fyOrig * scaleFactor;
460  float oldHeightScaled = (float)_imageSizeOrig.height * scaleFactor;
461  float heightDiff = (oldHeightScaled - (float)newSize.height) * 0.5f;
462 
463  cx = cxOrig * scaleFactor;
464  cy = cyOrig * scaleFactor - heightDiff;
465  }
466  else
467  {
468  float scaleFactor = (float)newSize.height / (float)_imageSizeOrig.height;
469  fx = fxOrig * scaleFactor;
470  fy = fyOrig * scaleFactor;
471  float oldWidthScaled = (float)_imageSizeOrig.width * scaleFactor;
472  float widthDiff = (oldWidthScaled - (float)newSize.width) * 0.5f;
473 
474  cx = cxOrig * scaleFactor - widthDiff;
475  cy = cyOrig * scaleFactor;
476  }
477 
478  // std::cout << "adaptForNewResolution: _cameraMat before: " << _cameraMat << std::endl;
479  _cameraMat = (cv::Mat_<double>(3, 3) << fx, 0, cx, 0, fy, cy, 0, 0, 1);
480  // std::cout << "adaptForNewResolution: _cameraMat after: " << _cameraMat << std::endl;
481  //_distortion remains unchanged
483 
484  // std::cout << "adaptForNewResolution: _imageSize before: " << _imageSize << std::endl;
485  _imageSize.width = newSize.width;
486  _imageSize.height = newSize.height;
487  // std::cout << "adaptForNewResolution: _imageSize after: " << _imageSize << std::endl;
488 
491  if (calcUndistortionMaps)
493 }
float fx() const
float fy() const
float cx() const
float cy() const
string getDateTime2String()
Returns local time as string like "20190213-154611".
Definition: Utils.cpp:289

◆ boardSize()

CVSize CVCalibration::boardSize ( ) const
inline

Definition at line 170 of file CVCalibration.h.

170 { return _boardSize; }

◆ boardSquareM()

float CVCalibration::boardSquareM ( ) const
inline

Definition at line 172 of file CVCalibration.h.

172 { return _boardSquareMM * 0.001f; }

◆ boardSquareMM()

float CVCalibration::boardSquareMM ( ) const
inline

Definition at line 171 of file CVCalibration.h.

171 { return _boardSquareMM; }

◆ buildUndistortionMaps()

void CVCalibration::buildUndistortionMaps ( )

Builds undistortion maps after calibration or loading.

Definition at line 344 of file CVCalibration.cpp.

345 {
346  if (_cameraMatUndistorted.rows != 3 || _cameraMatUndistorted.cols != 3)
347  Utils::exitMsg("SLProject",
348  "CVCalibration::buildUndistortionMaps: No _cameraMatUndistorted available",
349  __LINE__,
350  __FILE__);
351 
352  // Create undistortion maps
353  _undistortMapX.release();
354  _undistortMapY.release();
355 
356  HighResTimer t;
357  cv::initUndistortRectifyMap(_cameraMat,
358  _distortion,
359  cv::Mat(), // Identity matrix R
361  _imageSize,
362  CV_16SC2, // before we had CV_32FC1 but in all tutorials they use CV_16SC2.. is there a reason?
365 #if _DEBUG
366  Utils::log("CVCalibration",
367  "initUndistortRectifyMap: %fms",
369 #endif
370  if (_undistortMapX.empty() || _undistortMapY.empty())
371  Utils::exitMsg("SLProject",
372  "CVCalibration::buildUndistortionMaps failed.",
373  __LINE__,
374  __FILE__);
375 }
CVMat _undistortMapX
Undistortion float map in x-direction.
CVMat _cameraMatUndistorted
Camera matrix that defines scene camera and may also be used for reprojection of undistorted image.
CVMat _undistortMapY
Undistortion float map in y-direction.
High Resolution Timer class using C++11.
Definition: HighResTimer.h:31
float elapsedTimeInMilliSec()
Definition: HighResTimer.h:38
void exitMsg(const char *tag, const char *msg, const int line, const char *file)
Terminates the application with a message. No leak checking.
Definition: Utils.cpp:1135
void log(const char *tag, const char *format,...)
logs a formatted string platform independently
Definition: Utils.cpp:1103

◆ calcCameraFovFromUndistortedCameraMat()

void CVCalibration::calcCameraFovFromUndistortedCameraMat ( )
private

Calculates the vertical field of view angle in degrees.

Definition at line 562 of file CVCalibration.cpp.

563 {
564  if (_cameraMatUndistorted.rows != 3 || _cameraMatUndistorted.cols != 3)
565  Utils::exitMsg("SLProject", "CVCalibration::calcCameraFovFromSceneCameraMat: No _cameraMatUndistorted available", __LINE__, __FILE__);
566 
567  // calculate vertical field of view
568  float fx = (float)_cameraMatUndistorted.at<double>(0, 0);
569  float fy = (float)_cameraMatUndistorted.at<double>(1, 1);
570  float cx = (float)_cameraMatUndistorted.at<double>(0, 2);
571  float cy = (float)_cameraMatUndistorted.at<double>(1, 2);
572  _cameraFovHDeg = 2.0f * (float)atan2(cx, fx) * Utils::RAD2DEG;
573  _cameraFovVDeg = 2.0f * (float)atan2(cy, fy) * Utils::RAD2DEG;
574 }

◆ calculateUndistortedCameraMat()

void CVCalibration::calculateUndistortedCameraMat ( )
private

Calculate a camera matrix that we use for the scene graph and for the reprojection of the undistorted image.

(The following is the algorithm from cv::getOptimalNewCameraMatrix and the code is here for understanding (it does the same))

Definition at line 496 of file CVCalibration.cpp.

497 {
498  if (_cameraMat.rows != 3 || _cameraMat.cols != 3)
499  Utils::exitMsg("SLProject", "CVCalibration::calculateUndistortedCameraMat: No intrinsic parameter available", __LINE__, __FILE__);
500 
501  // An alpha of 0 leads to no black borders
502  // An alpha of 1 leads to black borders
503  // (with alpha equaly zero the augmentation fits best)
504  double alpha = 1.0;
505 
506  bool centerPrinciplePoint = true;
507  if (centerPrinciplePoint)
508  {
509  // Attention: the principle point has to be centered because for the projection matrix we assume that image plane is "symmetrically arranged wrt the focal plane"
510  //(see http://kgeorge.github.io/2014/03/08/calculating-opengl-perspective-matrix-from-opencv-intrinsic-matrix)
511  //_cameraMatUndistorted = cv::getOptimalNewCameraMatrix(_cameraMat, _distortion, _imageSize, alpha, _imageSize, nullptr, centerPrinciplePoint);
512  //! (The following is the algorithm from cv::getOptimalNewCameraMatrix and the code is here for understanding (it does the same))
513 
514  double cx0 = _cameraMat.at<double>(0, 2);
515  double cy0 = _cameraMat.at<double>(1, 2);
516  double cx = (_imageSize.width) * 0.5;
517  double cy = (_imageSize.height) * 0.5;
518 
519  cv::Rect_<float> inner, outer;
521  _distortion,
522  cv::Mat(),
523  _cameraMat,
524  _imageSize,
525  inner,
526  outer);
527 
528  double s0 = std::max(std::max(std::max((double)cx / (cx0 - inner.x),
529  (double)cy / (cy0 - inner.y)),
530  (double)cx / (inner.x + inner.width - cx0)),
531  (double)cy / (inner.y + inner.height - cy0));
532 
533  double s1 = std::min(std::min(std::min((double)cx / (cx0 - outer.x),
534  (double)cy / (cy0 - outer.y)),
535  (double)cx / (outer.x + outer.width - cx0)),
536  (double)cy / (outer.y + outer.height - cy0));
537 
538  double s = s0 * (1 - alpha) + s1 * alpha;
539 
541  _cameraMatUndistorted.at<double>(0, 0) *= s;
542  _cameraMatUndistorted.at<double>(1, 1) *= s;
543  _cameraMatUndistorted.at<double>(0, 2) = cx;
544  _cameraMatUndistorted.at<double>(1, 2) = cy;
545  }
546  else
547  {
548  _cameraMatUndistorted = cv::getOptimalNewCameraMatrix(_cameraMat,
549  _distortion,
550  _imageSize,
551  alpha,
552  _imageSize,
553  nullptr,
554  centerPrinciplePoint);
555  }
556 
557  // std::cout << "_cameraMatUndistorted: " << _cameraMatUndistorted << std::endl;
558  // std::cout << "_cameraMat: " << _cameraMat << std::endl;
559 }
void getInnerAndOuterRectangles(const cv::Mat &cameraMatrix, const cv::Mat &distCoeffs, const cv::Mat &R, const cv::Mat &newCameraMatrix, const cv::Size &imgSize, cv::Rect_< float > &inner, cv::Rect_< float > &outer)
get inscribed and circumscribed rectangle
float s1() const
The SLScene class represents the top level instance holding the scene structure.
Definition: SLScene.h:47

◆ calibFileName()

string CVCalibration::calibFileName ( ) const
inline

Definition at line 174 of file CVCalibration.h.

174 { return _calibFileName; }

◆ calibFixAspectRatio()

bool CVCalibration::calibFixAspectRatio ( )
inline

Definition at line 139 of file CVCalibration.h.

139 { return _calibFlags & cv::CALIB_FIX_ASPECT_RATIO; }

◆ calibFixPrincipalPoint()

bool CVCalibration::calibFixPrincipalPoint ( )
inline

Definition at line 138 of file CVCalibration.h.

138 { return _calibFlags & cv::CALIB_FIX_PRINCIPAL_POINT; }

◆ calibRationalModel()

bool CVCalibration::calibRationalModel ( )
inline

Definition at line 141 of file CVCalibration.h.

141 { return _calibFlags & cv::CALIB_RATIONAL_MODEL; }

◆ calibrationFlags()

int CVCalibration::calibrationFlags ( )
inline

Definition at line 137 of file CVCalibration.h.

137 { return _calibFlags; }

◆ calibrationTime()

string CVCalibration::calibrationTime ( ) const
inline

Definition at line 173 of file CVCalibration.h.

173 { return _calibrationTime; }

◆ calibThinPrismModel()

bool CVCalibration::calibThinPrismModel ( )
inline

Definition at line 143 of file CVCalibration.h.

143 { return _calibFlags & cv::CALIB_THIN_PRISM_MODEL; }

◆ calibTiltedModel()

bool CVCalibration::calibTiltedModel ( )
inline

Definition at line 142 of file CVCalibration.h.

142 { return _calibFlags & cv::CALIB_TILTED_MODEL; }

◆ calibZeroTangentDist()

bool CVCalibration::calibZeroTangentDist ( )
inline

Definition at line 140 of file CVCalibration.h.

140 { return _calibFlags & cv::CALIB_ZERO_TANGENT_DIST; }

◆ cameraFovHDeg()

float CVCalibration::cameraFovHDeg ( ) const
inline

Definition at line 135 of file CVCalibration.h.

135 { return _cameraFovHDeg; }

◆ cameraFovVDeg()

float CVCalibration::cameraFovVDeg ( ) const
inline

Definition at line 134 of file CVCalibration.h.

134 { return _cameraFovVDeg; }

◆ cameraMat()

const CVMat& CVCalibration::cameraMat ( ) const
inline

Definition at line 131 of file CVCalibration.h.

131 { return _cameraMat; }

◆ cameraMatUndistorted()

const CVMat& CVCalibration::cameraMatUndistorted ( ) const
inline

Definition at line 132 of file CVCalibration.h.

132 { return _cameraMatUndistorted; }

◆ camType()

CVCameraType CVCalibration::camType ( ) const
inline

Definition at line 166 of file CVCalibration.h.

166 { return _camType; }

◆ computerInfos()

string CVCalibration::computerInfos ( ) const
inline

Definition at line 175 of file CVCalibration.h.

175 { return _computerInfos; }

◆ createFromGuessedFOV()

void CVCalibration::createFromGuessedFOV ( int  imageWidthPX,
int  imageHeightPX,
float  fovH 
)
private

Calculates camera intrinsics from a guessed FOV angle.

Most laptop-, webcam- or mobile camera have a horizontal view angle or so called field of view (FOV) of around 65 degrees. From this parameter we can calculate the most important intrinsic parameter the focal length. All other parameters are set as if the lens would be perfect: No lens distortion and the view axis goes through the center of the image. If the focal length and sensor size is provided by the device we deduce the the fovV from it.

Parameters
imageWidthPXHeight of image in pixels
imageHeightPXWidth of image in pixels
fovHAverage horizontal view angle in degrees

Definition at line 407 of file CVCalibration.cpp.

410 {
411  // if (fx == fy) and (cx == imgwidth * 0.5f) and (cy == imgheight * 0.5f)
412  float f = (0.5f * (float)imageWidthPX) / tanf(fovH * 0.5f * Utils::DEG2RAD);
413  float fovV = 2.0f * (float)atan2(0.5f * (float)imageHeightPX, f) * Utils::RAD2DEG;
414 
415  // Create standard camera matrix
416  // fx, fx, cx, cy are all in pixel values not mm
417  // We asume that we have an ideal image sensor with square pixels
418  // so that the focal length fx and fy are identical
419  // See the OpenCV documentation for more details:
420  // http://docs.opencv.org/3.1.0/dc/dbb/tutorial_py_calibration.html
421 
422  float cx = (float)imageWidthPX * 0.5f;
423  float cy = (float)imageHeightPX * 0.5f;
424  float fx = cx / tanf(fovH * 0.5f * Utils::DEG2RAD);
425  float fy = fx;
426 
427  _imageSize.width = imageWidthPX;
428  _imageSize.height = imageHeightPX;
429  _cameraMat = (cv::Mat_<double>(3, 3) << fx, 0, cx, 0, fy, cy, 0, 0, 1);
430  _distortion = (cv::Mat_<double>(5, 1) << 0, 0, 0, 0, 0); // No distortion
431  _cameraFovHDeg = fovH;
432  _cameraFovVDeg = fovV;
434  _state = CS_guessed;
435 }
@ CS_guessed
The camera intrinsics where estimated from FOV.
Definition: CVCalibration.h:34
static const float DEG2RAD
Definition: Utils.h:239

◆ cx()

float CVCalibration::cx ( ) const
inline

Definition at line 149 of file CVCalibration.h.

149 { return _cameraMat.cols == 3 && _cameraMat.rows == 3 ? (float)_cameraMat.at<double>(0, 2) : 0.0f; }

◆ cy()

float CVCalibration::cy ( ) const
inline

Definition at line 150 of file CVCalibration.h.

150 { return _cameraMat.cols == 3 && _cameraMat.rows == 3 ? (float)_cameraMat.at<double>(1, 2) : 0.0f; }

◆ distortion()

const CVMat& CVCalibration::distortion ( ) const
inline

Definition at line 133 of file CVCalibration.h.

133 { return _distortion; }

◆ fx()

float CVCalibration::fx ( ) const
inline

Definition at line 147 of file CVCalibration.h.

147 { return _cameraMat.cols == 3 && _cameraMat.rows == 3 ? (float)_cameraMat.at<double>(0, 0) : 0.0f; }

◆ fy()

float CVCalibration::fy ( ) const
inline

Definition at line 148 of file CVCalibration.h.

148 { return _cameraMat.cols == 3 && _cameraMat.rows == 3 ? (float)_cameraMat.at<double>(1, 1) : 0.0f; }

◆ imageAspectRatio()

float CVCalibration::imageAspectRatio ( ) const
inline

Definition at line 130 of file CVCalibration.h.

130 { return (float)_imageSize.width / (float)_imageSize.height; }

◆ imageSize()

CVSize CVCalibration::imageSize ( ) const
inline

Definition at line 126 of file CVCalibration.h.

126 { return _imageSize; }

◆ imageSizeOriginal()

CVSize CVCalibration::imageSizeOriginal ( ) const
inline

Definition at line 127 of file CVCalibration.h.

127 { return _imageSizeOrig; }

◆ isMirroredH()

bool CVCalibration::isMirroredH ( )
inline

Definition at line 144 of file CVCalibration.h.

144 { return _isMirroredH; }

◆ isMirroredV()

bool CVCalibration::isMirroredV ( )
inline

Definition at line 145 of file CVCalibration.h.

145 { return _isMirroredV; }

◆ k1()

float CVCalibration::k1 ( ) const
inline

Definition at line 151 of file CVCalibration.h.

151 { return _distortion.rows >= 4 ? (float)_distortion.at<double>(0, 0) : 0.0f; }

◆ k2()

float CVCalibration::k2 ( ) const
inline

Definition at line 152 of file CVCalibration.h.

152 { return _distortion.rows >= 4 ? (float)_distortion.at<double>(1, 0) : 0.0f; }

◆ k3()

float CVCalibration::k3 ( ) const
inline

Definition at line 155 of file CVCalibration.h.

155 { return _distortion.rows >= 5 ? (float)_distortion.at<double>(4, 0) : 0.0f; }

◆ k4()

float CVCalibration::k4 ( ) const
inline

Definition at line 156 of file CVCalibration.h.

156 { return _distortion.rows >= 6 ? (float)_distortion.at<double>(5, 0) : 0.0f; }

◆ k5()

float CVCalibration::k5 ( ) const
inline

Definition at line 157 of file CVCalibration.h.

157 { return _distortion.rows >= 7 ? (float)_distortion.at<double>(6, 0) : 0.0f; }

◆ k6()

float CVCalibration::k6 ( ) const
inline

Definition at line 158 of file CVCalibration.h.

158 { return _distortion.rows >= 8 ? (float)_distortion.at<double>(7, 0) : 0.0f; }

◆ load()

bool CVCalibration::load ( const string &  calibDir,
const string &  calibFileName,
bool  calcUndistortionMaps 
)

Loads the calibration information from the config file.

Added a flag to disable calculation of undistortion maps because this may take a lot of time for big images on mobile devices

Definition at line 138 of file CVCalibration.cpp.

141 {
142  // load camera parameter
143  string fullPathAndFilename = Utils::unifySlashes(calibDir) + calibFileName;
144 
145  // try to open the local calibration file
146  cv::FileStorage fs(fullPathAndFilename, cv::FileStorage::READ);
147  if (!fs.isOpened())
148  {
149  Utils::log("SLProject", "Calibration : %s", calibFileName.c_str());
150  Utils::log("SLProject", "Calib. created : No. Calib. will be estimated");
151  _numCaptured = 0;
152  _isMirroredH = false;
153  _isMirroredV = false;
154  _reprojectionError = 0;
155  _calibrationTime = "-";
157  _camSizeIndex = -1;
158  return false;
159  }
160 
161  // Reset if new file format version is available
162  int calibFileVersion = 0;
163  fs["CALIBFILEVERSION"] >> calibFileVersion;
164  if (calibFileVersion < _CALIBFILEVERSION)
165  {
166  _numCaptured = 0;
167  _reprojectionError = -1;
168  _calibrationTime = "-";
170  _camSizeIndex = -1;
171  }
172  else
173  {
174  fs["imageSizeWidth"] >> _imageSize.width;
175  fs["imageSizeHeight"] >> _imageSize.height;
176  fs["numCaptured"] >> _numCaptured;
177  fs["isMirroredH"] >> _isMirroredH;
178  fs["isMirroredV"] >> _isMirroredV;
179  fs["cameraMat"] >> _cameraMat;
180  fs["distortion"] >> _distortion;
181  fs["reprojectionError"] >> _reprojectionError;
182  fs["calibrationTime"] >> _calibrationTime;
183  fs["camSizeIndex"] >> _camSizeIndex;
184  fs["boardSizeWidth"] >> _boardSize.width;
185  fs["boardSizeHeight"] >> _boardSize.height;
186  fs["boardSquareMM"] >> _boardSquareMM;
188  }
189 
190  // estimate computer infos
191  if (!fs["computerInfos"].empty())
192  fs["computerInfos"] >> _computerInfos;
193  else
194  {
195  vector<string> stringParts;
197  if (stringParts.size() >= 3)
198  _computerInfos = stringParts[1];
199  }
200 
201  // close the input file
202  fs.release();
203 
204  // calculate FOV and undistortion maps
205  if (_state == CS_calibrated)
206  {
207  // calcCameraFov();
210  if (calcUndistortionMaps)
212  }
213 
214  Utils::log("SLProject", "Calib. loaded : %s", fullPathAndFilename.c_str());
215  Utils::log("SLProject", "Calib. created : %s", _calibrationTime.c_str());
216  Utils::log("SLProject", "Camera FOV H/V : %3.1f/%3.1f", _cameraFovVDeg, _cameraFovHDeg);
217 
218  _cameraMatOrig = _cameraMat.clone();
220 
221  return true;
222 }
static const int _CALIBFILEVERSION
Global const file format version.
string calibFileName() const
string unifySlashes(const string &inputDir, bool withTrailingSlash)
Returns the inputDir string with unified forward slashes, e.g.: "dirA/dirB/".
Definition: Utils.cpp:368
string getFileNameWOExt(const string &pathFilename)
Returns the filename without extension.
Definition: Utils.cpp:616
void splitString(const string &s, char delimiter, vector< string > &splits)
Splits an input string at a delimiter character into a string vector.
Definition: Utils.cpp:152

◆ numCapturedImgs()

int CVCalibration::numCapturedImgs ( ) const
inline

Definition at line 168 of file CVCalibration.h.

168 { return _numCaptured; }

◆ p1()

float CVCalibration::p1 ( ) const
inline

Definition at line 153 of file CVCalibration.h.

153 { return _distortion.rows >= 4 ? (float)_distortion.at<double>(2, 0) : 0.0f; }

◆ p2()

float CVCalibration::p2 ( ) const
inline

Definition at line 154 of file CVCalibration.h.

154 { return _distortion.rows >= 4 ? (float)_distortion.at<double>(3, 0) : 0.0f; }

◆ remap()

void CVCalibration::remap ( CVMat inDistorted,
CVMat outUndistorted 
)

Undistorts the inDistorted image into the outUndistorted.

Definition at line 378 of file CVCalibration.cpp.

380 {
381  assert(!inDistorted.empty() &&
382  "Input image is empty!");
383 
384  assert(!_undistortMapX.empty() &&
385  !_undistortMapY.empty() &&
386  "Undistortion Maps are empty!");
387 
388  cv::remap(inDistorted,
389  outUndistorted,
392  cv::INTER_LINEAR);
393 }

◆ reprojectionError()

float CVCalibration::reprojectionError ( ) const
inline

Definition at line 169 of file CVCalibration.h.

169 { return _reprojectionError; }

◆ s1()

float CVCalibration::s1 ( ) const
inline

Definition at line 159 of file CVCalibration.h.

159 { return _distortion.rows >= 9 ? (float)_distortion.at<double>(8, 0) : 0.0f; }

◆ s2()

float CVCalibration::s2 ( ) const
inline

Definition at line 160 of file CVCalibration.h.

160 { return _distortion.rows >= 10 ? (float)_distortion.at<double>(9, 0) : 0.0f; }

◆ s3()

float CVCalibration::s3 ( ) const
inline

Definition at line 161 of file CVCalibration.h.

161 { return _distortion.rows >= 11 ? (float)_distortion.at<double>(10, 0) : 0.0f; }

◆ s4()

float CVCalibration::s4 ( ) const
inline

Definition at line 162 of file CVCalibration.h.

162 { return _distortion.rows >= 12 ? (float)_distortion.at<double>(11, 0) : 0.0f; }

◆ save()

bool CVCalibration::save ( const string &  calibDir,
const string &  calibFileName 
)

Saves the camera calibration parameters to the config file.

Definition at line 225 of file CVCalibration.cpp.

227 {
228  string fullPathAndFilename = Utils::unifySlashes(calibDir) + calibFileName;
229 
230  cv::FileStorage fs(fullPathAndFilename, cv::FileStorage::WRITE);
231 
232  if (!fs.isOpened())
233  {
234  Utils::log("SLProject", "Failed to write calib. %s", fullPathAndFilename.c_str());
235  return false;
236  }
237 
238  char buf[1024];
239  snprintf(buf,
240  sizeof(buf),
241  "flags:%s%s%s%s%s%s%s",
242  _calibFlags & cv::CALIB_USE_INTRINSIC_GUESS ? " +use_intrinsic_guess" : "",
243  _calibFlags & cv::CALIB_FIX_ASPECT_RATIO ? " +fix_aspectRatio" : "",
244  _calibFlags & cv::CALIB_FIX_PRINCIPAL_POINT ? " +fix_principal_point" : "",
245  _calibFlags & cv::CALIB_ZERO_TANGENT_DIST ? " +zero_tangent_dist" : "",
246  _calibFlags & cv::CALIB_RATIONAL_MODEL ? " +rational_model" : "",
247  _calibFlags & cv::CALIB_THIN_PRISM_MODEL ? " +thin_prism_model" : "",
248  _calibFlags & cv::CALIB_TILTED_MODEL ? " +tilted_model" : "");
249  fs.writeComment(buf, 0);
250 
251  fs << "CALIBFILEVERSION" << _CALIBFILEVERSION;
252  fs << "calibrationTime" << _calibrationTime;
253  fs << "imageSizeWidth" << _imageSize.width;
254  fs << "imageSizeHeight" << _imageSize.height;
255  fs << "boardSizeWidth" << _boardSize.width; // do not reload
256  fs << "boardSizeHeight" << _boardSize.height; // do not reload
257  fs << "boardSquareMM" << _boardSquareMM; // do not reload
258  fs << "numCaptured" << _numCaptured;
259  fs << "calibFlags" << _calibFlags;
260  fs << "isMirroredH" << _isMirroredH;
261  fs << "isMirroredV" << _isMirroredV;
262  fs << "calibFixAspectRatio" << (_calibFlags & cv::CALIB_FIX_ASPECT_RATIO);
263  fs << "calibFixPrincipalPoint" << (_calibFlags & cv::CALIB_FIX_PRINCIPAL_POINT);
264  fs << "calibZeroTangentDist" << (_calibFlags & cv::CALIB_ZERO_TANGENT_DIST);
265  fs << "calibRationalModel" << (_calibFlags & cv::CALIB_RATIONAL_MODEL);
266  fs << "calibTiltedModel" << (_calibFlags & cv::CALIB_TILTED_MODEL);
267  fs << "calibThinPrismModel" << (_calibFlags & cv::CALIB_THIN_PRISM_MODEL);
268  fs << "cameraMat" << _cameraMat;
269  fs << "distortion" << _distortion;
270  fs << "reprojectionError" << _reprojectionError;
271  fs << "cameraFovVDeg" << _cameraFovVDeg;
272  fs << "cameraFovHDeg" << _cameraFovHDeg;
273  fs << "camSizeIndex" << _camSizeIndex;
274  fs << "computerInfos" << _computerInfos;
275 
276  // close file
277  fs.release();
278  Utils::log("SLProject", "Calib. saved : %s", fullPathAndFilename.c_str());
279  return true;
280  // uploadCalibration(fullPathAndFilename);
281 }

◆ state()

CVCalibState CVCalibration::state ( ) const
inline

Definition at line 167 of file CVCalibration.h.

167 { return _state; }

◆ stateStr()

string CVCalibration::stateStr ( ) const
inline

Definition at line 176 of file CVCalibration.h.

177  {
178  switch (_state)
179  {
180  case CS_uncalibrated: return "CS_uncalibrated";
181  case CS_calibrated: return "CS_calibrated";
182  case CS_guessed: return "CS_guessed";
183  default: return "unknown";
184  }
185  }

◆ tauX()

float CVCalibration::tauX ( ) const
inline

Definition at line 163 of file CVCalibration.h.

163 { return _distortion.rows >= 13 ? (float)_distortion.at<double>(12, 0) : 0.0f; }

◆ tauY()

float CVCalibration::tauY ( ) const
inline

Definition at line 164 of file CVCalibration.h.

164 { return _distortion.rows >= 14 ? (float)_distortion.at<double>(13, 0) : 0.0f; }

Member Data Documentation

◆ _boardSize

CVSize CVCalibration::_boardSize
private

NO. of inner chessboard corners.

Definition at line 210 of file CVCalibration.h.

◆ _boardSquareMM

float CVCalibration::_boardSquareMM = 20.f
private

Size of chessboard square in mm.

Definition at line 211 of file CVCalibration.h.

◆ _calibFileName

string CVCalibration::_calibFileName
private

name for calibration file

Definition at line 204 of file CVCalibration.h.

◆ _CALIBFILEVERSION

const int CVCalibration::_CALIBFILEVERSION = 6
staticprivate

Global const file format version.

Increase the _CALIBFILEVERSION each time you change the file format.

Definition at line 223 of file CVCalibration.h.

◆ _calibFlags

int CVCalibration::_calibFlags = 0
private

OpenCV calibration flags.

Definition at line 205 of file CVCalibration.h.

◆ _calibrationTime

string CVCalibration::_calibrationTime = "-"
private

Time stamp string of calibration.

Definition at line 219 of file CVCalibration.h.

◆ _cameraFovHDeg

float CVCalibration::_cameraFovHDeg = 0.0f
private

Horizontal field of view in degrees.

Definition at line 203 of file CVCalibration.h.

◆ _cameraFovVDeg

float CVCalibration::_cameraFovVDeg = 0.0f
private

Vertical field of view in degrees.

Definition at line 202 of file CVCalibration.h.

◆ _cameraMat

CVMat CVCalibration::_cameraMat
private

3x3 Matrix for intrinsic camera matrix

Definition at line 193 of file CVCalibration.h.

◆ _cameraMatOrig

CVMat CVCalibration::_cameraMatOrig
private

3x3 Matrix for intrinsic camera matrix (original from loading or calibration estimation)

Definition at line 198 of file CVCalibration.h.

◆ _cameraMatUndistorted

CVMat CVCalibration::_cameraMatUndistorted
private

Camera matrix that defines scene camera and may also be used for reprojection of undistorted image.

Definition at line 218 of file CVCalibration.h.

◆ _camSizeIndex

int CVCalibration::_camSizeIndex = -1
private

The requested camera size index.

Definition at line 214 of file CVCalibration.h.

◆ _camType

CVCameraType CVCalibration::_camType = CVCameraType::FRONTFACING
private

Definition at line 221 of file CVCalibration.h.

◆ _computerInfos

string CVCalibration::_computerInfos
private

Definition at line 220 of file CVCalibration.h.

◆ _distortion

CVMat CVCalibration::_distortion
private

4x1 Matrix for intrinsic distortion

Definition at line 194 of file CVCalibration.h.

◆ _imageSize

CVSize CVCalibration::_imageSize
private

Input image size in pixels (after cropping)

Definition at line 213 of file CVCalibration.h.

◆ _imageSizeOrig

CVSize CVCalibration::_imageSizeOrig
private

original image size (original from loading or calibration estimation)

Definition at line 199 of file CVCalibration.h.

◆ _isMirroredH

bool CVCalibration::_isMirroredH = false
private

Flag if image must be horizontally mirrored.

Definition at line 206 of file CVCalibration.h.

◆ _isMirroredV

bool CVCalibration::_isMirroredV = false
private

Flag if image must be vertically mirrored.

Definition at line 207 of file CVCalibration.h.

◆ _numCaptured

int CVCalibration::_numCaptured = 0
private

NO. of images captured.

Definition at line 209 of file CVCalibration.h.

◆ _reprojectionError

float CVCalibration::_reprojectionError = -1.0f
private

Reprojection error after calibration.

Definition at line 212 of file CVCalibration.h.

◆ _state

CVCalibState CVCalibration::_state = CS_uncalibrated
private

calibration state enumeration

Definition at line 201 of file CVCalibration.h.

◆ _undistortMapX

CVMat CVCalibration::_undistortMapX
private

Undistortion float map in x-direction.

Definition at line 216 of file CVCalibration.h.

◆ _undistortMapY

CVMat CVCalibration::_undistortMapY
private

Undistortion float map in y-direction.

Definition at line 217 of file CVCalibration.h.


The documentation for this class was generated from the following files: