5#include <opencv2/imgproc.hpp>
7#include <yarp/os/LogStream.h>
11YARP_LOG_COMPONENT(STEREOCALIBRATIONTHREAD,
"yarp.tools.stereoCalibThread")
16 std::string formatCalibrationMatrix(
const cv::Mat& matrix)
18 std::ostringstream stream;
23 void logCameraCalibration(
const char* cameraName,
26 yCInfo(STEREOCALIBRATIONTHREAD) <<
"[CAMERA_CALIBRATION_" << cameraName <<
"]";
27 yCInfo(STEREOCALIBRATIONTHREAD) <<
"w" << camera.
imageSize.width <<
"h" << camera.
imageSize.height;
28 yCInfo(STEREOCALIBRATIONTHREAD) <<
"fx" << camera.
K.at<
double>(0, 0)
29 <<
"fy" << camera.
K.at<
double>(1, 1)
30 <<
"cx" << camera.
K.at<
double>(0, 2)
31 <<
"cy" << camera.
K.at<
double>(1, 2);
34 yCInfo(STEREOCALIBRATIONTHREAD) <<
"k1" << camera.
D.at<
double>(0, 0)
35 <<
"k2" << camera.
D.at<
double>(1, 0)
36 <<
"k3" << camera.
D.at<
double>(2, 0)
37 <<
"k4" << camera.
D.at<
double>(3, 0);
41 yCInfo(STEREOCALIBRATIONTHREAD) <<
"k1" << camera.
D.at<
double>(0, 0)
42 <<
"k2" << camera.
D.at<
double>(1, 0)
43 <<
"p1" << camera.
D.at<
double>(2, 0)
44 <<
"p2" << camera.
D.at<
double>(3, 0);
46 yCInfo(STEREOCALIBRATIONTHREAD) <<
"K =" << formatCalibrationMatrix(camera.
K);
47 yCInfo(STEREOCALIBRATIONTHREAD) <<
"monocular RMS =" << camera.
rms;
52 yCInfo(STEREOCALIBRATIONTHREAD) <<
"========== Calibration result (not written to disk) ==========";
56 logCameraCalibration(
"LEFT", result.
leftCamera);
65 cv::Mat homogeneousTransform = cv::Mat::eye(4, 4, CV_64F);
66 result.
stereo.
R.copyTo(homogeneousTransform(cv::Rect(0, 0, 3, 3)));
67 result.
stereo.
T.reshape(1, 3).copyTo(homogeneousTransform(cv::Rect(3, 0, 1, 3)));
69 yCInfo(STEREOCALIBRATIONTHREAD) <<
"[STEREO_DISPARITY]";
70 yCInfo(STEREOCALIBRATIONTHREAD) <<
"Stereo RMS =" << result.
stereo.
rms
71 <<
"baseline norm =" << cv::norm(result.
stereo.
T);
72 yCInfo(STEREOCALIBRATIONTHREAD) <<
"R =" << formatCalibrationMatrix(result.
stereo.
R);
73 yCInfo(STEREOCALIBRATIONTHREAD) <<
"T =" << formatCalibrationMatrix(result.
stereo.
T.t());
75 yCInfo(STEREOCALIBRATIONTHREAD) <<
"HN =" << formatCalibrationMatrix(homogeneousTransform);
77 yCInfo(STEREOCALIBRATIONTHREAD) <<
"======================================================================";
82 if(modelString ==
"pinhole")
86 else if(modelString ==
"fisheye")
92 yCError(STEREOCALIBRATIONTHREAD) <<
"Invalid camera model string:" << modelString
93 <<
". Setting to Invalid.";
100 if(modeString ==
"MonocularLeft")
104 else if(modeString ==
"MonocularRight")
108 else if(modeString ==
"MonocularBoth")
112 else if(modeString ==
"StereoFull")
118 yCError(STEREOCALIBRATIONTHREAD) <<
"Invalid calibration mode string:" << modeString
119 <<
". Using default StereoFull.";
128 this->maxQueueSize = maxQueueSize;
136 std::lock_guard<std::mutex> lock(_mutex);
145 frame.
image.copy(leftFrame);
146 frame.
stamp = timestamp;
148 leftQueue.push_back(std::move(frame));
157 frame.
image.copy(rightFrame);
158 frame.
stamp = timestamp;
160 rightQueue.push_back(std::move(frame));
165void StereoPairSynchronizer::trimLeftQueue()
167 while(leftQueue.size() > maxQueueSize)
169 leftQueue.pop_front();
170 std::lock_guard<std::mutex> lock(_mutex);
175void StereoPairSynchronizer::trimRightQueue()
177 while(rightQueue.size() > maxQueueSize)
179 rightQueue.pop_front();
180 std::lock_guard<std::mutex> lock(_mutex);
181 ++stats.droppedRightFrames;
187 while(!leftQueue.empty() && !rightQueue.empty())
189 const double leftStamp = leftQueue.front().stamp.getTime();
190 const double rightStamp = rightQueue.front().stamp.getTime();
192 const double absoluteDelta = std::abs(leftStamp - rightStamp);
193 if(absoluteDelta <= toleranceSeconds)
195 pair.left = std::move(leftQueue.front().image);
196 pair.right = std::move(rightQueue.front().image);
197 pair.leftStamp = leftQueue.front().stamp;
198 pair.rightStamp = rightQueue.front().stamp;
200 pair.timeStampDelta = absoluteDelta;
202 leftQueue.pop_front();
203 rightQueue.pop_front();
205 std::lock_guard<std::mutex> lock(_mutex);
206 ++stats.pairedFrames;
207 stats.accumulatedTimeStampDelta += absoluteDelta;
208 stats.maxTimeStampDelta = std::max(stats.maxTimeStampDelta, absoluteDelta);
213 if(leftStamp < rightStamp)
216 leftQueue.pop_front();
217 std::lock_guard<std::mutex> lock(_mutex);
218 ++stats.droppedLeftFrames;
222 rightQueue.pop_front();
223 std::lock_guard<std::mutex> lock(_mutex);
224 ++stats.droppedRightFrames;
233 moduleName=rf.check(
"name", Value(
"stereoCalib"),
"module name (string)").asString().c_str();
234 robotName=rf.check(
"robotName",Value(
"icub"),
"module name (string)").asString().c_str();
236 this->inputLeftPortName =
"/"+moduleName;
237 this->inputLeftPortName +=rf.check(
"imgLeft",Value(
"/cam/left:i"),
"Input image port (string)").asString().c_str();
239 this->inputRightPortName =
"/"+moduleName;
240 this->inputRightPortName += rf.check(
"imgRight", Value(
"/cam/right:i"),
"Input image port (string)").asString().c_str();
242 this->outNameRight =
"/"+moduleName;
243 this->outNameRight += rf.check(
"outRight",Value(
"/cam/right:o"),
"Output image port (string)").asString().c_str();
245 this->outNameLeft =
"/"+moduleName;
246 this->outNameLeft +=rf.check(
"outLeft",Value(
"/cam/left:o"),
"Output image port (string)").asString().c_str();
248 Bottle stereoCalibOpts=rf.findGroup(
"STEREO_CALIBRATION_CONFIGURATION");
249 this->boardWidth = stereoCalibOpts.check(
"boardWidth", Value(8)).asInt32();
250 this->boardHeight = stereoCalibOpts.check(
"boardHeight", Value(6)).asInt32();
251 this->numOfPairs = stereoCalibOpts.check(
"numberOfPairs", Value(30)).asInt32();
252 if(this->numOfPairs < 30)
254 yCWarning(STEREOCALIBRATIONTHREAD) <<
"numberOfPairs must be at least 30; using 30";
255 this->numOfPairs = 30;
257 this->squareSize = (float)stereoCalibOpts.check(
"boardSize", Value(0.09241)).asFloat64();
258 this->boardType = stereoCalibOpts.check(
"boardType", Value(
"CHESSBOARD")).asString();
259 const double syncToleranceMs = stereoCalibOpts.check(
"syncToleranceMs", Value(20.0)).asFloat64();
260 _syncToleranceSeconds = syncToleranceMs / 1000.0;
261 const int configuredQueueSize = stereoCalibOpts.check(
"syncQueueSize", Value(5)).asInt32();
262 if(configuredQueueSize <= 0)
264 yCWarning(STEREOCALIBRATIONTHREAD) <<
"Invalid syncQueueSize; using 5";
269 _syncQueueSize =
static_cast<std::size_t
>(configuredQueueSize);
272 if(_syncToleranceSeconds <= 0.0)
274 yCWarning(STEREOCALIBRATIONTHREAD) <<
"Invalid syncToleranceMs; using 20 ms";
275 _syncToleranceSeconds = 0.020;
278 synchronizer.configure(_syncToleranceSeconds, _syncQueueSize);
280 this->minCaptureIntervalSeconds = stereoCalibOpts.check(
"minCaptureIntervalSeconds", Value(2.0)).asFloat64();
281 this->minimumBoardSpanRatio = stereoCalibOpts.check(
"minimumBoardSpanRatio", Value(0.15)).asFloat64();
282 this->commandPort=commPort;
283 this->imageDir=imageDir;
284 this->collectionResetRequested.store(
false);
285 this->calibrationState.store(CalibrationState::Idle);
288 this->camCalibFile=rf.getHomeContextPath().c_str();
289 this->standalone = rf.check(
"standalone", Value(
false)).asBool();
290 string fileName=
"outputCalib.ini";
292 this->camCalibFile=this->camCalibFile+
"/"+fileName.c_str();
294 _observationsFile = stereoCalibOpts.check(
295 "observationsFile", Value(
"calibrationObservations.yml")).asString();
296 if(!_observationsFile.empty() && _observationsFile.front() !=
'/')
298 _observationsFile = this->imageDir +
"/" + _observationsFile;
302 _chessboardConfiguration.cornersX = this->boardWidth;
303 _chessboardConfiguration.cornersY = this->boardHeight;
306 _chessboardConfiguration.squareSizeMeters = this->squareSize;
308 _saveImages = stereoCalibOpts.check(
"saveImages", Value(1)).asInt32() != 0;
309 _drawDiagnosticCorners = stereoCalibOpts.check(
"drawDiagnosticCorners", Value(1)).asInt32() != 0;
310 _cameraModel = parseCameraModel(stereoCalibOpts.check(
"cameraModel", Value(
"pinhole")).asString());
311 _calibrationMode = parseCalibrationMode(stereoCalibOpts.check(
"calibrationMode", Value(
"StereoFull")).asString());
313 if(!_chessboardConfiguration.isValid())
315 yCError(STEREOCALIBRATIONTHREAD) <<
"Invalid chessboard configuration";
321 if (!imagePortInLeft.open(inputLeftPortName.c_str())) {
322 cout <<
": unable to open port " << inputLeftPortName << endl;
326 if (!imagePortInRight.open(inputRightPortName.c_str())) {
327 cout <<
": unable to open port " << inputRightPortName << endl;
331 if (!outPortLeft.open(outNameLeft.c_str())) {
332 cout <<
": unable to open port " << outNameLeft << endl;
336 if (!outPortRight.open(outNameRight.c_str())) {
337 cout <<
": unable to open port " << outNameRight << endl;
342 if(standalone)
return true;
348 optHead.put(
"device",
"remote_controlboard");
349 optHead.put(
"remote",(
"/"+robotName+
"/head").c_str());
350 optHead.put(
"local",
"/"+moduleName+
"/client/head");
351 if (!polyHead.open(optHead) ||
352 !polyHead.view(posHead) ||
355 yCError(STEREOCALIBRATIONTHREAD) <<
"Unable to acquire the head encoder interface";
360 optTorso.put(
"device",
"remote_controlboard");
361 optTorso.put(
"remote",(
"/"+robotName+
"/torso").c_str());
362 optTorso.put(
"local",
"/"+moduleName+
"/client/torso");
365 if (!polyTorso.open(optTorso) ||
366 !polyTorso.view(posTorso) ||
369 yCWarning(STEREOCALIBRATIONTHREAD,
"Unable to connect to torso! Continuing without...");
373 yarp::sig::Vector head_angles(6,0.0);
374 posHead->getEncoders(head_angles.data());
376 yarp::sig::Vector torso_angles(3,0.0);
378 posTorso->getEncoders(torso_angles.data());
380 qL.resize(torso_angles.length()+head_angles.length()-1);
381 for(
size_t i=0; i<torso_angles.length(); i++)
382 qL[i]=torso_angles[torso_angles.length()-i-1];
384 for(
size_t i=0; i<head_angles.length()-2; i++)
385 qL[i+torso_angles.length()]=head_angles[i];
386 qL[7]=head_angles[4]+(0.5-(
LEFT))*head_angles[5];
389 qR.resize(torso_angles.length()+head_angles.length()-1);
390 for(
size_t i=0; i<torso_angles.length(); i++)
391 qR[i]=torso_angles[torso_angles.length()-i-1];
393 for(
size_t i=0; i<head_angles.length()-2; i++)
394 qR[i+torso_angles.length()]=head_angles[i];
395 qR[7]=head_angles[4]+(0.5-(
RIGHT))*head_angles[5];
401 yCInfo(STEREOCALIBRATIONTHREAD,
"Running synchronized fisheye calibration pipeline... \n");
405void stereoCalibThread::processSynchronizedPair(
SynchronizedPair& pair, Size boardSize)
408 const double pairTime = 0.5 * (pair.leftStamp.getTime() + pair.rightStamp.getTime());
409 const double previousProcessedCandidateTime = lastProcessedCandidateTime;
410 if(previousProcessedCandidateTime >= 0.0 && (pairTime - previousProcessedCandidateTime) < minCaptureIntervalSeconds)
412 yCDebug(STEREOCALIBRATIONTHREAD) <<
"Skipping candidate pair due to minimum capture interval";
415 if(previousProcessedCandidateTime >= 0.0)
417 yCDebug(STEREOCALIBRATIONTHREAD) <<
"Timestamp delta between processed pairs:" << (pairTime - previousProcessedCandidateTime) <<
"seconds";
419 lastProcessedCandidateTime = pairTime;
424 const Size leftSize(pair.
left.width(), pair.
left.height());
425 const Size rightSize(pair.
right.width(), pair.
right.height());
427 if(leftSize != _expectedImageSize || rightSize != _expectedImageSize)
429 if(_expectedImageSize.empty())
431 _expectedImageSize = leftSize;
435 if(leftSize != _expectedImageSize || rightSize != _expectedImageSize)
437 yCError(STEREOCALIBRATIONTHREAD) <<
"Left and right images have different sizes:" <<
438 "Left:" << leftSize.width <<
"x" << leftSize.height <<
439 "Right:" << rightSize.width <<
"x" << rightSize.height;
441 std::lock_guard<std::mutex> lock(mtx);
442 _calibrationError =
"Input images do not match the expected calibration resolution.";
443 _calibrationResults = stereo_calib::CalibrationResult{};
445 calibrationState.store(CalibrationState::Error);
450 LeftRgb=yarp::cv::toCvMat(pair.
left);
451 RightRgb=yarp::cv::toCvMat(pair.
right);
454 Mat leftGray, rightGray;
455 cvtColor(LeftRgb,leftGray,cv::COLOR_RGB2GRAY);
456 cvtColor(RightRgb,rightGray,cv::COLOR_RGB2GRAY);
458 std::vector<Point2f> leftCorners;
459 std::vector<Point2f> rightCorners;
462 if(boardType ==
"CIRCLES_GRID") {
463 foundL = findCirclesGrid(LeftRgb, boardSize, leftCorners, CALIB_CB_SYMMETRIC_GRID | CALIB_CB_CLUSTERING);
464 foundR = findCirclesGrid(RightRgb, boardSize, rightCorners, CALIB_CB_SYMMETRIC_GRID | CALIB_CB_CLUSTERING);
465 yCWarning(STEREOCALIBRATIONTHREAD) <<
"Board type:" << boardType <<
"not yet implemented.";
466 }
else if(boardType ==
"ASYMMETRIC_CIRCLES_GRID") {
467 foundL = findCirclesGrid(LeftRgb, boardSize, leftCorners, CALIB_CB_ASYMMETRIC_GRID | CALIB_CB_CLUSTERING);
468 foundR = findCirclesGrid(RightRgb, boardSize, rightCorners, CALIB_CB_ASYMMETRIC_GRID | CALIB_CB_CLUSTERING);
469 yCWarning(STEREOCALIBRATIONTHREAD) <<
"Board type:" << boardType <<
"not yet implemented.";
470 }
else if(boardType ==
"CHESSBOARD_SECTOR_BASED") {
471 foundL = findChessboardCornersSB(leftGray, boardSize, leftCorners);
472 foundR = findChessboardCornersSB(rightGray, boardSize, rightCorners);
473 yCWarning(STEREOCALIBRATIONTHREAD) <<
"Board type:" << boardType <<
"not yet implemented.";
475 foundL = findChessboardCorners(leftGray, boardSize, leftCorners, CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_NORMALIZE_IMAGE | CALIB_CB_FILTER_QUADS);
476 foundR = findChessboardCorners(rightGray, boardSize, rightCorners, CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_NORMALIZE_IMAGE | CALIB_CB_FILTER_QUADS);
481 yCDebug(STEREOCALIBRATIONTHREAD) <<
"Found calibration board corners in both left and right images";
483 const Rect leftBoardBounds = boundingRect(leftCorners);
484 const Rect rightBoardBounds = boundingRect(rightCorners);
485 const bool leftBoardTooSmall =
486 leftBoardBounds.width < leftSize.width * minimumBoardSpanRatio ||
487 leftBoardBounds.height < leftSize.height * minimumBoardSpanRatio;
488 const bool rightBoardTooSmall =
489 rightBoardBounds.width < rightSize.width * minimumBoardSpanRatio ||
490 rightBoardBounds.height < rightSize.height * minimumBoardSpanRatio;
492 if(leftBoardTooSmall || rightBoardTooSmall)
494 yCWarning(STEREOCALIBRATIONTHREAD) <<
"Skipping stereo pair: chessboard is too small."
495 <<
"Left board:" << leftBoardBounds.width <<
"x" << leftBoardBounds.height
496 <<
"of" << leftSize.width <<
"x" << leftSize.height <<
";"
497 <<
"right board:" << rightBoardBounds.width <<
"x" << rightBoardBounds.height
498 <<
"of" << rightSize.width <<
"x" << rightSize.height <<
"."
499 <<
"Each board must span at least" << (minimumBoardSpanRatio * 100.0)
500 <<
"% of both image dimensions.";
502 ++_rejectedDetections;
506 TermCriteria criteria = TermCriteria(TermCriteria::EPS+TermCriteria::COUNT, 30, 0.01);
507 cornerSubPix(leftGray, leftCorners, Size(5,5), Size(-1,-1), criteria);
508 cornerSubPix(rightGray, rightCorners, Size(5,5), Size(-1,-1), criteria);
512 stereo_calib::StereoObservation observation;
515 observation.
objectPoints = _chessboardConfiguration.createObjectPoints();
528 yCError(STEREOCALIBRATIONTHREAD) <<
"Generated invalid stereo observation";
529 ++_rejectedDetections;
533 std::size_t observationIndex = 0;
534 observationIndex = _observations.size();
540 std::string imageError;
541 if(!_calibrationWriter.writeImagePair(imageDir, observationIndex,
547 yCError(STEREOCALIBRATIONTHREAD) <<
"Could not save accepted calibration image pair:" << imageError;
549 std::lock_guard<std::mutex> lock(mtx);
550 if (calibrationState.load() != CalibrationState::Collecting)
555 _calibrationError = imageError;
556 _calibrationResults = stereo_calib::CalibrationResult{};
557 calibrationState.store(CalibrationState::Error);
565 std::lock_guard<std::mutex> lock(mtx);
566 if (calibrationState.load() != CalibrationState::Collecting)
570 _observations.push_back(std::move(observation));
575 if(_drawDiagnosticCorners)
577 drawChessboardCorners(LeftRgb, boardSize, leftCorners, foundL);
578 drawChessboardCorners(RightRgb, boardSize, rightCorners, foundR);
581 ImageOf<PixelRgb>& outimL = outPortLeft.prepare();
586 ImageOf<PixelRgb>& outimR = outPortRight.prepare();
589 outPortRight.write();
594 ++_rejectedDetections;
604 std::lock_guard<std::mutex> lock(mtx);
606 switch(calibrationState.load())
608 case CalibrationState::Idle:
609 result.
state =
"Idle";
611 case CalibrationState::Collecting:
612 result.
state =
"Collecting";
614 case CalibrationState::Calibrating:
615 result.
state =
"Calibrating";
617 case CalibrationState::Completed:
618 result.
state =
"Completed";
620 case CalibrationState::Error:
621 result.
state =
"Error";
625 const auto syncStats = synchronizer.getStatistics();
631 if(syncStats.pairedFrames > 0)
633 result.
meanTimestampDeltaMs = 1000.0 * syncStats.accumulatedTimeStampDelta /
static_cast<double>(syncStats.pairedFrames);
639 if(calibrationState.load() == CalibrationState::Completed && _calibrationResults.isValid())
642 switch(_calibrationResults.mode)
658 if(_calibrationResults.leftCamera.isValid())
662 if(_calibrationResults.rightCamera.isValid())
666 if(_calibrationResults.stereo.isValid())
668 result.
stereoRms = _calibrationResults.stereo.rms;
669 result.
baselineNorm = _calibrationResults.quality.baseline;
676bool stereoCalibThread::shouldQueueFrameForCollection(
const Stamp& timestamp)
const
678 return lastProcessedCandidateTime < 0.0 ||
679 (timestamp.getTime() - lastProcessedCandidateTime) >= minCaptureIntervalSeconds;
682void stereoCalibThread::stereoCalibRun()
685 boardSize.width=this->boardWidth;
686 boardSize.height=this->boardHeight;
688 while (!isStopping())
693 if(calibrationState.load() == CalibrationState::Error)
699 if(collectionResetRequested.exchange(
false))
701 synchronizer.reset();
702 lastProcessedCandidateTime = -1.0;
703 _expectedImageSize = {};
704 _observations.clear();
705 _rejectedDetections = 0;
707 std::lock_guard<std::mutex> lock(mtx);
708 _calibrationResults = stereo_calib::CalibrationResult{};
709 _calibrationError.clear();
713 bool areFramesReceived =
false;
714 ImageOf<PixelRgb> *tmpL = imagePortInLeft.read(
false);
718 areFramesReceived =
true;
721 imagePortInLeft.getEnvelope(TSLeft);
724 ImageOf<PixelRgb>& outimL = outPortLeft.prepare();
726 outPortLeft.setEnvelope(TSLeft);
730 if(calibrationState.load() == CalibrationState::Collecting &&
731 shouldQueueFrameForCollection(TSLeft))
733 synchronizer.pushLeft(*tmpL, TSLeft);
737 ImageOf<PixelRgb> *tmpR = imagePortInRight.read(
false);
740 areFramesReceived =
true;
743 imagePortInRight.getEnvelope(TSRight);
746 ImageOf<PixelRgb>& outimR=outPortRight.prepare();
748 outPortRight.setEnvelope(TSRight);
749 outPortRight.write();
753 if(calibrationState.load() == CalibrationState::Collecting &&
754 shouldQueueFrameForCollection(TSRight))
756 synchronizer.pushRight(*tmpR, TSRight);
760 std::vector<stereo_calib::StereoObservation> observationSnapshot;
762 if(calibrationState.load() == CalibrationState::Collecting)
764 SynchronizedPair pair;
765 while(calibrationState.load() == CalibrationState::Collecting &&
766 synchronizer.tryPopPair(pair))
769 processSynchronizedPair(pair, boardSize);
771 if(calibrationState.load() != CalibrationState::Collecting)
775 if(_observations.size() >=
static_cast<std::size_t
>(numOfPairs))
777 yCInfo(STEREOCALIBRATIONTHREAD,
"Collected %zu valid stereo observations. Stopping collection.", _observations.size());
778 observationSnapshot = _observations;
779 calibrationState.store(CalibrationState::Calibrating);
780 yCInfo(STEREOCALIBRATIONTHREAD) <<
"Observation collection complete";
786 if(calibrationState.load() == CalibrationState::Calibrating)
788 yCInfo(STEREOCALIBRATIONTHREAD) <<
"Starting the calibration process";
789 if(observationSnapshot.empty())
791 observationSnapshot = _observations;
794 stereo_calib::CalibrationResult calibrationResult;
795 std::string calibrationError;
796 bool success =
false;
799 stereo_calib::PinholeCalibrationOptions options = _pinholeCalibrationOptions;
802 success = _pinholeCalibrationEngine.calibrate(
811 stereo_calib::FisheyeCalibrationOptions options = _fisheyeCalibrationOptions;
815 success = _fisheyeCalibrationEngine.calibrate(
824 calibrationError =
"Unsupported camera model.";
834 yCError(STEREOCALIBRATIONTHREAD) <<
"Calibration failed:" << calibrationError;
836 std::lock_guard<std::mutex> lock(mtx);
837 _calibrationResults = stereo_calib::CalibrationResult{};
838 _calibrationError = calibrationError.empty()
839 ?
"Calibration failed without an error message."
842 calibrationState.store(CalibrationState::Error);
846 const auto syncStats = synchronizer.getStatistics();
850 if(syncStats.pairedFrames > 0)
852 calibrationResult.
quality.
meanTimestampDeltaMs = 1000.0 * syncStats.accumulatedTimeStampDelta /
static_cast<double>(syncStats.pairedFrames);
857 std::string persistenceError;
858 if(!_calibrationWriter.write(camCalibFile, calibrationResult, persistenceError))
860 yCError(STEREOCALIBRATIONTHREAD) <<
"Could not save calibration results:" << persistenceError;
862 std::lock_guard<std::mutex> lock(mtx);
863 _calibrationResults = std::move(calibrationResult);
864 _calibrationError = persistenceError;
866 calibrationState.store(CalibrationState::Error);
869 if(!_calibrationWriter.writeObservations(_observationsFile, observationSnapshot, persistenceError))
871 yCError(STEREOCALIBRATIONTHREAD) <<
"Could not save calibration observations:" << persistenceError;
873 std::lock_guard<std::mutex> lock(mtx);
874 _calibrationResults = std::move(calibrationResult);
875 _calibrationError = persistenceError;
877 calibrationState.store(CalibrationState::Error);
881 logCalibrationResult(calibrationResult);
883 std::lock_guard<std::mutex> lock(mtx);
884 _calibrationResults = std::move(calibrationResult);
885 _calibrationError.clear();
888 calibrationState.store(CalibrationState::Completed);
889 yCInfo(STEREOCALIBRATIONTHREAD) <<
"Entire calibration process completed";
892 if(!areFramesReceived)
902 imagePortInRight.close();
903 imagePortInLeft.close();
905 outPortRight.close();
906 commandPort->close();
908 if (polyHead.isValid())
911 if (polyTorso.isValid())
917 calibrationState.store(CalibrationState::Idle);
918 collectionResetRequested.store(
false);
919 imagePortInRight.interrupt();
920 imagePortInLeft.interrupt();
921 outPortLeft.interrupt();
922 outPortRight.interrupt();
923 commandPort->interrupt();
928 std::lock_guard<std::mutex> lock(mtx);
930 const CalibrationState currentState = calibrationState.load();
932 if(currentState == CalibrationState::Collecting || currentState == CalibrationState::Calibrating)
934 yCWarning(STEREOCALIBRATIONTHREAD) <<
"Cannot start a new calibration while calibration is already running";
939 _calibrationError.clear();
940 calibrationState.store(CalibrationState::Collecting);
941 collectionResetRequested.store(
true);
943 yCInfo(STEREOCALIBRATIONTHREAD) <<
"Calibration collection started";
947 std::lock_guard<std::mutex> lock(mtx);
949 if(calibrationState.load() != CalibrationState::Collecting)
951 yCWarning(STEREOCALIBRATIONTHREAD) <<
"Cannot stop calibration collection when it is not running";
954 calibrationState.store(CalibrationState::Idle);
955 collectionResetRequested.store(
true);
957 yCInfo(STEREOCALIBRATIONTHREAD) <<
"Calibration collection stopped";
constexpr double tolerance
void configure(double tolerance, std::size_t maxQueueSize)
void pushRight(const ImageOf< PixelRgb > &rightFrame, const Stamp ×tamp)
bool tryPopPair(SynchronizedPair &pair)
void pushLeft(const ImageOf< PixelRgb > &leftFrame, const Stamp ×tamp)
stereoCalibThread(ResourceFinder &rf, Port *commPort, const char *imageDir)
StereoCalibStatus getStatus() const
constexpr double CTRL_DEG2RAD
PI/180.
ImageOf< PixelRgb > image
bool calibrationAvailable
std::string lastCalibrationError
std::size_t droppedLeftFrames
std::string calibrationMode
double meanTimestampDeltaMs
double maxTimestampDeltaMs
std::size_t droppedRightFrames
ImageOf< PixelRgb > right
std::size_t droppedLeftFrames
std::size_t synchronizedPairs
std::size_t acceptedObservations
double meanTimestampDeltaMs
double maxTimestampDeltaMs
std::size_t rejectedDetections
CameraCalibrationResult leftCamera
StereoCalibrationResult stereo
CameraCalibrationResult rightCamera
CalibrationQualityMetrics quality
CalibrationMode calibrationMode
CommonCalibrationOptions common
double cameraFocalLengthGuess
CommonCalibrationOptions common
double timestampDeltaSeconds
int64_t leftSequenceNumber
std::string leftImageFilename
int64_t rightSequenceNumber
std::vector< cv::Point2f > leftImagePoints
std::vector< cv::Point3f > objectPoints
std::string rightImageFilename
double rightTimestampSeconds
double leftTimestampSeconds
std::vector< cv::Point2f > rightImagePoints