iCub-main
Loading...
Searching...
No Matches
stereoCalibThread.cpp
Go to the documentation of this file.
1#include <algorithm>
2#include <cmath>
3#include <utility>
4#include <sstream>
5#include <opencv2/imgproc.hpp>
6#include <yarp/cv/Cv.h>
7#include <yarp/os/LogStream.h>
8#include "stereoCalibThread.h"
9
10
11YARP_LOG_COMPONENT(STEREOCALIBRATIONTHREAD, "yarp.tools.stereoCalibThread")
12
13namespace
14{
15
16 std::string formatCalibrationMatrix(const cv::Mat& matrix)
17 {
18 std::ostringstream stream;
19 stream << matrix;
20 return stream.str();
21 }
22
23 void logCameraCalibration(const char* cameraName,
25 {
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);
33 {
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);
38 }
40 {
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);
45 }
46 yCInfo(STEREOCALIBRATIONTHREAD) << "K =" << formatCalibrationMatrix(camera.K);
47 yCInfo(STEREOCALIBRATIONTHREAD) << "monocular RMS =" << camera.rms;
48 }
49
50 void logCalibrationResult(const stereo_calib::CalibrationResult& result)
51 {
52 yCInfo(STEREOCALIBRATIONTHREAD) << "========== Calibration result (not written to disk) ==========";
53
54 if(result.leftCamera.isValid())
55 {
56 logCameraCalibration("LEFT", result.leftCamera);
57 }
58 if(result.rightCamera.isValid())
59 {
60 logCameraCalibration("RIGHT", result.rightCamera);
61 }
62
63 if(result.stereo.isValid())
64 {
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)));
68
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());
74 // HN is the same homogeneous transform layout used by outputCalib.ini.
75 yCInfo(STEREOCALIBRATIONTHREAD) << "HN =" << formatCalibrationMatrix(homogeneousTransform);
76 }
77 yCInfo(STEREOCALIBRATIONTHREAD) << "======================================================================";
78 }
79
80 stereo_calib::CameraModel parseCameraModel(const std::string& modelString)
81 {
82 if(modelString == "pinhole")
83 {
85 }
86 else if(modelString == "fisheye")
87 {
89 }
90 else
91 {
92 yCError(STEREOCALIBRATIONTHREAD) << "Invalid camera model string:" << modelString
93 << ". Setting to Invalid.";
95 }
96 }
97
98 stereo_calib::CalibrationMode parseCalibrationMode(const std::string& modeString)
99 {
100 if(modeString == "MonocularLeft")
101 {
103 }
104 else if(modeString == "MonocularRight")
105 {
107 }
108 else if(modeString == "MonocularBoth")
109 {
111 }
112 else if(modeString == "StereoFull")
113 {
115 }
116 else
117 {
118 yCError(STEREOCALIBRATIONTHREAD) << "Invalid calibration mode string:" << modeString
119 << ". Using default StereoFull.";
121 }
122 }
123} // namespace
124
125void StereoPairSynchronizer::configure(double tolerance, std::size_t maxQueueSize)
126{
127 this->toleranceSeconds = tolerance;
128 this->maxQueueSize = maxQueueSize;
129}
130
132{
133 leftQueue.clear();
134 rightQueue.clear();
135
136 std::lock_guard<std::mutex> lock(_mutex);
137 stats = SynchronizerStatistics{};
138}
139
140void StereoPairSynchronizer::pushLeft(const ImageOf<PixelRgb>& leftFrame, const Stamp& timestamp)
141{
142 StampedFrame frame;
143
144 // Must be a deep copy. Do not retain pointer to the input-port buffer
145 frame.image.copy(leftFrame);
146 frame.stamp = timestamp;
147
148 leftQueue.push_back(std::move(frame));
149 trimLeftQueue();
150}
151
152void StereoPairSynchronizer::pushRight(const ImageOf<PixelRgb>& rightFrame, const Stamp& timestamp)
153{
154 StampedFrame frame;
155
156 // Must be a deep copy. Do not retain pointer to the input-port buffer
157 frame.image.copy(rightFrame);
158 frame.stamp = timestamp;
159
160 rightQueue.push_back(std::move(frame));
161 trimRightQueue();
162}
163
164
165void StereoPairSynchronizer::trimLeftQueue()
166{
167 while(leftQueue.size() > maxQueueSize)
168 {
169 leftQueue.pop_front();
170 std::lock_guard<std::mutex> lock(_mutex);
171 ++stats.droppedLeftFrames;
172 }
173}
174
175void StereoPairSynchronizer::trimRightQueue()
176{
177 while(rightQueue.size() > maxQueueSize)
178 {
179 rightQueue.pop_front();
180 std::lock_guard<std::mutex> lock(_mutex);
181 ++stats.droppedRightFrames;
182 }
183}
184
186{
187 while(!leftQueue.empty() && !rightQueue.empty())
188 {
189 const double leftStamp = leftQueue.front().stamp.getTime();
190 const double rightStamp = rightQueue.front().stamp.getTime();
191
192 const double absoluteDelta = std::abs(leftStamp - rightStamp);
193 if(absoluteDelta <= toleranceSeconds)
194 {
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;
199
200 pair.timeStampDelta = absoluteDelta;
201
202 leftQueue.pop_front();
203 rightQueue.pop_front();
204
205 std::lock_guard<std::mutex> lock(_mutex);
206 ++stats.pairedFrames;
207 stats.accumulatedTimeStampDelta += absoluteDelta;
208 stats.maxTimeStampDelta = std::max(stats.maxTimeStampDelta, absoluteDelta);
209
210 return true;
211 }
212
213 if(leftStamp < rightStamp)
214 {
215 // the oldest left frame cannot be paired with this or any newer right frame, so drop it
216 leftQueue.pop_front();
217 std::lock_guard<std::mutex> lock(_mutex);
218 ++stats.droppedLeftFrames;
219 }
220 else
221 {
222 rightQueue.pop_front();
223 std::lock_guard<std::mutex> lock(_mutex);
224 ++stats.droppedRightFrames;
225 }
226 }
227 return false;
228}
229
230
231stereoCalibThread::stereoCalibThread(ResourceFinder &rf, Port* commPort, const char *imageDir)
232{
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();
235
236 this->inputLeftPortName = "/"+moduleName;
237 this->inputLeftPortName +=rf.check("imgLeft",Value("/cam/left:i"),"Input image port (string)").asString().c_str();
238
239 this->inputRightPortName = "/"+moduleName;
240 this->inputRightPortName += rf.check("imgRight", Value("/cam/right:i"),"Input image port (string)").asString().c_str();
241
242 this->outNameRight = "/"+moduleName;
243 this->outNameRight += rf.check("outRight",Value("/cam/right:o"),"Output image port (string)").asString().c_str();
244
245 this->outNameLeft = "/"+moduleName;
246 this->outNameLeft +=rf.check("outLeft",Value("/cam/left:o"),"Output image port (string)").asString().c_str();
247
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)
253 {
254 yCWarning(STEREOCALIBRATIONTHREAD) << "numberOfPairs must be at least 30; using 30";
255 this->numOfPairs = 30;
256 }
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)
263 {
264 yCWarning(STEREOCALIBRATIONTHREAD) << "Invalid syncQueueSize; using 5";
265 _syncQueueSize = 5;
266 }
267 else
268 {
269 _syncQueueSize = static_cast<std::size_t>(configuredQueueSize);
270 }
271
272 if(_syncToleranceSeconds <= 0.0)
273 {
274 yCWarning(STEREOCALIBRATIONTHREAD) << "Invalid syncToleranceMs; using 20 ms";
275 _syncToleranceSeconds = 0.020;
276 }
277
278 synchronizer.configure(_syncToleranceSeconds, _syncQueueSize);
279
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);
286 // All new calibration modes use the synchronized-observation pipeline.
287 // In particular, completion must never bypass CalibrationWriter.
288 this->camCalibFile=rf.getHomeContextPath().c_str();
289 this->standalone = rf.check("standalone", Value(false)).asBool();
290 string fileName= "outputCalib.ini";
291
292 this->camCalibFile=this->camCalibFile+"/"+fileName.c_str();
293
294 _observationsFile = stereoCalibOpts.check(
295 "observationsFile", Value("calibrationObservations.yml")).asString();
296 if(!_observationsFile.empty() && _observationsFile.front() != '/')
297 {
298 _observationsFile = this->imageDir + "/" + _observationsFile;
299 }
300
301 // TODO: remove. This is a duplication. Enough to set: _chessboardConfiguration.cornersX stereoCalibOpts.check("boardWidth", Value(8)).asInt32();
302 _chessboardConfiguration.cornersX = this->boardWidth;
303 _chessboardConfiguration.cornersY = this->boardHeight;
304
305 // TODO: remove as well --> duplication
306 _chessboardConfiguration.squareSizeMeters = this->squareSize;
307
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());
312
313 if(!_chessboardConfiguration.isValid())
314 {
315 yCError(STEREOCALIBRATIONTHREAD) << "Invalid chessboard configuration";
316 }
317}
318
320{
321 if (!imagePortInLeft.open(inputLeftPortName.c_str())) {
322 cout << ": unable to open port " << inputLeftPortName << endl;
323 return false;
324 }
325
326 if (!imagePortInRight.open(inputRightPortName.c_str())) {
327 cout << ": unable to open port " << inputRightPortName << endl;
328 return false;
329 }
330
331 if (!outPortLeft.open(outNameLeft.c_str())) {
332 cout << ": unable to open port " << outNameLeft << endl;
333 return false;
334 }
335
336 if (!outPortRight.open(outNameRight.c_str())) {
337 cout << ": unable to open port " << outNameRight << endl;
338 return false;
339 }
340
341 //when in standalone mode we won't open the remote control board devices
342 if(standalone) return true;
343
344 //TODO: develop what to do with the control boards for head and torso
345 // in the legacy implementation the kinematic chain was calculated and joint position added to the output file
346 // now why we need that? is it uselful? do we need to change it to a check on steadiness for the calibration procedure
347 Property optHead;
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) ||
353 posHead == nullptr)
354 {
355 yCError(STEREOCALIBRATIONTHREAD) << "Unable to acquire the head encoder interface";
356 return false;
357 }
358
359 Property optTorso;
360 optTorso.put("device","remote_controlboard");
361 optTorso.put("remote",("/"+robotName+"/torso").c_str());
362 optTorso.put("local","/"+moduleName+"/client/torso");
363
364 bool useTorso=true;
365 if (!polyTorso.open(optTorso) ||
366 !polyTorso.view(posTorso) ||
367 posTorso == nullptr)
368 {
369 yCWarning(STEREOCALIBRATIONTHREAD, "Unable to connect to torso! Continuing without...");
370 useTorso=false;
371 }
372
373 yarp::sig::Vector head_angles(6,0.0);
374 posHead->getEncoders(head_angles.data());
375
376 yarp::sig::Vector torso_angles(3,0.0);
377 if (useTorso)
378 posTorso->getEncoders(torso_angles.data());
379
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];
383
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];
388
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];
392
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];
397
398 return true;
399}
401 yCInfo(STEREOCALIBRATIONTHREAD, "Running synchronized fisheye calibration pipeline... \n");
402 stereoCalibRun();
403}
404
405void stereoCalibThread::processSynchronizedPair(SynchronizedPair& pair, Size boardSize)
406{
407 // Check minimum capture interval
408 const double pairTime = 0.5 * (pair.leftStamp.getTime() + pair.rightStamp.getTime()); //average pair timestamp
409 const double previousProcessedCandidateTime = lastProcessedCandidateTime;
410 if(previousProcessedCandidateTime >= 0.0 && (pairTime - previousProcessedCandidateTime) < minCaptureIntervalSeconds)
411 {
412 yCDebug(STEREOCALIBRATIONTHREAD) << "Skipping candidate pair due to minimum capture interval";
413 return;
414 }
415 if(previousProcessedCandidateTime >= 0.0)
416 {
417 yCDebug(STEREOCALIBRATIONTHREAD) << "Timestamp delta between processed pairs:" << (pairTime - previousProcessedCandidateTime) << "seconds";
418 }
419 lastProcessedCandidateTime = pairTime;
420
421
422 bool foundL=false;
423 bool foundR=false;
424 const Size leftSize(pair.left.width(), pair.left.height());
425 const Size rightSize(pair.right.width(), pair.right.height());
426
427 if(leftSize != _expectedImageSize || rightSize != _expectedImageSize)
428 {
429 if(_expectedImageSize.empty())
430 {
431 _expectedImageSize = leftSize;
432 }
433 }
434
435 if(leftSize != _expectedImageSize || rightSize != _expectedImageSize)
436 {
437 yCError(STEREOCALIBRATIONTHREAD) << "Left and right images have different sizes:" <<
438 "Left:" << leftSize.width << "x" << leftSize.height <<
439 "Right:" << rightSize.width << "x" << rightSize.height;
440 {
441 std::lock_guard<std::mutex> lock(mtx);
442 _calibrationError = "Input images do not match the expected calibration resolution.";
443 _calibrationResults = stereo_calib::CalibrationResult{};
444 }
445 calibrationState.store(CalibrationState::Error);
446
447 return;
448 }
449
450 LeftRgb=yarp::cv::toCvMat(pair.left);
451 RightRgb=yarp::cv::toCvMat(pair.right);
452
453 // Color adjust
454 Mat leftGray, rightGray;
455 cvtColor(LeftRgb,leftGray,cv::COLOR_RGB2GRAY);
456 cvtColor(RightRgb,rightGray,cv::COLOR_RGB2GRAY);
457
458 std::vector<Point2f> leftCorners;
459 std::vector<Point2f> rightCorners;
460
461 //TODO: for now we are only using CHESSBOARD GRID. For circle grid and so on we will add an update in the future.
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.";
474 } else {
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);
477 }
478
479 if(foundL && foundR)
480 {
481 yCDebug(STEREOCALIBRATIONTHREAD) << "Found calibration board corners in both left and right images";
482
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;
491
492 if(leftBoardTooSmall || rightBoardTooSmall)
493 {
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.";
501
502 ++_rejectedDetections;
503 return;
504 }
505
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);
509
510 // Detection and geometry have succeeded. Build and validate the
511 // complete observation before assigning its accepted index.
512 stereo_calib::StereoObservation observation;
513 observation.imageSize = Size(pair.left.width(), pair.left.height());
514
515 observation.objectPoints = _chessboardConfiguration.createObjectPoints();
516 observation.leftImagePoints = leftCorners;
517 observation.rightImagePoints = rightCorners;
518
519 observation.leftTimestampSeconds = pair.leftStamp.getTime();
520 observation.rightTimestampSeconds = pair.rightStamp.getTime();
521 observation.timestampDeltaSeconds = pair.timeStampDelta;
522
523 observation.leftSequenceNumber = pair.leftStamp.getCount();
524 observation.rightSequenceNumber = pair.rightStamp.getCount();
525
526 if(!observation.isValid())
527 {
528 yCError(STEREOCALIBRATIONTHREAD) << "Generated invalid stereo observation";
529 ++_rejectedDetections;
530 return;
531 }
532
533 std::size_t observationIndex = 0;
534 observationIndex = _observations.size();
535
536 // Raw images are saved before drawing any optional diagnostics and
537 // only after the pair has become an accepted observation candidate.
538 if(_saveImages)
539 {
540 std::string imageError;
541 if(!_calibrationWriter.writeImagePair(imageDir, observationIndex,
542 LeftRgb, RightRgb,
543 observation.leftImageFilename,
544 observation.rightImageFilename,
545 imageError))
546 {
547 yCError(STEREOCALIBRATIONTHREAD) << "Could not save accepted calibration image pair:" << imageError;
548 {
549 std::lock_guard<std::mutex> lock(mtx);
550 if (calibrationState.load() != CalibrationState::Collecting)
551 {
552 return;
553 }
554
555 _calibrationError = imageError;
556 _calibrationResults = stereo_calib::CalibrationResult{};
557 calibrationState.store(CalibrationState::Error);
558 }
559 return;
560 }
561 }
562
563 // Detection and validation have completed.
564 {
565 std::lock_guard<std::mutex> lock(mtx);
566 if (calibrationState.load() != CalibrationState::Collecting)
567 {
568 return;
569 }
570 _observations.push_back(std::move(observation));
571 }
572
573 // Diagnostic overlays are deliberately the final step: they never
574 // affect the persisted raw dataset or the stored corner coordinates.
575 if(_drawDiagnosticCorners)
576 {
577 drawChessboardCorners(LeftRgb, boardSize, leftCorners, foundL);
578 drawChessboardCorners(RightRgb, boardSize, rightCorners, foundR);
579 }
580
581 ImageOf<PixelRgb>& outimL = outPortLeft.prepare();
582 outimL = pair.left;
583 outPortLeft.setEnvelope(pair.leftStamp);
584 outPortLeft.write();
585
586 ImageOf<PixelRgb>& outimR = outPortRight.prepare();
587 outimR = pair.right;
588 outPortRight.setEnvelope(pair.rightStamp);
589 outPortRight.write();
590
591 }
592 else
593 {
594 ++_rejectedDetections;
595 }
596
597 return;
598}
599
601{
602 StereoCalibStatus result;
603
604 std::lock_guard<std::mutex> lock(mtx);
605
606 switch(calibrationState.load())
607 {
608 case CalibrationState::Idle:
609 result.state = "Idle";
610 break;
611 case CalibrationState::Collecting:
612 result.state = "Collecting";
613 break;
614 case CalibrationState::Calibrating:
615 result.state = "Calibrating";
616 break;
617 case CalibrationState::Completed:
618 result.state = "Completed";
619 break;
620 case CalibrationState::Error:
621 result.state = "Error";
622 break;
623 }
624
625 const auto syncStats = synchronizer.getStatistics();
626
627 result.pairedFrames = syncStats.pairedFrames;
628 result.droppedLeftFrames = syncStats.droppedLeftFrames;
629 result.droppedRightFrames = syncStats.droppedRightFrames;
630
631 if(syncStats.pairedFrames > 0)
632 {
633 result.meanTimestampDeltaMs = 1000.0 * syncStats.accumulatedTimeStampDelta / static_cast<double>(syncStats.pairedFrames);
634 }
635
636 result.maxTimestampDeltaMs = 1000.0 * syncStats.maxTimeStampDelta;
637
638 result.lastCalibrationError = _calibrationError;
639 if(calibrationState.load() == CalibrationState::Completed && _calibrationResults.isValid())
640 {
641 result.calibrationAvailable = true;
642 switch(_calibrationResults.mode)
643 {
645 result.calibrationMode = "MonocularLeft";
646 break;
648 result.calibrationMode = "MonocularRight";
649 break;
651 result.calibrationMode = "MonocularBoth";
652 break;
654 result.calibrationMode = "StereoFull";
655 break;
656 }
657
658 if(_calibrationResults.leftCamera.isValid())
659 {
660 result.leftMonocularRms = _calibrationResults.leftCamera.rms;
661 }
662 if(_calibrationResults.rightCamera.isValid())
663 {
664 result.rightMonocularRms = _calibrationResults.rightCamera.rms;
665 }
666 if(_calibrationResults.stereo.isValid())
667 {
668 result.stereoRms = _calibrationResults.stereo.rms;
669 result.baselineNorm = _calibrationResults.quality.baseline;
670 }
671 }
672
673 return result;
674}
675
676bool stereoCalibThread::shouldQueueFrameForCollection(const Stamp& timestamp) const
677{
678 return lastProcessedCandidateTime < 0.0 ||
679 (timestamp.getTime() - lastProcessedCandidateTime) >= minCaptureIntervalSeconds;
680}
681
682void stereoCalibThread::stereoCalibRun()
683{
684 Size boardSize;
685 boardSize.width=this->boardWidth;
686 boardSize.height=this->boardHeight;
687
688 while (!isStopping())
689 {
690 // Keep the worker alive for RPC status inspection after a calibration
691 // failure, but stop consuming/processing camera data until a new start
692 // request changes the state back to Collecting.
693 if(calibrationState.load() == CalibrationState::Error)
694 {
695 Time::delay(0.1);
696 continue;
697 }
698
699 if(collectionResetRequested.exchange(false))
700 {
701 synchronizer.reset();
702 lastProcessedCandidateTime = -1.0;
703 _expectedImageSize = {};
704 _observations.clear();
705 _rejectedDetections = 0;
706 {
707 std::lock_guard<std::mutex> lock(mtx);
708 _calibrationResults = stereo_calib::CalibrationResult{};
709 _calibrationError.clear();
710 }
711 }
712
713 bool areFramesReceived = false;
714 ImageOf<PixelRgb> *tmpL = imagePortInLeft.read(false);
715
716 if(tmpL != nullptr)
717 {
718 areFramesReceived = true;
719
720 Stamp TSLeft;
721 imagePortInLeft.getEnvelope(TSLeft);
722
723 // Always publish preview immediately
724 ImageOf<PixelRgb>& outimL = outPortLeft.prepare();
725 outimL = *tmpL;
726 outPortLeft.setEnvelope(TSLeft);
727 outPortLeft.write();
728
729 // Only enqueue a separate copy while collecting
730 if(calibrationState.load() == CalibrationState::Collecting &&
731 shouldQueueFrameForCollection(TSLeft))
732 {
733 synchronizer.pushLeft(*tmpL, TSLeft); // this is done for not consuming memory bandwidth for data that will never be used by the calibration
734 }
735 }
736
737 ImageOf<PixelRgb> *tmpR = imagePortInRight.read(false);
738 if(tmpR!=nullptr)
739 {
740 areFramesReceived = true;
741
742 Stamp TSRight;
743 imagePortInRight.getEnvelope(TSRight);
744
745 // Always publish preview immediately
746 ImageOf<PixelRgb>& outimR=outPortRight.prepare();
747 outimR = *tmpR;
748 outPortRight.setEnvelope(TSRight);
749 outPortRight.write();
750
751
752 // Only enqueue a separate copy while collecting
753 if(calibrationState.load() == CalibrationState::Collecting &&
754 shouldQueueFrameForCollection(TSRight))
755 {
756 synchronizer.pushRight(*tmpR, TSRight);
757 }
758 }
759
760 std::vector<stereo_calib::StereoObservation> observationSnapshot;
761
762 if(calibrationState.load() == CalibrationState::Collecting)
763 {
764 SynchronizedPair pair;
765 while(calibrationState.load() == CalibrationState::Collecting &&
766 synchronizer.tryPopPair(pair))
767 {
768 // Process the synchronized pair
769 processSynchronizedPair(pair, boardSize);
770
771 if(calibrationState.load() != CalibrationState::Collecting)
772 {
773 break;
774 }
775 if(_observations.size() >= static_cast<std::size_t>(numOfPairs))
776 {
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";
781 break;
782 }
783 }
784 }
785
786 if(calibrationState.load() == CalibrationState::Calibrating)
787 {
788 yCInfo(STEREOCALIBRATIONTHREAD) << "Starting the calibration process";
789 if(observationSnapshot.empty())
790 {
791 observationSnapshot = _observations;
792 }
793
794 stereo_calib::CalibrationResult calibrationResult;
795 std::string calibrationError;
796 bool success = false;
797 if (_cameraModel == stereo_calib::CameraModel::Pinhole)
798 {
799 stereo_calib::PinholeCalibrationOptions options = _pinholeCalibrationOptions;
800 options.common.calibrationMode = _calibrationMode;
801 options.common.imageSize = observationSnapshot.front().imageSize;
802 success = _pinholeCalibrationEngine.calibrate(
803 observationSnapshot,
804 options,
805 calibrationResult,
806 calibrationError
807 );
808 }
809 else if(_cameraModel == stereo_calib::CameraModel::Fisheye)
810 {
811 stereo_calib::FisheyeCalibrationOptions options = _fisheyeCalibrationOptions;
812 options.common.calibrationMode = _calibrationMode;
813 options.common.imageSize = observationSnapshot.front().imageSize;
814 options.cameraFocalLengthGuess = 625.0;
815 success = _fisheyeCalibrationEngine.calibrate(
816 observationSnapshot,
817 options,
818 calibrationResult,
819 calibrationError
820 );
821 }
822 else
823 {
824 calibrationError = "Unsupported camera model.";
825 success = false;
826 }
827
828 // success and writer should be common between fisheye and pinhole engines, so this block can be shared
829 if(!success)
830 {
831 // The engine converts OpenCV exceptions into a diagnostic. Log
832 // it here, where YARP logging is allowed, and stop calibration
833 // processing while keeping the Error state and status available.
834 yCError(STEREOCALIBRATIONTHREAD) << "Calibration failed:" << calibrationError;
835 {
836 std::lock_guard<std::mutex> lock(mtx);
837 _calibrationResults = stereo_calib::CalibrationResult{};
838 _calibrationError = calibrationError.empty()
839 ? "Calibration failed without an error message."
840 : calibrationError;
841 }
842 calibrationState.store(CalibrationState::Error);
843 continue;
844 }
845
846 const auto syncStats = synchronizer.getStatistics();
847 calibrationResult.quality.rejectedDetections = _rejectedDetections;
848 calibrationResult.quality.acceptedObservations = observationSnapshot.size();
849 calibrationResult.quality.synchronizedPairs = syncStats.pairedFrames;
850 if(syncStats.pairedFrames > 0)
851 {
852 calibrationResult.quality.meanTimestampDeltaMs = 1000.0 * syncStats.accumulatedTimeStampDelta / static_cast<double>(syncStats.pairedFrames);
853 }
854 calibrationResult.quality.maxTimestampDeltaMs = syncStats.maxTimeStampDelta;
855 calibrationResult.quality.baseline = cv::norm(calibrationResult.stereo.T);
856
857 std::string persistenceError;
858 if(!_calibrationWriter.write(camCalibFile, calibrationResult, persistenceError))
859 {
860 yCError(STEREOCALIBRATIONTHREAD) << "Could not save calibration results:" << persistenceError;
861 {
862 std::lock_guard<std::mutex> lock(mtx);
863 _calibrationResults = std::move(calibrationResult);
864 _calibrationError = persistenceError;
865 }
866 calibrationState.store(CalibrationState::Error);
867 continue;
868 }
869 if(!_calibrationWriter.writeObservations(_observationsFile, observationSnapshot, persistenceError))
870 {
871 yCError(STEREOCALIBRATIONTHREAD) << "Could not save calibration observations:" << persistenceError;
872 {
873 std::lock_guard<std::mutex> lock(mtx);
874 _calibrationResults = std::move(calibrationResult);
875 _calibrationError = persistenceError;
876 }
877 calibrationState.store(CalibrationState::Error);
878 continue;
879 }
880
881 logCalibrationResult(calibrationResult);
882 {
883 std::lock_guard<std::mutex> lock(mtx);
884 _calibrationResults = std::move(calibrationResult);
885 _calibrationError.clear();
886 }
887
888 calibrationState.store(CalibrationState::Completed);
889 yCInfo(STEREOCALIBRATIONTHREAD) << "Entire calibration process completed";
890 }
891
892 if(!areFramesReceived)
893 {
894 Time::delay(0.001); // Sleep for a short duration to avoid busy waiting
895 }
896 cout.flush();
897 }
898}
899
901{
902 imagePortInRight.close();
903 imagePortInLeft.close();
904 outPortLeft.close();
905 outPortRight.close();
906 commandPort->close();
907
908 if (polyHead.isValid())
909 polyHead.close();
910
911 if (polyTorso.isValid())
912 polyTorso.close();
913}
914
916 // TODO: the following 2 should not ne necessary since we already store their state in stop()
917 calibrationState.store(CalibrationState::Idle);
918 collectionResetRequested.store(false);
919 imagePortInRight.interrupt();
920 imagePortInLeft.interrupt();
921 outPortLeft.interrupt();
922 outPortRight.interrupt();
923 commandPort->interrupt();
924
925}
927
928 std::lock_guard<std::mutex> lock(mtx);
929
930 const CalibrationState currentState = calibrationState.load();
931
932 if(currentState == CalibrationState::Collecting || currentState == CalibrationState::Calibrating)
933 {
934 yCWarning(STEREOCALIBRATIONTHREAD) << "Cannot start a new calibration while calibration is already running";
935 return;
936 }
937
938 _calibrationResults = stereo_calib::CalibrationResult{};
939 _calibrationError.clear();
940 calibrationState.store(CalibrationState::Collecting);
941 collectionResetRequested.store(true);
942
943 yCInfo(STEREOCALIBRATIONTHREAD) << "Calibration collection started";
944}
945
947 std::lock_guard<std::mutex> lock(mtx);
948
949 if(calibrationState.load() != CalibrationState::Collecting)
950 {
951 yCWarning(STEREOCALIBRATIONTHREAD) << "Cannot stop calibration collection when it is not running";
952 return;
953 }
954 calibrationState.store(CalibrationState::Idle);
955 collectionResetRequested.store(true);
956
957 yCInfo(STEREOCALIBRATIONTHREAD) << "Calibration collection stopped";
958}
constexpr double tolerance
void configure(double tolerance, std::size_t maxQueueSize)
void pushRight(const ImageOf< PixelRgb > &rightFrame, const Stamp &timestamp)
bool tryPopPair(SynchronizedPair &pair)
void pushLeft(const ImageOf< PixelRgb > &leftFrame, const Stamp &timestamp)
stereoCalibThread(ResourceFinder &rf, Port *commPort, const char *imageDir)
StereoCalibStatus getStatus() const
constexpr double CTRL_DEG2RAD
PI/180.
Definition math.h:66
#define LEFT
#define RIGHT
ImageOf< PixelRgb > image
std::string lastCalibrationError
std::size_t droppedLeftFrames
std::string calibrationMode
std::size_t droppedRightFrames
ImageOf< PixelRgb > left
ImageOf< PixelRgb > right
CameraCalibrationResult leftCamera
StereoCalibrationResult stereo
CameraCalibrationResult rightCamera
CalibrationQualityMetrics quality
std::vector< cv::Point2f > leftImagePoints
std::vector< cv::Point3f > objectPoints
std::vector< cv::Point2f > rightImagePoints