Subversion Repositories seema-scanner

Rev

Rev 249 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
27 jakw 1
#include "SMCalibrationWorker.h"
2
#include "SMCalibrationParameters.h"
22 jakw 3
 
31 jakw 4
#include "cvtools.h"
5
 
249 jakw 6
#include <opencv2/aruco/charuco.hpp>
7
 
22 jakw 8
#include <QSettings>
225 jakw 9
#include <QTextStream>
22 jakw 10
 
196 jakw 11
#include <ceres/ceres.h>
12
 
13
// Closed form solution to solve for the rotation axis from sets of 3D point coordinates of flat pattern feature points
14
// Algorithm according to Chen et al., Rotation axis calibration of a turntable using constrained global optimization, Optik 2014
15
// DTU, 2014, Jakob Wilm
225 jakw 16
static void rotationAxisEstimation(const std::vector< std::vector<cv::Point3f> > Qcam,
17
                                   const std::vector<cv::Point3f> Qobj,
18
                                   cv::Vec3f &axis, cv::Vec3f &point){
207 flgw 19
    assert(Qobj.size() == Qcam[0].size());
196 jakw 20
 
21
    // number of frames (points on each arch)
250 jakw 22
    auto l = Qcam.size();
196 jakw 23
 
24
    // number of points in each frame
25
    size_t mn = Qobj.size();
26
 
27
    // construct matrix for axis determination
28
    cv::Mat M(6, 6, CV_32F, cv::Scalar(0));
29
 
30
    for(int k=0; k<l; k++){
31
        for(unsigned int idx=0; idx<mn; idx++){
32
 
207 flgw 33
            //            float i = Qobj[idx].x+4;
34
            //            float j = Qobj[idx].y+4;
196 jakw 35
            float i = Qobj[idx].x;
36
            float j = Qobj[idx].y;
37
 
38
            float x = Qcam[k][idx].x;
39
            float y = Qcam[k][idx].y;
40
            float z = Qcam[k][idx].z;
41
 
42
            M += (cv::Mat_<float>(6,6) << x*x, x*y, x*z, x, i*x, j*x,
207 flgw 43
                  0, y*y, y*z, y, i*y, j*y,
44
                  0,   0, z*z, z, i*z, j*z,
45
                  0,   0,   0, 1,   i,   j,
46
                  0,   0,   0, 0, i*i, i*j,
47
                  0,   0,   0, 0,   0, j*j);
196 jakw 48
 
49
        }
50
    }
51
 
52
    cv::completeSymm(M, false);
53
 
54
    // solve for axis
55
    std::vector<float> lambda;
56
    cv::Mat u;
57
    cv::eigen(M, lambda, u);
58
 
59
    float minLambda = std::abs(lambda[0]);
60
    int idx = 0;
61
    for(unsigned int i=1; i<lambda.size(); i++){
62
        if(abs(lambda[i]) < minLambda){
63
            minLambda = lambda[i];
64
            idx = i;
65
        }
66
    }
67
 
68
    axis = u.row(idx).colRange(0, 3);
69
    axis = cv::normalize(axis);
70
 
71
    float nx = u.at<float>(idx, 0);
72
    float ny = u.at<float>(idx, 1);
73
    float nz = u.at<float>(idx, 2);
74
    //float d  = u.at<float>(idx, 3);
75
    float dh = u.at<float>(idx, 4);
76
    float dv = u.at<float>(idx, 5);
77
 
207 flgw 78
    // Paper version: c is initially eliminated
79
    /*cv::Mat A(l*mn, mn+2, CV_32F, cv::Scalar(0.0));
80
        cv::Mat bb(l*mn, 1, CV_32F);
196 jakw 81
 
207 flgw 82
        for(int k=0; k<l; k++){
83
            for(unsigned int idx=0; idx<mn; idx++){
196 jakw 84
 
207 flgw 85
                float i = Qobj[idx].x;
86
                float j = Qobj[idx].y;
196 jakw 87
 
207 flgw 88
                float x = Qcam[k][idx].x;
89
                float y = Qcam[k][idx].y;
90
                float z = Qcam[k][idx].z;
196 jakw 91
 
207 flgw 92
                float f = x*x + y*y + z*z + (2*x*nx + 2*y*ny + 2*z*nz)*(i*dh + j*dv);
196 jakw 93
 
207 flgw 94
                int row = k*mn+idx;
95
                A.at<float>(row, 0) = 2*x - (2*z*nx)/nz;
96
                A.at<float>(row, 1) = 2*y - (2*z*ny)/nz;
97
                A.at<float>(row, idx+2) = 1.0;
196 jakw 98
 
207 flgw 99
                bb.at<float>(row, 0) = f + (2*z*d)/nz;
100
            }
101
        }
196 jakw 102
 
207 flgw 103
        // solve for point
104
        cv::Mat abe;
105
        cv::solve(A, bb, abe, cv::DECOMP_SVD);
196 jakw 106
 
207 flgw 107
        float a = abe.at<float>(0, 0);
108
        float b = abe.at<float>(1, 0);
109
        float c = -(nx*a+ny*b+d)/nz;
110
        */
196 jakw 111
 
112
    // Our version: solve simultanously for a,b,c
113
    cv::Mat A(l*mn, mn+3, CV_32F, cv::Scalar(0.0));
114
    cv::Mat bb(l*mn, 1, CV_32F);
115
 
116
    for(int k=0; k<l; k++){
117
        for(unsigned int idx=0; idx<mn; idx++){
118
 
119
            float i = Qobj[idx].x;
120
            float j = Qobj[idx].y;
121
 
122
            float x = Qcam[k][idx].x;
123
            float y = Qcam[k][idx].y;
124
            float z = Qcam[k][idx].z;
125
 
126
            float f = x*x + y*y + z*z + (2*x*nx + 2*y*ny + 2*z*nz)*(i*dh + j*dv);
127
 
128
            int row = k*mn+idx;
129
            A.at<float>(row, 0) = 2*x;
130
            A.at<float>(row, 1) = 2*y;
131
            A.at<float>(row, 2) = 2*z;
132
            A.at<float>(row, idx+3) = 1.0;
133
 
134
            bb.at<float>(row, 0) = f;
135
        }
136
    }
137
 
138
    // solve for point
139
    cv::Mat abe;
140
    cv::solve(A, bb, abe, cv::DECOMP_SVD);
141
 
142
    float a = abe.at<float>(0, 0);
143
    float b = abe.at<float>(1, 0);
144
    float c = abe.at<float>(2, 0);
145
 
146
    point[0] = a;
147
    point[1] = b;
148
    point[2] = c;
149
 
225 jakw 150
}
151
 
152
struct CircleResidual {
153
    CircleResidual(std::vector<cv::Point3f> _pointsOnArc)
154
        : pointsOnArc(_pointsOnArc) {}
155
 
156
    template <typename T>
157
    bool operator()(const T* point, const T* axis, T* residual) const {
158
 
159
        T axisSqNorm = axis[0]*axis[0] + axis[1]*axis[1] + axis[2]*axis[2];
160
 
161
        unsigned int l = pointsOnArc.size();
162
        std::vector<T> dI(l);
163
 
164
        // note, this is automatically initialized to 0
165
        T sum(0.0);
166
 
167
        for(unsigned int i=0; i<l; i++){
168
            cv::Point3d p = pointsOnArc[i];
169
            //T p[3] = {pointsOnArc[i].x, pointsOnArc[i].y, pointsOnArc[i].z};
170
 
171
            // point to line distance
172
            T dotProd = (point[0]-p.x)*axis[0] + (point[1]-p.y)*axis[1] + (point[2]-p.z)*axis[2];
173
            T dIx = point[0] - p.x - (dotProd*axis[0]/axisSqNorm);
174
            T dIy = point[1] - p.y - (dotProd*axis[1]/axisSqNorm);
175
            T dIz = point[2] - p.z - (dotProd*axis[2]/axisSqNorm);
176
            dI[i] = ceres::sqrt(dIx*dIx + dIy*dIy + dIz*dIz);
177
 
178
            sum += dI[i];
179
        }
180
 
181
        T mean = sum / double(l);
182
 
183
        for(unsigned int i=0; i<l; i++){
184
            residual[i] = dI[i] - mean;
185
        }
186
 
187
        return true;
188
    }
189
 
190
    private:
191
        // Observations for one checkerboard corner.
192
        const std::vector<cv::Point3f> pointsOnArc;
193
};
194
 
195
static void rotationAxisOptimization(const std::vector< std::vector<cv::Point3f> > Qcam, const std::vector<cv::Point3f> Qobj, cv::Vec3f &axis, cv::Vec3f &point, float &error){
196
 
197
    // number of frames (points on each arch)
198
    size_t l = Qcam.size();
199
 
200
    // number of points in each frame
201
    size_t mn = Qobj.size();
202
 
203
    // read initial guess
197 jakw 204
    double pointArray[] = {point[0], point[1], point[2]};
205
    double axisArray[] = {axis[0], axis[1], axis[2]};
196 jakw 206
 
207
    ceres::Problem problem;
225 jakw 208
 
196 jakw 209
    // loop through saddle points
210
    for(unsigned int idx=0; idx<mn; idx++){
211
        std::vector<cv::Point3f> pointsOnArch(l);
225 jakw 212
        for(unsigned int k=0; k<l; k++){
196 jakw 213
            pointsOnArch[k] = Qcam[k][idx];
214
        }
215
        ceres::CostFunction* cost_function =
207 flgw 216
                new ceres::AutoDiffCostFunction<CircleResidual, ceres::DYNAMIC, 3, 3>(
217
                    new CircleResidual(pointsOnArch), l);
197 jakw 218
        problem.AddResidualBlock(cost_function, NULL, pointArray, axisArray);
196 jakw 219
    }
220
 
221
    // Run the solver!
222
    ceres::Solver::Options options;
223
    options.linear_solver_type = ceres::DENSE_QR;
224
    options.minimizer_progress_to_stdout = true;
225
    ceres::Solver::Summary summary;
226
    ceres::Solve(options, &problem, &summary);
227
 
228
    std::cout << summary.BriefReport() << "\n";
229
 
197 jakw 230
    point = cv::Vec3f(pointArray[0], pointArray[1], pointArray[2]);
231
    axis = cv::Vec3f(axisArray[0], axisArray[1], axisArray[2]);
232
    axis /= cv::norm(axis);
196 jakw 233
 
234
 
197 jakw 235
    // Error estimate (sum of squared differences)
196 jakw 236
    error = 0;
237
    // loop through saddle points
238
    for(unsigned int idx=0; idx<mn; idx++){
239
 
240
        // vector of distances from rotation axis
241
        std::vector<float> dI(l);
242
        // loop through angular positions
225 jakw 243
        for(unsigned int k=0; k<l; k++){
196 jakw 244
            cv::Vec3f p = cv::Vec3f(Qcam[k][idx]);
245
            // point to line distance
246
            dI[k] = cv::norm((point-p)-(point-p).dot(axis)*axis);
247
        }
248
        float sum = std::accumulate(dI.begin(), dI.end(), 0.0);
249
        float mean = sum / dI.size();
198 jakw 250
        float meanDev = 0;
225 jakw 251
        for(unsigned int k=0; k<l; k++){
198 jakw 252
            meanDev += std::abs(dI[k] - mean);
196 jakw 253
        }
198 jakw 254
        meanDev /= l;
255
        error += meanDev;
196 jakw 256
    }
198 jakw 257
    error /= mn;
196 jakw 258
}
259
 
225 jakw 260
static std::vector<cv::Point3f> generateWorldCoords(const cv::Size checkerCount, const float checkerSize){
261
 
262
    std::vector<cv::Point3f> Qi;
263
    for (int h=0; h<checkerCount.height; h++)
264
        for (int w=0; w<checkerCount.width; w++)
265
            Qi.push_back(cv::Point3f(checkerSize * w, checkerSize* h, 0.0));
266
 
267
    return Qi;
268
}
269
 
270
static bool detectCheckerBoardCorners(const cv::Size & checkerCount,
271
                                    const cv::Mat & frame,
272
                                    cv::Mat & frameResult,
273
                                    std::vector<cv::Point2f> & qc){
206 flgw 274
    // Convert to grayscale
275
    cv::Mat gray;
225 jakw 276
    if(frame.channels() == 1)
277
        cv::cvtColor(frame, gray, CV_BayerBG2GRAY);
206 flgw 278
    else
225 jakw 279
        cv::cvtColor(frame, gray, CV_RGB2GRAY);
206 flgw 280
 
281
    // Extract checker corners
225 jakw 282
    bool success = cv::findChessboardCorners(gray, checkerCount, qc, cv::CALIB_CB_ADAPTIVE_THRESH + cv::CALIB_CB_FAST_CHECK);
206 flgw 283
    if(success){
225 jakw 284
        cv::cornerSubPix(gray, qc, cv::Size(6, 6), cv::Size(1, 1), cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 20, 0.0001));
206 flgw 285
        // Draw colored chessboard
225 jakw 286
        if(frame.channels() == 1)
287
            cv::cvtColor(frame, frameResult, CV_BayerBG2RGB);
206 flgw 288
        else
225 jakw 289
            frameResult = frame.clone();
206 flgw 290
 
225 jakw 291
        cvtools::drawChessboardCorners(frameResult, checkerCount, qc, success, 10);
228 jakw 292
    } else {
293
        qc.clear();
206 flgw 294
    }
295
    return success;
296
}
297
 
225 jakw 298
void SMCalibrationWorker::checkerboardDetection(SMCalibrationSet calibrationSet){
22 jakw 299
 
207 flgw 300
    QSettings settings;
225 jakw 301
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
22 jakw 302
 
225 jakw 303
    bool success0 = detectCheckerBoardCorners(checkerCount, calibrationSet.frame0, calibrationSet.frame0Result, calibrationSet.qc0);
228 jakw 304
    if(!success0){
305
//        calibrationSet.qc0.clear();
225 jakw 306
        emit logMessage(QString("Could not detect checkerboard on set %1 camera0").arg(calibrationSet.id));
242 jakw 307
        std::cerr << "Could not detect checkerboard on set " << calibrationSet.id << " camera0" << std::endl;
228 jakw 308
    }
22 jakw 309
 
225 jakw 310
    bool success1 = detectCheckerBoardCorners(checkerCount, calibrationSet.frame1, calibrationSet.frame1Result, calibrationSet.qc1);
228 jakw 311
    if(!success1){
312
//        calibrationSet.qc1.clear();
225 jakw 313
        emit logMessage(QString("Could not detect checkerboard on set %1 camera1").arg(calibrationSet.id));
242 jakw 314
        std::cerr << "Could not detect checkerboard on set " << calibrationSet.id << " camera1" << std::endl;
228 jakw 315
    }
25 jakw 316
 
225 jakw 317
    emit newCheckerboardResult(calibrationSet.id, calibrationSet);
25 jakw 318
 
207 flgw 319
}
25 jakw 320
 
225 jakw 321
void SMCalibrationWorker::cameraCalibration(std::vector<SMCalibrationSet> calibrationData){
137 jakw 322
 
225 jakw 323
    QSettings settings;
324
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
22 jakw 325
 
225 jakw 326
    unsigned int nSets = calibrationData.size();
22 jakw 327
 
225 jakw 328
    // 2D Points collected for OpenCV's calibration procedures
329
    std::vector< std::vector<cv::Point2f> > qc0, qc1, qc0Stereo, qc1Stereo;
207 flgw 330
 
236 jakw 331
    for(unsigned int i=0; i<nSets; i++){
207 flgw 332
 
225 jakw 333
        if(!calibrationData[i].selected)
334
            continue;
207 flgw 335
 
225 jakw 336
        // Note: avoiding push_back has only minor theoretical value
337
        if(!calibrationData[i].qc0.empty())
338
            qc0.push_back(calibrationData[i].qc0);
207 flgw 339
 
225 jakw 340
        if(!calibrationData[i].qc1.empty())
341
            qc1.push_back(calibrationData[i].qc1);
207 flgw 342
 
225 jakw 343
        if(!calibrationData[i].qc0.empty() && !calibrationData[i].qc1.empty()){
344
            qc0Stereo.push_back(calibrationData[i].qc0);
345
            qc1Stereo.push_back(calibrationData[i].qc1);
207 flgw 346
        }
22 jakw 347
    }
348
 
349
    // Generate world object coordinates [mm]
225 jakw 350
    std::vector<cv::Point3f> Qi = generateWorldCoords(checkerCount, settings.value("calibration/squareSize", 10.0).toFloat());
137 jakw 351
 
225 jakw 352
    std::vector< std::vector<cv::Point3f> > Q0(qc0.size(), Qi), Q1(qc1.size(), Qi), QStereo(qc0Stereo.size(), Qi);
22 jakw 353
 
225 jakw 354
    // Calibrate the cameras
31 jakw 355
    SMCalibrationParameters cal;
356
    cal.frameWidth = calibrationData[0].frame0.cols;
357
    cal.frameHeight = calibrationData[0].frame0.rows;
358
    cv::Size frameSize(cal.frameWidth, cal.frameHeight);
22 jakw 359
 
68 jakw 360
    // determine only k1, k2 for lens distortion
242 jakw 361
    int flags = cv::CALIB_FIX_ASPECT_RATIO + cv::CALIB_FIX_K2 + cv::CALIB_FIX_K3 + cv::CALIB_ZERO_TANGENT_DIST + cv::CALIB_FIX_PRINCIPAL_POINT;
225 jakw 362
 
33 jakw 363
    std::vector<cv::Mat> cam_rvecs0, cam_tvecs0;
225 jakw 364
 
365
    cal.cam0_error = cv::calibrateCamera(Q0, qc0, frameSize, cal.K0, cal.k0, cam_rvecs0, cam_tvecs0, cal.cam0_intrinsic_std, cal.cam0_extrinsic_std, cal.cam0_errors_per_view, flags,
134 jakw 366
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
86 jakw 367
 
33 jakw 368
    std::vector<cv::Mat> cam_rvecs1, cam_tvecs1;
225 jakw 369
    cal.cam1_error = cv::calibrateCamera(Q1, qc1, frameSize, cal.K1, cal.k1, cam_rvecs1, cam_tvecs1, cal.cam1_intrinsic_std, cal.cam1_extrinsic_std, cal.cam1_errors_per_view, flags,
134 jakw 370
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
225 jakw 371
 
372
    // Stereo calibration
136 jakw 373
    int flags_stereo = cv::CALIB_FIX_INTRINSIC;// + cv::CALIB_FIX_K2 + cv::CALIB_FIX_K3 + cv::CALIB_ZERO_TANGENT_DIST + cv::CALIB_FIX_PRINCIPAL_POINT + cv::CALIB_FIX_ASPECT_RATIO;
33 jakw 374
    cv::Mat E, F, R1, T1;
22 jakw 375
 
225 jakw 376
    #if CV_MAJOR_VERSION < 3
207 flgw 377
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
378
                                               frameSize, R1, T1, E, F,
379
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON),
380
                                               flags_stereo);
225 jakw 381
    #else
207 flgw 382
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
225 jakw 383
                                               frameSize, R1, T1, E, F, flags_stereo,
207 flgw 384
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON));
225 jakw 385
    #endif
207 flgw 386
 
33 jakw 387
    cal.R1 = R1;
388
    cal.T1 = T1;
389
    cal.E = E;
390
    cal.F = F;
391
 
225 jakw 392
    // Print to log
393
    std::stringstream out;
394
    out << "## Camera Calibration ##" << std::endl
395
        << "No. images used for intrinsics of cam0: " << qc0.size() << std::endl
396
        << "No. images used for intrinsics of cam1: " << qc1.size() << std::endl
397
        << "No. images used for stereo calibration: " << qc0Stereo.size() << std::endl;
398
    cal.printCamera(out);
399
    out << std::endl << std::endl;
400
    emit logMessage(QString::fromStdString(out.str()));
148 jakw 401
 
225 jakw 402
    // save to (reentrant) qsettings object
403
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
31 jakw 404
 
225 jakw 405
    emit done();
406
}
33 jakw 407
 
249 jakw 408
static void drawDetectedMarkersCharuco(cv::InputOutputArray _image, cv::InputArrayOfArrays _corners,
409
                                cv::InputArray _ids, cv::Scalar borderColor) {
91 jakw 410
 
249 jakw 411
    using namespace cv;
412
    using namespace std;
413
 
414
    CV_Assert(_image.getMat().total() != 0 &&
415
              (_image.getMat().channels() == 1 || _image.getMat().channels() == 3));
416
    CV_Assert((_corners.total() == _ids.total()) || _ids.total() == 0);
417
 
418
    // calculate colors
419
    Scalar textColor, cornerColor;
420
    textColor = cornerColor = borderColor;
421
    swap(textColor.val[0], textColor.val[1]);     // text color just sawp G and R
422
    swap(cornerColor.val[1], cornerColor.val[2]); // corner color just sawp G and B
423
 
424
    int nMarkers = (int)_corners.total();
425
    for(int i = 0; i < nMarkers; i++) {
426
        Mat currentMarker = _corners.getMat(i);
427
        CV_Assert(currentMarker.total() == 4 && currentMarker.type() == CV_32FC2);
428
 
429
        // draw marker sides
430
        for(int j = 0; j < 4; j++) {
431
            Point2f p0, p1;
432
            p0 = currentMarker.ptr< Point2f >(0)[j];
433
            p1 = currentMarker.ptr< Point2f >(0)[(j + 1) % 4];
434
            line(_image, p0, p1, borderColor, 2, LINE_AA);
435
        }
436
        // draw first corner mark
437
        rectangle(_image, currentMarker.ptr< Point2f >(0)[0] - Point2f(3, 3),
438
                  currentMarker.ptr< Point2f >(0)[0] + Point2f(3, 3), cornerColor, 1, LINE_AA);
439
 
440
        // draw ID
441
        if(_ids.total() != 0) {
442
            Point2f cent(0, 0);
443
            for(int p = 0; p < 4; p++)
444
                cent += currentMarker.ptr< Point2f >(0)[p];
445
            cent = cent / 4.;
446
            stringstream s;
447
            s << _ids.getMat().ptr< int >(0)[i];
448
            putText(_image, s.str(), cent, FONT_HERSHEY_SIMPLEX, 1, textColor, 2, LINE_AA);
449
        }
450
    }
451
}
452
 
453
static void drawDetectedCornersCharuco(cv::InputOutputArray _image, cv::InputArray _charucoCorners,
454
                                       cv::InputArray _charucoIds, cv::Scalar cornerColor) {
455
 
456
    using namespace cv;
457
    using namespace std;
458
 
459
    CV_Assert(_image.getMat().total() != 0 &&
460
              (_image.getMat().channels() == 1 || _image.getMat().channels() == 3));
461
    CV_Assert((_charucoCorners.getMat().total() == _charucoIds.getMat().total()) ||
462
              _charucoIds.getMat().total() == 0);
463
 
464
    unsigned int nCorners = (unsigned int)_charucoCorners.getMat().total();
465
    for(unsigned int i = 0; i < nCorners; i++) {
466
        Point2f corner = _charucoCorners.getMat().at< Point2f >(i);
467
 
468
        // draw first corner mark
469
        rectangle(_image, corner - Point2f(3, 3), corner + Point2f(3, 3), cornerColor, 2, LINE_AA);
470
 
471
        // draw ID
472
        if(_charucoIds.total() != 0) {
473
            int id = _charucoIds.getMat().at< int >(i);
474
            stringstream s;
475
            s << id;
476
            putText(_image, s.str(), corner + Point2f(5, -5), FONT_HERSHEY_SIMPLEX, 1.0,
477
                    cornerColor, 4, cv::LINE_AA);
478
        }
479
    }
480
}
481
 
482
 
250 jakw 483
static bool detectCheckerBoardCornersCharuco(const cv::Mat & frame,
484
                                            const cv::Ptr<cv::aruco::Dictionary> dict,
485
                                            const cv::Ptr<cv::aruco::CharucoBoard> board,
486
                                            const cv::Ptr<cv::aruco::DetectorParameters> parameters,
487
                                            cv::Mat& frameResult,
488
                                            std::vector<cv::Point2f>& qc,
489
                                            std::vector<int>& qci){
249 jakw 490
 
250 jakw 491
    // Convert to grayscale
492
    cv::Mat gray;
493
    if(frame.channels() == 1)
494
        cv::cvtColor(frame, gray, CV_BayerBG2GRAY);
495
    else
496
        cv::cvtColor(frame, gray, CV_RGB2GRAY);
249 jakw 497
 
498
 
250 jakw 499
    std::vector<std::vector<cv::Point2f>> mc;
500
    std::vector<int> mi;
249 jakw 501
 
250 jakw 502
    cv::Mat grayBlurred;
503
    cv::GaussianBlur(gray, grayBlurred, cv::Size(0, 0), 3);
249 jakw 504
 
250 jakw 505
    // Extract checker corners
506
    cv::aruco::detectMarkers(grayBlurred, dict, mc, mi, parameters);
507
    //std::vector<std::vector<cv::Point2f>> mc, rejecti;
508
    //cv::aruco::refineDetectedMarkers(gray0, board, mc0, mi0, rejecti0);
249 jakw 509
 
250 jakw 510
    //cv::Mat cci, cidsi;
511
    cv::aruco::interpolateCornersCharuco(mc, mi, gray, board, qc, qci, cv::noArray(), cv::noArray(), 1);
249 jakw 512
 
250 jakw 513
    bool success = (qc.size() >= 4);
514
    if(success){
515
        cv::cornerSubPix(gray, qc, cv::Size(6, 6), cv::Size(1, 1), cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 20, 0.0001));
516
        // Draw colored chessboard
517
        if(frame.channels() == 1)
518
            cv::cvtColor(frame, frameResult, CV_BayerBG2RGB);
519
        else
520
            frameResult = frame.clone();
249 jakw 521
 
250 jakw 522
        // Draw colored chessboard
523
        drawDetectedMarkersCharuco(frameResult, mc, mi, cv::Scalar(0, 255, 0));
524
        drawDetectedCornersCharuco(frameResult, qc, qci, cv::Scalar(0, 255, 0));
525
    } else {
526
        qc.clear();
527
    }
249 jakw 528
 
250 jakw 529
    return success;
249 jakw 530
 
250 jakw 531
}
249 jakw 532
 
250 jakw 533
void SMCalibrationWorker::checkerboardDetectionCharuco(SMCalibrationSet calibrationSet){
534
 
535
    QSettings settings;
536
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
537
    const float checkerSize = settings.value("calibration/squareSize", 10.0).toFloat();
538
    float markerLength = 0.8f*checkerSize;
539
 
540
    // Charuco board and dictionary
541
    cv::Ptr<cv::aruco::Dictionary> dict = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_6X6_250);
249 jakw 542
    cv::Ptr<cv::aruco::CharucoBoard> board = cv::aruco::CharucoBoard::create(checkerCount.width+1, checkerCount.height+1, checkerSize, markerLength, dict);
543
 
250 jakw 544
    //    cv::Mat boardImg;
545
    //    board->draw(cv::Size((saddlePointCountX+1)*100, (saddlePointCountY+1)*100), boardImg, 0, 1);
546
    //    cv::Mat boardImgRes;
547
    //    cv::resize(boardImg, boardImgRes, cv::Size((saddlePointCountX+1)*10, (saddlePointCountY+1)*10), 0, 0, cv::INTER_NEAREST);
548
    //    cv::imwrite("boardImg.png", boardImg);
549
    //    cv::imwrite("boardImgRes.png", boardImgRes);
249 jakw 550
 
551
    cv::Ptr<cv::aruco::DetectorParameters> parameters = cv::aruco::DetectorParameters::create();
250 jakw 552
//    parameters->adaptiveThreshWinSizeMin = 3;
553
//    parameters->adaptiveThreshWinSizeMax = 153;
554
//    parameters->adaptiveThreshWinSizeStep = 5;
249 jakw 555
//    parameters->adaptiveThreshConstant = 20;
556
//    parameters->minMarkerPerimeterRate = 0.01;
557
    parameters->maxMarkerPerimeterRate = 5.0;
558
//    parameters->minCornerDistanceRate = 0.10;
559
//    parameters->perspectiveRemovePixelPerCell = 6;
560
//    parameters->maxErroneousBitsInBorderRate = 0.8;
561
//    parameters->minOtsuStdDev = 1;
562
//    parameters->errorCorrectionRate = 0.1;
250 jakw 563
    parameters->cornerRefinementWinSize = 10;
249 jakw 564
 
250 jakw 565
    bool success0 = detectCheckerBoardCornersCharuco(calibrationSet.frame0, dict, board, parameters, calibrationSet.frame0Result, calibrationSet.qc0, calibrationSet.qc0id);
566
    if(!success0){
567
        emit logMessage(QString("Could not detect  Charuco corners on set %1 camera0").arg(calibrationSet.id));
568
        std::cerr << "Could not detect Charuco corners on set " << calibrationSet.id << " camera0" << std::endl;
569
    }
249 jakw 570
 
250 jakw 571
    bool success1 = detectCheckerBoardCornersCharuco(calibrationSet.frame1, dict, board, parameters, calibrationSet.frame1Result, calibrationSet.qc1, calibrationSet.qc1id);
572
    if(!success1){
573
        emit logMessage(QString("Could not detect Charuco corners on set %1 camera1").arg(calibrationSet.id));
574
        std::cerr << "Could not detect Charuco corners on set " << calibrationSet.id << " camera1" << std::endl;
575
    }
249 jakw 576
 
250 jakw 577
    emit newCheckerboardResult(calibrationSet.id, calibrationSet);
249 jakw 578
 
250 jakw 579
}
249 jakw 580
 
250 jakw 581
void SMCalibrationWorker::cameraCalibrationCharuco(std::vector<SMCalibrationSet> calibrationData){
249 jakw 582
 
250 jakw 583
    QSettings settings;
249 jakw 584
 
250 jakw 585
    // Number of saddle points on calibration pattern
586
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
587
    const float checkerSize = settings.value("calibration/squareSize", 10.0).toFloat();
588
    float markerLength = 0.8f*checkerSize;
249 jakw 589
 
250 jakw 590
    cv::Ptr<cv::aruco::Dictionary> dict = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_6X6_250);
591
    cv::Ptr<cv::aruco::CharucoBoard> board = cv::aruco::CharucoBoard::create(checkerCount.width+1, checkerCount.height+1, checkerSize, markerLength, dict);
249 jakw 592
 
250 jakw 593
    auto nSets = calibrationData.size();
249 jakw 594
 
250 jakw 595
    // 2D Points collected for OpenCV's calibration procedures
596
    std::vector< std::vector<cv::Point2f> > qc0, qc1;
597
    std::vector< std::vector<cv::Point2f> > qc0Stereo, qc1Stereo;
249 jakw 598
 
250 jakw 599
    // 3D object points
600
    std::vector< std::vector<cv::Point3f> > Q0, Q1, QStereo;
249 jakw 601
 
250 jakw 602
    // Loop through calibration sets
603
    for(unsigned int i=0; i<nSets; i++){
249 jakw 604
 
250 jakw 605
        if(!calibrationData[i].selected)
606
            continue;
249 jakw 607
 
250 jakw 608
        bool success0 = !calibrationData[i].qc0.empty();
609
        bool success1 = !calibrationData[i].qc1.empty();
249 jakw 610
 
611
        if(success0){
612
            std::vector<cv::Point3f> Q0i;
250 jakw 613
            for(std::size_t j=0; j<calibrationData[i].qc0id.size(); j++){
614
                int id = calibrationData[i].qc0id[j];
249 jakw 615
                Q0i.push_back(board->chessboardCorners[id]);
616
            }
617
 
250 jakw 618
            qc0.push_back(calibrationData[i].qc0);
249 jakw 619
            Q0.push_back(Q0i);
620
        }
621
 
622
        if(success1){
623
            std::vector<cv::Point3f> Q1i;
250 jakw 624
            for(std::size_t j=0; j<calibrationData[i].qc1id.size(); j++){
625
                int id = calibrationData[i].qc1id[j];
249 jakw 626
                Q1i.push_back(board->chessboardCorners[id]);
627
            }
628
 
250 jakw 629
            qc1.push_back(calibrationData[i].qc1);
249 jakw 630
            Q1.push_back(Q1i);
631
        }
632
 
633
        if(success0 && success1){
634
 
635
            std::vector<cv::Point2f> qc0iStereo, qc1iStereo;
636
            std::vector<cv::Point3f> QiStereo;
637
 
638
            int j0 = 0;
639
            int j1 = 0;
250 jakw 640
            while(j0<calibrationData[i].qc0.size() && j1<calibrationData[i].qc1.size()){
249 jakw 641
 
250 jakw 642
                int id0 = calibrationData[i].qc0id[j0];
643
                int id1 = calibrationData[i].qc1id[j1];
249 jakw 644
 
645
                if(id0 < id1)
646
                    j0++;
647
                else if (id1 < id0)
648
                    j1++;
649
                else{
650
                    assert(id0 == id1);
250 jakw 651
                    qc0iStereo.push_back(calibrationData[i].qc0[j0]);
652
                    qc1iStereo.push_back(calibrationData[i].qc1[j1]);
249 jakw 653
                    QiStereo.push_back(board->chessboardCorners[id0]);
654
                    j0++;
655
                    j1++;
656
                }
657
 
658
            }
659
 
660
            if(QiStereo.size() > 0){
661
                qc0Stereo.push_back(qc0iStereo);
662
                qc1Stereo.push_back(qc1iStereo);
663
                QStereo.push_back(QiStereo);
664
            }
665
        }
666
 
667
    }
668
 
669
    size_t nValidSets = qc0Stereo.size();
670
    if(nValidSets < 2){
671
        std::cerr << "Not enough valid calibration sequences!" << std::endl;
672
        emit done();
673
        return;
674
    }
675
 
676
 
677
    // calibrate the cameras
678
    SMCalibrationParameters cal;
679
    cal.frameWidth = calibrationData[0].frame0.cols;
680
    cal.frameHeight = calibrationData[0].frame0.rows;
681
    cv::Size frameSize(cal.frameWidth, cal.frameHeight);
682
 
683
    // determine only k1, k2 for lens distortion
250 jakw 684
    int flags = cv::CALIB_FIX_ASPECT_RATIO + cv::CALIB_FIX_K3 + cv::CALIB_ZERO_TANGENT_DIST + cv::CALIB_FIX_PRINCIPAL_POINT;
249 jakw 685
 
686
    // Note: several of the output arguments below must be cv::Mat, otherwise segfault
687
    std::vector<cv::Mat> cam_rvecs0, cam_tvecs0;
688
    cal.cam0_error = cv::calibrateCamera(Q0, qc0, frameSize, cal.K0, cal.k0, cam_rvecs0, cam_tvecs0, cal.cam0_intrinsic_std, cal.cam0_extrinsic_std, cal.cam0_errors_per_view, flags,
689
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
690
 
691
    std::vector<cv::Mat> cam_rvecs1, cam_tvecs1;
692
    cal.cam1_error = cv::calibrateCamera(Q1, qc1, frameSize, cal.K1, cal.k1, cam_rvecs1, cam_tvecs1, cal.cam1_intrinsic_std, cal.cam1_extrinsic_std, cal.cam1_errors_per_view, flags,
693
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
694
 
695
    // stereo calibration
696
    int flags_stereo = cv::CALIB_FIX_INTRINSIC;// + cv::CALIB_FIX_K2 + cv::CALIB_FIX_K3 + cv::CALIB_ZERO_TANGENT_DIST + cv::CALIB_FIX_PRINCIPAL_POINT + cv::CALIB_FIX_ASPECT_RATIO;
697
    cv::Mat E, F, R1, T1;
698
 
699
    #if CV_MAJOR_VERSION < 3
700
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
701
                                               frameSize, R1, T1, E, F,
702
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON),
703
                                               flags_stereo);
704
    #else
705
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
706
                                               frameSize, R1, T1, E, F, flags_stereo,
707
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON));
708
    #endif
709
 
710
    cal.R1 = R1;
711
    cal.T1 = T1;
712
    cal.E = E;
713
    cal.F = F;
714
 
715
    // Print to log
716
    std::stringstream out;
717
    out << "## Camera Calibration ##" << std::endl
718
        << "No. images used for intrinsics of cam0: " << qc0.size() << std::endl
719
        << "No. images used for intrinsics of cam1: " << qc1.size() << std::endl
720
        << "No. images used for stereo calibration: " << qc0Stereo.size() << std::endl;
721
    cal.printCamera(out);
722
    out << std::endl << std::endl;
723
    emit logMessage(QString::fromStdString(out.str()));
724
 
725
    // save to (reentrant qsettings object)
726
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
727
 
728
    emit done();
729
 
730
}
731
 
732
 
225 jakw 733
void SMCalibrationWorker::rotationStageCalibration(std::vector<SMCalibrationSet> calibrationData){
91 jakw 734
 
250 jakw 735
    auto nSets = calibrationData.size();
91 jakw 736
 
225 jakw 737
    std::vector< std::vector<cv::Point2f> > qc0Stereo, qc1Stereo;
250 jakw 738
    std::vector<cv::Point3f> Qi;
91 jakw 739
 
250 jakw 740
    QSettings settings;
741
    // Generate world object coordinates [mm]
742
    const cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(),settings.value("calibration/patternSizeY", 13).toInt()));
743
    const float checkerSize = settings.value("calibration/squareSize", 10.0).toFloat();
91 jakw 744
 
250 jakw 745
    if(settings.value("calibration/method").toString() == "Charuco"){
746
 
747
        // Find id's which were detected in all images
748
        std::vector<int> ids;
749
 
750
        for(int i=0; i<calibrationData.size(); i++){
751
 
752
            if(!calibrationData[i].selected)
753
                continue;
754
 
755
            if(ids.empty()){
756
                ids = calibrationData[i].qc0id;
757
            }
758
 
759
            std::vector<int> idsi0;
760
            std::set_intersection(ids.begin(), ids.end(), calibrationData[i].qc0id.begin(), calibrationData[i].qc0id.end(), std::back_inserter(idsi0));
761
            ids = idsi0;
762
            std::vector<int> idsi1;
763
            std::set_intersection(ids.begin(), ids.end(), calibrationData[i].qc1id.begin(), calibrationData[i].qc1id.end(), std::back_inserter(idsi1));
764
            ids = idsi1;
225 jakw 765
        }
33 jakw 766
 
250 jakw 767
        if(ids.size() < 2){
768
            std::cerr << "Not enough feature points present in all images for rotation axis determination!" << std::endl;
769
            emit logMessage("Not enough feature points present in all images for rotation axis determination! Deselect some calibration images.");
770
        }
81 jakw 771
 
250 jakw 772
        for(int i=0; i<calibrationData.size(); i++){
91 jakw 773
 
250 jakw 774
            if(!calibrationData[i].selected)
775
                continue;
81 jakw 776
 
250 jakw 777
            std::vector<cv::Point2f> qc0StereoI, qc1StereoI;
778
            for(int j=0; j<ids.size(); j++){
225 jakw 779
 
250 jakw 780
                ptrdiff_t idx0 = std::find(calibrationData[i].qc0id.begin(), calibrationData[i].qc0id.end(), ids[j]) - calibrationData[i].qc0id.begin();
781
                ptrdiff_t idx1 = std::find(calibrationData[i].qc1id.begin(), calibrationData[i].qc1id.end(), ids[j]) - calibrationData[i].qc1id.begin();
81 jakw 782
 
250 jakw 783
                qc0StereoI.push_back(calibrationData[i].qc0[idx0]);
784
                qc1StereoI.push_back(calibrationData[i].qc1[idx1]);
81 jakw 785
 
250 jakw 786
            }
33 jakw 787
 
250 jakw 788
            qc0Stereo.push_back(qc0StereoI);
789
            qc1Stereo.push_back(qc1StereoI);
207 flgw 790
        }
81 jakw 791
 
250 jakw 792
        float markerLength = 0.8f*checkerSize;
84 jakw 793
 
250 jakw 794
        cv::Ptr<cv::aruco::Dictionary> dict = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_6X6_250);
795
        cv::Ptr<cv::aruco::CharucoBoard> board = cv::aruco::CharucoBoard::create(checkerCount.width+1, checkerCount.height+1, checkerSize, markerLength, dict);
84 jakw 796
 
250 jakw 797
        for(int j=0; j<ids.size(); j++){
798
            Qi.push_back(board->chessboardCorners[ids[j]]);
799
        }
207 flgw 800
 
225 jakw 801
    } else {
250 jakw 802
 
803
        // Normal checkerboard with all corners
804
        for(auto i=0; i<nSets; i++){
805
 
806
            if(!calibrationData[i].selected)
807
                continue;
808
 
809
            if(!calibrationData[i].qc0.empty() && !calibrationData[i].qc1.empty()){
810
                qc0Stereo.push_back(calibrationData[i].qc0);
811
                qc1Stereo.push_back(calibrationData[i].qc1);
812
            }
813
        }
814
 
815
        Qi = generateWorldCoords(checkerCount, checkerSize);
816
 
91 jakw 817
    }
225 jakw 818
 
250 jakw 819
    SMCalibrationParameters cal = settings.value("calibration/parameters").value<SMCalibrationParameters>();
820
 
821
    if(qc0Stereo.size() <= 2){
822
        std::cerr << "Not enough images for rotation axis determination!" << std::endl;
823
        emit logMessage("Not enough images for rotation axis determination!");
824
 
825
       cal.Rr = cv::Matx33f::eye();
826
       cal.Tr = cv::Vec3f(0,0,0);
827
       cal.rot_axis_error = -1;
828
 
829
       emit done();
830
       return;
831
    }
832
 
833
    // Direct rotation axis calibration //
834
    // full camera matrices
835
    cv::Matx34f P0 = cv::Matx34f::eye();
836
    cv::Mat RT1(3, 4, CV_32F);
837
    cv::Mat(cal.R1).copyTo(RT1(cv::Range(0, 3), cv::Range(0, 3)));
838
    cv::Mat(cal.T1).copyTo(RT1(cv::Range(0, 3), cv::Range(3, 4)));
839
    cv::Matx34f P1 = cv::Matx34f(RT1);
840
 
841
    // calibration points in camera 0 frame
842
    std::vector< std::vector<cv::Point3f> > Qcam(qc0Stereo.size());
843
 
844
    #pragma omp parallel for
845
    for(unsigned int i=0; i<qc0Stereo.size(); i++){
846
        std::vector<cv::Point2f> qc0i, qc1i;
847
 
848
        cv::undistortPoints(qc0Stereo[i], qc0i, cal.K0, cal.k0);
849
        cv::undistortPoints(qc1Stereo[i], qc1i, cal.K1, cal.k1);
850
 
851
        cv::Mat Qhom, Qcami;
852
        cv::triangulatePoints(P0, P1, qc0i, qc1i, Qhom);
853
        cvtools::convertMatFromHomogeneous(Qhom, Qcami);
854
        std::vector<cv::Point3f> QcamiPoints;
855
        cvtools::matToPoints3f(Qcami, QcamiPoints);
856
 
857
        Qcam[i] = QcamiPoints;
858
    }
859
 
860
    cv::Vec3f axis, point;
861
    float rot_axis_error;
862
    rotationAxisEstimation(Qcam, Qi, axis, point);
863
    rotationAxisOptimization(Qcam, Qi, axis, point, rot_axis_error);
864
 
865
    // construct transformation matrix
866
    cv::Vec3f ex = axis.cross(cv::Vec3f(0,0,1.0));
867
    ex = cv::normalize(ex);
868
    cv::Vec3f ez = ex.cross(axis);
869
    ez = cv::normalize(ez);
870
 
871
    cv::Mat RrMat(3, 3, CV_32F);
872
    cv::Mat(ex).copyTo(RrMat.col(0));
873
    cv::Mat(axis).copyTo(RrMat.col(1));
874
    cv::Mat(ez).copyTo(RrMat.col(2));
875
 
876
    cal.Rr = cv::Matx33f(RrMat).t();
877
    cal.Tr = -cv::Matx33f(RrMat).t()*point;
878
    cal.rot_axis_error = rot_axis_error;
879
 
225 jakw 880
    // Print to log
881
    std::stringstream out;
882
    out << "## Rotation Stage Calibration ##" << std::endl
883
        << "No. images used for calibration: " << qc0Stereo.size() << std::endl;
884
    cal.printRotationStage(out);
885
    out << std::endl << std::endl;
886
    emit logMessage(QString::fromStdString(out.str()));
887
 
888
    // Save to (reentrant) qsettings object
889
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
890
 
891
    emit done();
22 jakw 892
}