Subversion Repositories seema-scanner

Rev

Rev 249 | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 249 Rev 250
1
#include "SMCalibrationWorker.h"
1
#include "SMCalibrationWorker.h"
2
#include "SMCalibrationParameters.h"
2
#include "SMCalibrationParameters.h"
3
 
3
 
4
#include "cvtools.h"
4
#include "cvtools.h"
5
 
5
 
6
#include <opencv2/aruco/charuco.hpp>
6
#include <opencv2/aruco/charuco.hpp>
7
 
7
 
8
#include <QSettings>
8
#include <QSettings>
9
#include <QTextStream>
9
#include <QTextStream>
10
 
10
 
11
#include <ceres/ceres.h>
11
#include <ceres/ceres.h>
12
 
12
 
13
// Closed form solution to solve for the rotation axis from sets of 3D point coordinates of flat pattern feature points
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
14
// Algorithm according to Chen et al., Rotation axis calibration of a turntable using constrained global optimization, Optik 2014
15
// DTU, 2014, Jakob Wilm
15
// DTU, 2014, Jakob Wilm
16
static void rotationAxisEstimation(const std::vector< std::vector<cv::Point3f> > Qcam,
16
static void rotationAxisEstimation(const std::vector< std::vector<cv::Point3f> > Qcam,
17
                                   const std::vector<cv::Point3f> Qobj,
17
                                   const std::vector<cv::Point3f> Qobj,
18
                                   cv::Vec3f &axis, cv::Vec3f &point){
18
                                   cv::Vec3f &axis, cv::Vec3f &point){
19
    assert(Qobj.size() == Qcam[0].size());
19
    assert(Qobj.size() == Qcam[0].size());
20
 
20
 
21
    // number of frames (points on each arch)
21
    // number of frames (points on each arch)
22
    int l = Qcam.size();
22
    auto l = Qcam.size();
23
 
23
 
24
    // number of points in each frame
24
    // number of points in each frame
25
    size_t mn = Qobj.size();
25
    size_t mn = Qobj.size();
26
 
26
 
27
    // construct matrix for axis determination
27
    // construct matrix for axis determination
28
    cv::Mat M(6, 6, CV_32F, cv::Scalar(0));
28
    cv::Mat M(6, 6, CV_32F, cv::Scalar(0));
29
 
29
 
30
    for(int k=0; k<l; k++){
30
    for(int k=0; k<l; k++){
31
        for(unsigned int idx=0; idx<mn; idx++){
31
        for(unsigned int idx=0; idx<mn; idx++){
32
 
32
 
33
            //            float i = Qobj[idx].x+4;
33
            //            float i = Qobj[idx].x+4;
34
            //            float j = Qobj[idx].y+4;
34
            //            float j = Qobj[idx].y+4;
35
            float i = Qobj[idx].x;
35
            float i = Qobj[idx].x;
36
            float j = Qobj[idx].y;
36
            float j = Qobj[idx].y;
37
 
37
 
38
            float x = Qcam[k][idx].x;
38
            float x = Qcam[k][idx].x;
39
            float y = Qcam[k][idx].y;
39
            float y = Qcam[k][idx].y;
40
            float z = Qcam[k][idx].z;
40
            float z = Qcam[k][idx].z;
41
 
41
 
42
            M += (cv::Mat_<float>(6,6) << x*x, x*y, x*z, x, i*x, j*x,
42
            M += (cv::Mat_<float>(6,6) << x*x, x*y, x*z, x, i*x, j*x,
43
                  0, y*y, y*z, y, i*y, j*y,
43
                  0, y*y, y*z, y, i*y, j*y,
44
                  0,   0, z*z, z, i*z, j*z,
44
                  0,   0, z*z, z, i*z, j*z,
45
                  0,   0,   0, 1,   i,   j,
45
                  0,   0,   0, 1,   i,   j,
46
                  0,   0,   0, 0, i*i, i*j,
46
                  0,   0,   0, 0, i*i, i*j,
47
                  0,   0,   0, 0,   0, j*j);
47
                  0,   0,   0, 0,   0, j*j);
48
 
48
 
49
        }
49
        }
50
    }
50
    }
51
 
51
 
52
    cv::completeSymm(M, false);
52
    cv::completeSymm(M, false);
53
 
53
 
54
    // solve for axis
54
    // solve for axis
55
    std::vector<float> lambda;
55
    std::vector<float> lambda;
56
    cv::Mat u;
56
    cv::Mat u;
57
    cv::eigen(M, lambda, u);
57
    cv::eigen(M, lambda, u);
58
 
58
 
59
    float minLambda = std::abs(lambda[0]);
59
    float minLambda = std::abs(lambda[0]);
60
    int idx = 0;
60
    int idx = 0;
61
    for(unsigned int i=1; i<lambda.size(); i++){
61
    for(unsigned int i=1; i<lambda.size(); i++){
62
        if(abs(lambda[i]) < minLambda){
62
        if(abs(lambda[i]) < minLambda){
63
            minLambda = lambda[i];
63
            minLambda = lambda[i];
64
            idx = i;
64
            idx = i;
65
        }
65
        }
66
    }
66
    }
67
 
67
 
68
    axis = u.row(idx).colRange(0, 3);
68
    axis = u.row(idx).colRange(0, 3);
69
    axis = cv::normalize(axis);
69
    axis = cv::normalize(axis);
70
 
70
 
71
    float nx = u.at<float>(idx, 0);
71
    float nx = u.at<float>(idx, 0);
72
    float ny = u.at<float>(idx, 1);
72
    float ny = u.at<float>(idx, 1);
73
    float nz = u.at<float>(idx, 2);
73
    float nz = u.at<float>(idx, 2);
74
    //float d  = u.at<float>(idx, 3);
74
    //float d  = u.at<float>(idx, 3);
75
    float dh = u.at<float>(idx, 4);
75
    float dh = u.at<float>(idx, 4);
76
    float dv = u.at<float>(idx, 5);
76
    float dv = u.at<float>(idx, 5);
77
 
77
 
78
    // Paper version: c is initially eliminated
78
    // Paper version: c is initially eliminated
79
    /*cv::Mat A(l*mn, mn+2, CV_32F, cv::Scalar(0.0));
79
    /*cv::Mat A(l*mn, mn+2, CV_32F, cv::Scalar(0.0));
80
        cv::Mat bb(l*mn, 1, CV_32F);
80
        cv::Mat bb(l*mn, 1, CV_32F);
81
 
81
 
82
        for(int k=0; k<l; k++){
82
        for(int k=0; k<l; k++){
83
            for(unsigned int idx=0; idx<mn; idx++){
83
            for(unsigned int idx=0; idx<mn; idx++){
84
 
84
 
85
                float i = Qobj[idx].x;
85
                float i = Qobj[idx].x;
86
                float j = Qobj[idx].y;
86
                float j = Qobj[idx].y;
87
 
87
 
88
                float x = Qcam[k][idx].x;
88
                float x = Qcam[k][idx].x;
89
                float y = Qcam[k][idx].y;
89
                float y = Qcam[k][idx].y;
90
                float z = Qcam[k][idx].z;
90
                float z = Qcam[k][idx].z;
91
 
91
 
92
                float f = x*x + y*y + z*z + (2*x*nx + 2*y*ny + 2*z*nz)*(i*dh + j*dv);
92
                float f = x*x + y*y + z*z + (2*x*nx + 2*y*ny + 2*z*nz)*(i*dh + j*dv);
93
 
93
 
94
                int row = k*mn+idx;
94
                int row = k*mn+idx;
95
                A.at<float>(row, 0) = 2*x - (2*z*nx)/nz;
95
                A.at<float>(row, 0) = 2*x - (2*z*nx)/nz;
96
                A.at<float>(row, 1) = 2*y - (2*z*ny)/nz;
96
                A.at<float>(row, 1) = 2*y - (2*z*ny)/nz;
97
                A.at<float>(row, idx+2) = 1.0;
97
                A.at<float>(row, idx+2) = 1.0;
98
 
98
 
99
                bb.at<float>(row, 0) = f + (2*z*d)/nz;
99
                bb.at<float>(row, 0) = f + (2*z*d)/nz;
100
            }
100
            }
101
        }
101
        }
102
 
102
 
103
        // solve for point
103
        // solve for point
104
        cv::Mat abe;
104
        cv::Mat abe;
105
        cv::solve(A, bb, abe, cv::DECOMP_SVD);
105
        cv::solve(A, bb, abe, cv::DECOMP_SVD);
106
 
106
 
107
        float a = abe.at<float>(0, 0);
107
        float a = abe.at<float>(0, 0);
108
        float b = abe.at<float>(1, 0);
108
        float b = abe.at<float>(1, 0);
109
        float c = -(nx*a+ny*b+d)/nz;
109
        float c = -(nx*a+ny*b+d)/nz;
110
        */
110
        */
111
 
111
 
112
    // Our version: solve simultanously for a,b,c
112
    // Our version: solve simultanously for a,b,c
113
    cv::Mat A(l*mn, mn+3, CV_32F, cv::Scalar(0.0));
113
    cv::Mat A(l*mn, mn+3, CV_32F, cv::Scalar(0.0));
114
    cv::Mat bb(l*mn, 1, CV_32F);
114
    cv::Mat bb(l*mn, 1, CV_32F);
115
 
115
 
116
    for(int k=0; k<l; k++){
116
    for(int k=0; k<l; k++){
117
        for(unsigned int idx=0; idx<mn; idx++){
117
        for(unsigned int idx=0; idx<mn; idx++){
118
 
118
 
119
            float i = Qobj[idx].x;
119
            float i = Qobj[idx].x;
120
            float j = Qobj[idx].y;
120
            float j = Qobj[idx].y;
121
 
121
 
122
            float x = Qcam[k][idx].x;
122
            float x = Qcam[k][idx].x;
123
            float y = Qcam[k][idx].y;
123
            float y = Qcam[k][idx].y;
124
            float z = Qcam[k][idx].z;
124
            float z = Qcam[k][idx].z;
125
 
125
 
126
            float f = x*x + y*y + z*z + (2*x*nx + 2*y*ny + 2*z*nz)*(i*dh + j*dv);
126
            float f = x*x + y*y + z*z + (2*x*nx + 2*y*ny + 2*z*nz)*(i*dh + j*dv);
127
 
127
 
128
            int row = k*mn+idx;
128
            int row = k*mn+idx;
129
            A.at<float>(row, 0) = 2*x;
129
            A.at<float>(row, 0) = 2*x;
130
            A.at<float>(row, 1) = 2*y;
130
            A.at<float>(row, 1) = 2*y;
131
            A.at<float>(row, 2) = 2*z;
131
            A.at<float>(row, 2) = 2*z;
132
            A.at<float>(row, idx+3) = 1.0;
132
            A.at<float>(row, idx+3) = 1.0;
133
 
133
 
134
            bb.at<float>(row, 0) = f;
134
            bb.at<float>(row, 0) = f;
135
        }
135
        }
136
    }
136
    }
137
 
137
 
138
    // solve for point
138
    // solve for point
139
    cv::Mat abe;
139
    cv::Mat abe;
140
    cv::solve(A, bb, abe, cv::DECOMP_SVD);
140
    cv::solve(A, bb, abe, cv::DECOMP_SVD);
141
 
141
 
142
    float a = abe.at<float>(0, 0);
142
    float a = abe.at<float>(0, 0);
143
    float b = abe.at<float>(1, 0);
143
    float b = abe.at<float>(1, 0);
144
    float c = abe.at<float>(2, 0);
144
    float c = abe.at<float>(2, 0);
145
 
145
 
146
    point[0] = a;
146
    point[0] = a;
147
    point[1] = b;
147
    point[1] = b;
148
    point[2] = c;
148
    point[2] = c;
149
 
149
 
150
}
150
}
151
 
151
 
152
struct CircleResidual {
152
struct CircleResidual {
153
    CircleResidual(std::vector<cv::Point3f> _pointsOnArc)
153
    CircleResidual(std::vector<cv::Point3f> _pointsOnArc)
154
        : pointsOnArc(_pointsOnArc) {}
154
        : pointsOnArc(_pointsOnArc) {}
155
 
155
 
156
    template <typename T>
156
    template <typename T>
157
    bool operator()(const T* point, const T* axis, T* residual) const {
157
    bool operator()(const T* point, const T* axis, T* residual) const {
158
 
158
 
159
        T axisSqNorm = axis[0]*axis[0] + axis[1]*axis[1] + axis[2]*axis[2];
159
        T axisSqNorm = axis[0]*axis[0] + axis[1]*axis[1] + axis[2]*axis[2];
160
 
160
 
161
        unsigned int l = pointsOnArc.size();
161
        unsigned int l = pointsOnArc.size();
162
        std::vector<T> dI(l);
162
        std::vector<T> dI(l);
163
 
163
 
164
        // note, this is automatically initialized to 0
164
        // note, this is automatically initialized to 0
165
        T sum(0.0);
165
        T sum(0.0);
166
 
166
 
167
        for(unsigned int i=0; i<l; i++){
167
        for(unsigned int i=0; i<l; i++){
168
            cv::Point3d p = pointsOnArc[i];
168
            cv::Point3d p = pointsOnArc[i];
169
            //T p[3] = {pointsOnArc[i].x, pointsOnArc[i].y, pointsOnArc[i].z};
169
            //T p[3] = {pointsOnArc[i].x, pointsOnArc[i].y, pointsOnArc[i].z};
170
 
170
 
171
            // point to line distance
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];
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);
173
            T dIx = point[0] - p.x - (dotProd*axis[0]/axisSqNorm);
174
            T dIy = point[1] - p.y - (dotProd*axis[1]/axisSqNorm);
174
            T dIy = point[1] - p.y - (dotProd*axis[1]/axisSqNorm);
175
            T dIz = point[2] - p.z - (dotProd*axis[2]/axisSqNorm);
175
            T dIz = point[2] - p.z - (dotProd*axis[2]/axisSqNorm);
176
            dI[i] = ceres::sqrt(dIx*dIx + dIy*dIy + dIz*dIz);
176
            dI[i] = ceres::sqrt(dIx*dIx + dIy*dIy + dIz*dIz);
177
 
177
 
178
            sum += dI[i];
178
            sum += dI[i];
179
        }
179
        }
180
 
180
 
181
        T mean = sum / double(l);
181
        T mean = sum / double(l);
182
 
182
 
183
        for(unsigned int i=0; i<l; i++){
183
        for(unsigned int i=0; i<l; i++){
184
            residual[i] = dI[i] - mean;
184
            residual[i] = dI[i] - mean;
185
        }
185
        }
186
 
186
 
187
        return true;
187
        return true;
188
    }
188
    }
189
 
189
 
190
    private:
190
    private:
191
        // Observations for one checkerboard corner.
191
        // Observations for one checkerboard corner.
192
        const std::vector<cv::Point3f> pointsOnArc;
192
        const std::vector<cv::Point3f> pointsOnArc;
193
};
193
};
194
 
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){
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
 
196
 
197
    // number of frames (points on each arch)
197
    // number of frames (points on each arch)
198
    size_t l = Qcam.size();
198
    size_t l = Qcam.size();
199
 
199
 
200
    // number of points in each frame
200
    // number of points in each frame
201
    size_t mn = Qobj.size();
201
    size_t mn = Qobj.size();
202
 
202
 
203
    // read initial guess
203
    // read initial guess
204
    double pointArray[] = {point[0], point[1], point[2]};
204
    double pointArray[] = {point[0], point[1], point[2]};
205
    double axisArray[] = {axis[0], axis[1], axis[2]};
205
    double axisArray[] = {axis[0], axis[1], axis[2]};
206
 
206
 
207
    ceres::Problem problem;
207
    ceres::Problem problem;
208
 
208
 
209
    // loop through saddle points
209
    // loop through saddle points
210
    for(unsigned int idx=0; idx<mn; idx++){
210
    for(unsigned int idx=0; idx<mn; idx++){
211
        std::vector<cv::Point3f> pointsOnArch(l);
211
        std::vector<cv::Point3f> pointsOnArch(l);
212
        for(unsigned int k=0; k<l; k++){
212
        for(unsigned int k=0; k<l; k++){
213
            pointsOnArch[k] = Qcam[k][idx];
213
            pointsOnArch[k] = Qcam[k][idx];
214
        }
214
        }
215
        ceres::CostFunction* cost_function =
215
        ceres::CostFunction* cost_function =
216
                new ceres::AutoDiffCostFunction<CircleResidual, ceres::DYNAMIC, 3, 3>(
216
                new ceres::AutoDiffCostFunction<CircleResidual, ceres::DYNAMIC, 3, 3>(
217
                    new CircleResidual(pointsOnArch), l);
217
                    new CircleResidual(pointsOnArch), l);
218
        problem.AddResidualBlock(cost_function, NULL, pointArray, axisArray);
218
        problem.AddResidualBlock(cost_function, NULL, pointArray, axisArray);
219
    }
219
    }
220
 
220
 
221
    // Run the solver!
221
    // Run the solver!
222
    ceres::Solver::Options options;
222
    ceres::Solver::Options options;
223
    options.linear_solver_type = ceres::DENSE_QR;
223
    options.linear_solver_type = ceres::DENSE_QR;
224
    options.minimizer_progress_to_stdout = true;
224
    options.minimizer_progress_to_stdout = true;
225
    ceres::Solver::Summary summary;
225
    ceres::Solver::Summary summary;
226
    ceres::Solve(options, &problem, &summary);
226
    ceres::Solve(options, &problem, &summary);
227
 
227
 
228
    std::cout << summary.BriefReport() << "\n";
228
    std::cout << summary.BriefReport() << "\n";
229
 
229
 
230
    point = cv::Vec3f(pointArray[0], pointArray[1], pointArray[2]);
230
    point = cv::Vec3f(pointArray[0], pointArray[1], pointArray[2]);
231
    axis = cv::Vec3f(axisArray[0], axisArray[1], axisArray[2]);
231
    axis = cv::Vec3f(axisArray[0], axisArray[1], axisArray[2]);
232
    axis /= cv::norm(axis);
232
    axis /= cv::norm(axis);
233
 
233
 
234
 
234
 
235
    // Error estimate (sum of squared differences)
235
    // Error estimate (sum of squared differences)
236
    error = 0;
236
    error = 0;
237
    // loop through saddle points
237
    // loop through saddle points
238
    for(unsigned int idx=0; idx<mn; idx++){
238
    for(unsigned int idx=0; idx<mn; idx++){
239
 
239
 
240
        // vector of distances from rotation axis
240
        // vector of distances from rotation axis
241
        std::vector<float> dI(l);
241
        std::vector<float> dI(l);
242
        // loop through angular positions
242
        // loop through angular positions
243
        for(unsigned int k=0; k<l; k++){
243
        for(unsigned int k=0; k<l; k++){
244
            cv::Vec3f p = cv::Vec3f(Qcam[k][idx]);
244
            cv::Vec3f p = cv::Vec3f(Qcam[k][idx]);
245
            // point to line distance
245
            // point to line distance
246
            dI[k] = cv::norm((point-p)-(point-p).dot(axis)*axis);
246
            dI[k] = cv::norm((point-p)-(point-p).dot(axis)*axis);
247
        }
247
        }
248
        float sum = std::accumulate(dI.begin(), dI.end(), 0.0);
248
        float sum = std::accumulate(dI.begin(), dI.end(), 0.0);
249
        float mean = sum / dI.size();
249
        float mean = sum / dI.size();
250
        float meanDev = 0;
250
        float meanDev = 0;
251
        for(unsigned int k=0; k<l; k++){
251
        for(unsigned int k=0; k<l; k++){
252
            meanDev += std::abs(dI[k] - mean);
252
            meanDev += std::abs(dI[k] - mean);
253
        }
253
        }
254
        meanDev /= l;
254
        meanDev /= l;
255
        error += meanDev;
255
        error += meanDev;
256
    }
256
    }
257
    error /= mn;
257
    error /= mn;
258
}
258
}
259
 
259
 
260
static std::vector<cv::Point3f> generateWorldCoords(const cv::Size checkerCount, const float checkerSize){
260
static std::vector<cv::Point3f> generateWorldCoords(const cv::Size checkerCount, const float checkerSize){
261
 
261
 
262
    std::vector<cv::Point3f> Qi;
262
    std::vector<cv::Point3f> Qi;
263
    for (int h=0; h<checkerCount.height; h++)
263
    for (int h=0; h<checkerCount.height; h++)
264
        for (int w=0; w<checkerCount.width; w++)
264
        for (int w=0; w<checkerCount.width; w++)
265
            Qi.push_back(cv::Point3f(checkerSize * w, checkerSize* h, 0.0));
265
            Qi.push_back(cv::Point3f(checkerSize * w, checkerSize* h, 0.0));
266
 
266
 
267
    return Qi;
267
    return Qi;
268
}
268
}
269
 
269
 
270
static bool detectCheckerBoardCorners(const cv::Size & checkerCount,
270
static bool detectCheckerBoardCorners(const cv::Size & checkerCount,
271
                                    const cv::Mat & frame,
271
                                    const cv::Mat & frame,
272
                                    cv::Mat & frameResult,
272
                                    cv::Mat & frameResult,
273
                                    std::vector<cv::Point2f> & qc){
273
                                    std::vector<cv::Point2f> & qc){
274
    // Convert to grayscale
274
    // Convert to grayscale
275
    cv::Mat gray;
275
    cv::Mat gray;
276
    if(frame.channels() == 1)
276
    if(frame.channels() == 1)
277
        cv::cvtColor(frame, gray, CV_BayerBG2GRAY);
277
        cv::cvtColor(frame, gray, CV_BayerBG2GRAY);
278
    else
278
    else
279
        cv::cvtColor(frame, gray, CV_RGB2GRAY);
279
        cv::cvtColor(frame, gray, CV_RGB2GRAY);
280
 
280
 
281
    // Extract checker corners
281
    // Extract checker corners
282
    bool success = cv::findChessboardCorners(gray, checkerCount, qc, cv::CALIB_CB_ADAPTIVE_THRESH + cv::CALIB_CB_FAST_CHECK);
282
    bool success = cv::findChessboardCorners(gray, checkerCount, qc, cv::CALIB_CB_ADAPTIVE_THRESH + cv::CALIB_CB_FAST_CHECK);
283
    if(success){
283
    if(success){
284
        cv::cornerSubPix(gray, qc, cv::Size(6, 6), cv::Size(1, 1), cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 20, 0.0001));
284
        cv::cornerSubPix(gray, qc, cv::Size(6, 6), cv::Size(1, 1), cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 20, 0.0001));
285
        // Draw colored chessboard
285
        // Draw colored chessboard
286
        if(frame.channels() == 1)
286
        if(frame.channels() == 1)
287
            cv::cvtColor(frame, frameResult, CV_BayerBG2RGB);
287
            cv::cvtColor(frame, frameResult, CV_BayerBG2RGB);
288
        else
288
        else
289
            frameResult = frame.clone();
289
            frameResult = frame.clone();
290
 
290
 
291
        cvtools::drawChessboardCorners(frameResult, checkerCount, qc, success, 10);
291
        cvtools::drawChessboardCorners(frameResult, checkerCount, qc, success, 10);
292
    } else {
292
    } else {
293
        qc.clear();
293
        qc.clear();
294
    }
294
    }
295
    return success;
295
    return success;
296
}
296
}
297
 
297
 
298
void SMCalibrationWorker::checkerboardDetection(SMCalibrationSet calibrationSet){
298
void SMCalibrationWorker::checkerboardDetection(SMCalibrationSet calibrationSet){
299
 
299
 
300
    QSettings settings;
300
    QSettings settings;
301
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
301
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
302
 
302
 
303
    bool success0 = detectCheckerBoardCorners(checkerCount, calibrationSet.frame0, calibrationSet.frame0Result, calibrationSet.qc0);
303
    bool success0 = detectCheckerBoardCorners(checkerCount, calibrationSet.frame0, calibrationSet.frame0Result, calibrationSet.qc0);
304
    if(!success0){
304
    if(!success0){
305
//        calibrationSet.qc0.clear();
305
//        calibrationSet.qc0.clear();
306
        emit logMessage(QString("Could not detect checkerboard on set %1 camera0").arg(calibrationSet.id));
306
        emit logMessage(QString("Could not detect checkerboard on set %1 camera0").arg(calibrationSet.id));
307
        std::cerr << "Could not detect checkerboard on set " << calibrationSet.id << " camera0" << std::endl;
307
        std::cerr << "Could not detect checkerboard on set " << calibrationSet.id << " camera0" << std::endl;
308
    }
308
    }
309
 
309
 
310
    bool success1 = detectCheckerBoardCorners(checkerCount, calibrationSet.frame1, calibrationSet.frame1Result, calibrationSet.qc1);
310
    bool success1 = detectCheckerBoardCorners(checkerCount, calibrationSet.frame1, calibrationSet.frame1Result, calibrationSet.qc1);
311
    if(!success1){
311
    if(!success1){
312
//        calibrationSet.qc1.clear();
312
//        calibrationSet.qc1.clear();
313
        emit logMessage(QString("Could not detect checkerboard on set %1 camera1").arg(calibrationSet.id));
313
        emit logMessage(QString("Could not detect checkerboard on set %1 camera1").arg(calibrationSet.id));
314
        std::cerr << "Could not detect checkerboard on set " << calibrationSet.id << " camera1" << std::endl;
314
        std::cerr << "Could not detect checkerboard on set " << calibrationSet.id << " camera1" << std::endl;
315
    }
315
    }
316
 
316
 
317
    emit newCheckerboardResult(calibrationSet.id, calibrationSet);
317
    emit newCheckerboardResult(calibrationSet.id, calibrationSet);
318
 
318
 
319
}
319
}
320
 
320
 
321
void SMCalibrationWorker::cameraCalibration(std::vector<SMCalibrationSet> calibrationData){
321
void SMCalibrationWorker::cameraCalibration(std::vector<SMCalibrationSet> calibrationData){
322
 
322
 
323
    QSettings settings;
323
    QSettings settings;
324
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
324
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
325
 
325
 
326
    unsigned int nSets = calibrationData.size();
326
    unsigned int nSets = calibrationData.size();
327
 
327
 
328
    // 2D Points collected for OpenCV's calibration procedures
328
    // 2D Points collected for OpenCV's calibration procedures
329
    std::vector< std::vector<cv::Point2f> > qc0, qc1, qc0Stereo, qc1Stereo;
329
    std::vector< std::vector<cv::Point2f> > qc0, qc1, qc0Stereo, qc1Stereo;
330
 
330
 
331
    for(unsigned int i=0; i<nSets; i++){
331
    for(unsigned int i=0; i<nSets; i++){
332
 
332
 
333
        if(!calibrationData[i].selected)
333
        if(!calibrationData[i].selected)
334
            continue;
334
            continue;
335
 
335
 
336
        // Note: avoiding push_back has only minor theoretical value
336
        // Note: avoiding push_back has only minor theoretical value
337
        if(!calibrationData[i].qc0.empty())
337
        if(!calibrationData[i].qc0.empty())
338
            qc0.push_back(calibrationData[i].qc0);
338
            qc0.push_back(calibrationData[i].qc0);
339
 
339
 
340
        if(!calibrationData[i].qc1.empty())
340
        if(!calibrationData[i].qc1.empty())
341
            qc1.push_back(calibrationData[i].qc1);
341
            qc1.push_back(calibrationData[i].qc1);
342
 
342
 
343
        if(!calibrationData[i].qc0.empty() && !calibrationData[i].qc1.empty()){
343
        if(!calibrationData[i].qc0.empty() && !calibrationData[i].qc1.empty()){
344
            qc0Stereo.push_back(calibrationData[i].qc0);
344
            qc0Stereo.push_back(calibrationData[i].qc0);
345
            qc1Stereo.push_back(calibrationData[i].qc1);
345
            qc1Stereo.push_back(calibrationData[i].qc1);
346
        }
346
        }
347
    }
347
    }
348
 
348
 
349
    // Generate world object coordinates [mm]
349
    // Generate world object coordinates [mm]
350
    std::vector<cv::Point3f> Qi = generateWorldCoords(checkerCount, settings.value("calibration/squareSize", 10.0).toFloat());
350
    std::vector<cv::Point3f> Qi = generateWorldCoords(checkerCount, settings.value("calibration/squareSize", 10.0).toFloat());
351
 
351
 
352
    std::vector< std::vector<cv::Point3f> > Q0(qc0.size(), Qi), Q1(qc1.size(), Qi), QStereo(qc0Stereo.size(), Qi);
352
    std::vector< std::vector<cv::Point3f> > Q0(qc0.size(), Qi), Q1(qc1.size(), Qi), QStereo(qc0Stereo.size(), Qi);
353
 
353
 
354
    // Calibrate the cameras
354
    // Calibrate the cameras
355
    SMCalibrationParameters cal;
355
    SMCalibrationParameters cal;
356
    cal.frameWidth = calibrationData[0].frame0.cols;
356
    cal.frameWidth = calibrationData[0].frame0.cols;
357
    cal.frameHeight = calibrationData[0].frame0.rows;
357
    cal.frameHeight = calibrationData[0].frame0.rows;
358
    cv::Size frameSize(cal.frameWidth, cal.frameHeight);
358
    cv::Size frameSize(cal.frameWidth, cal.frameHeight);
359
 
359
 
360
    // determine only k1, k2 for lens distortion
360
    // determine only k1, k2 for lens distortion
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;
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;
362
 
362
 
363
    std::vector<cv::Mat> cam_rvecs0, cam_tvecs0;
363
    std::vector<cv::Mat> cam_rvecs0, cam_tvecs0;
364
 
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,
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,
366
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
366
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
367
 
367
 
368
    std::vector<cv::Mat> cam_rvecs1, cam_tvecs1;
368
    std::vector<cv::Mat> cam_rvecs1, cam_tvecs1;
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,
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,
370
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
370
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
371
 
371
 
372
    // Stereo calibration
372
    // Stereo calibration
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;
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;
374
    cv::Mat E, F, R1, T1;
374
    cv::Mat E, F, R1, T1;
375
 
375
 
376
    #if CV_MAJOR_VERSION < 3
376
    #if CV_MAJOR_VERSION < 3
377
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
377
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
378
                                               frameSize, R1, T1, E, F,
378
                                               frameSize, R1, T1, E, F,
379
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON),
379
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON),
380
                                               flags_stereo);
380
                                               flags_stereo);
381
    #else
381
    #else
382
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
382
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
383
                                               frameSize, R1, T1, E, F, flags_stereo,
383
                                               frameSize, R1, T1, E, F, flags_stereo,
384
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON));
384
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON));
385
    #endif
385
    #endif
386
 
386
 
387
    cal.R1 = R1;
387
    cal.R1 = R1;
388
    cal.T1 = T1;
388
    cal.T1 = T1;
389
    cal.E = E;
389
    cal.E = E;
390
    cal.F = F;
390
    cal.F = F;
391
 
391
 
392
    // Print to log
392
    // Print to log
393
    std::stringstream out;
393
    std::stringstream out;
394
    out << "## Camera Calibration ##" << std::endl
394
    out << "## Camera Calibration ##" << std::endl
395
        << "No. images used for intrinsics of cam0: " << qc0.size() << 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
396
        << "No. images used for intrinsics of cam1: " << qc1.size() << std::endl
397
        << "No. images used for stereo calibration: " << qc0Stereo.size() << std::endl;
397
        << "No. images used for stereo calibration: " << qc0Stereo.size() << std::endl;
398
    cal.printCamera(out);
398
    cal.printCamera(out);
399
    out << std::endl << std::endl;
399
    out << std::endl << std::endl;
400
    emit logMessage(QString::fromStdString(out.str()));
400
    emit logMessage(QString::fromStdString(out.str()));
401
 
401
 
402
    // save to (reentrant) qsettings object
402
    // save to (reentrant) qsettings object
403
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
403
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
404
 
404
 
405
    emit done();
405
    emit done();
406
}
406
}
407
 
407
 
408
static void drawDetectedMarkersCharuco(cv::InputOutputArray _image, cv::InputArrayOfArrays _corners,
408
static void drawDetectedMarkersCharuco(cv::InputOutputArray _image, cv::InputArrayOfArrays _corners,
409
                                cv::InputArray _ids, cv::Scalar borderColor) {
409
                                cv::InputArray _ids, cv::Scalar borderColor) {
410
 
410
 
411
    using namespace cv;
411
    using namespace cv;
412
    using namespace std;
412
    using namespace std;
413
 
413
 
414
    CV_Assert(_image.getMat().total() != 0 &&
414
    CV_Assert(_image.getMat().total() != 0 &&
415
              (_image.getMat().channels() == 1 || _image.getMat().channels() == 3));
415
              (_image.getMat().channels() == 1 || _image.getMat().channels() == 3));
416
    CV_Assert((_corners.total() == _ids.total()) || _ids.total() == 0);
416
    CV_Assert((_corners.total() == _ids.total()) || _ids.total() == 0);
417
 
417
 
418
    // calculate colors
418
    // calculate colors
419
    Scalar textColor, cornerColor;
419
    Scalar textColor, cornerColor;
420
    textColor = cornerColor = borderColor;
420
    textColor = cornerColor = borderColor;
421
    swap(textColor.val[0], textColor.val[1]);     // text color just sawp G and R
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
422
    swap(cornerColor.val[1], cornerColor.val[2]); // corner color just sawp G and B
423
 
423
 
424
    int nMarkers = (int)_corners.total();
424
    int nMarkers = (int)_corners.total();
425
    for(int i = 0; i < nMarkers; i++) {
425
    for(int i = 0; i < nMarkers; i++) {
426
        Mat currentMarker = _corners.getMat(i);
426
        Mat currentMarker = _corners.getMat(i);
427
        CV_Assert(currentMarker.total() == 4 && currentMarker.type() == CV_32FC2);
427
        CV_Assert(currentMarker.total() == 4 && currentMarker.type() == CV_32FC2);
428
 
428
 
429
        // draw marker sides
429
        // draw marker sides
430
        for(int j = 0; j < 4; j++) {
430
        for(int j = 0; j < 4; j++) {
431
            Point2f p0, p1;
431
            Point2f p0, p1;
432
            p0 = currentMarker.ptr< Point2f >(0)[j];
432
            p0 = currentMarker.ptr< Point2f >(0)[j];
433
            p1 = currentMarker.ptr< Point2f >(0)[(j + 1) % 4];
433
            p1 = currentMarker.ptr< Point2f >(0)[(j + 1) % 4];
434
            line(_image, p0, p1, borderColor, 2, LINE_AA);
434
            line(_image, p0, p1, borderColor, 2, LINE_AA);
435
        }
435
        }
436
        // draw first corner mark
436
        // draw first corner mark
437
        rectangle(_image, currentMarker.ptr< Point2f >(0)[0] - Point2f(3, 3),
437
        rectangle(_image, currentMarker.ptr< Point2f >(0)[0] - Point2f(3, 3),
438
                  currentMarker.ptr< Point2f >(0)[0] + Point2f(3, 3), cornerColor, 1, LINE_AA);
438
                  currentMarker.ptr< Point2f >(0)[0] + Point2f(3, 3), cornerColor, 1, LINE_AA);
439
 
439
 
440
        // draw ID
440
        // draw ID
441
        if(_ids.total() != 0) {
441
        if(_ids.total() != 0) {
442
            Point2f cent(0, 0);
442
            Point2f cent(0, 0);
443
            for(int p = 0; p < 4; p++)
443
            for(int p = 0; p < 4; p++)
444
                cent += currentMarker.ptr< Point2f >(0)[p];
444
                cent += currentMarker.ptr< Point2f >(0)[p];
445
            cent = cent / 4.;
445
            cent = cent / 4.;
446
            stringstream s;
446
            stringstream s;
447
            s << _ids.getMat().ptr< int >(0)[i];
447
            s << _ids.getMat().ptr< int >(0)[i];
448
            putText(_image, s.str(), cent, FONT_HERSHEY_SIMPLEX, 1, textColor, 2, LINE_AA);
448
            putText(_image, s.str(), cent, FONT_HERSHEY_SIMPLEX, 1, textColor, 2, LINE_AA);
449
        }
449
        }
450
    }
450
    }
451
}
451
}
452
 
452
 
453
static void drawDetectedCornersCharuco(cv::InputOutputArray _image, cv::InputArray _charucoCorners,
453
static void drawDetectedCornersCharuco(cv::InputOutputArray _image, cv::InputArray _charucoCorners,
454
                                       cv::InputArray _charucoIds, cv::Scalar cornerColor) {
454
                                       cv::InputArray _charucoIds, cv::Scalar cornerColor) {
455
 
455
 
456
    using namespace cv;
456
    using namespace cv;
457
    using namespace std;
457
    using namespace std;
458
 
458
 
459
    CV_Assert(_image.getMat().total() != 0 &&
459
    CV_Assert(_image.getMat().total() != 0 &&
460
              (_image.getMat().channels() == 1 || _image.getMat().channels() == 3));
460
              (_image.getMat().channels() == 1 || _image.getMat().channels() == 3));
461
    CV_Assert((_charucoCorners.getMat().total() == _charucoIds.getMat().total()) ||
461
    CV_Assert((_charucoCorners.getMat().total() == _charucoIds.getMat().total()) ||
462
              _charucoIds.getMat().total() == 0);
462
              _charucoIds.getMat().total() == 0);
463
 
463
 
464
    unsigned int nCorners = (unsigned int)_charucoCorners.getMat().total();
464
    unsigned int nCorners = (unsigned int)_charucoCorners.getMat().total();
465
    for(unsigned int i = 0; i < nCorners; i++) {
465
    for(unsigned int i = 0; i < nCorners; i++) {
466
        Point2f corner = _charucoCorners.getMat().at< Point2f >(i);
466
        Point2f corner = _charucoCorners.getMat().at< Point2f >(i);
467
 
467
 
468
        // draw first corner mark
468
        // draw first corner mark
469
        rectangle(_image, corner - Point2f(3, 3), corner + Point2f(3, 3), cornerColor, 2, LINE_AA);
469
        rectangle(_image, corner - Point2f(3, 3), corner + Point2f(3, 3), cornerColor, 2, LINE_AA);
470
 
470
 
471
        // draw ID
471
        // draw ID
472
        if(_charucoIds.total() != 0) {
472
        if(_charucoIds.total() != 0) {
473
            int id = _charucoIds.getMat().at< int >(i);
473
            int id = _charucoIds.getMat().at< int >(i);
474
            stringstream s;
474
            stringstream s;
475
            s << id;
475
            s << id;
476
            putText(_image, s.str(), corner + Point2f(5, -5), FONT_HERSHEY_SIMPLEX, 1.0,
476
            putText(_image, s.str(), corner + Point2f(5, -5), FONT_HERSHEY_SIMPLEX, 1.0,
477
                    cornerColor, 4, cv::LINE_AA);
477
                    cornerColor, 4, cv::LINE_AA);
478
        }
478
        }
479
    }
479
    }
480
}
480
}
481
 
481
 
482
void SMCalibrationWorker::cameraCalibrationCharuco(std::vector<SMCalibrationSet> calibrationData){
-
 
483
 
482
 
-
 
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,
484
    QSettings settings;
489
                                            std::vector<int>& qci){
485
 
490
 
486
    // Number of saddle points on calibration pattern
491
    // Convert to grayscale
-
 
492
    cv::Mat gray;
487
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
493
    if(frame.channels() == 1)
488
    const float checkerSize = settings.value("calibration/squareSize", 10.0).toFloat();
494
        cv::cvtColor(frame, gray, CV_BayerBG2GRAY);
-
 
495
    else
489
    float markerLength = 0.8*checkerSize;
496
        cv::cvtColor(frame, gray, CV_RGB2GRAY);
490
 
497
 
491
    unsigned int nSets = calibrationData.size();
-
 
492
 
498
 
493
    // 2D Points collected for OpenCV's calibration procedures
-
 
494
    std::vector< std::vector<cv::Point2f> > qc0, qc1;
499
    std::vector<std::vector<cv::Point2f>> mc;
495
    std::vector< std::vector<cv::Point2f> > qc0Stereo, qc1Stereo;
500
    std::vector<int> mi;
496
 
501
 
497
    // 3D object points
502
    cv::Mat grayBlurred;
498
    std::vector< std::vector<cv::Point3f> > Q0, Q1, QStereo;
503
    cv::GaussianBlur(gray, grayBlurred, cv::Size(0, 0), 3);
499
 
504
 
500
    // Charuco board and dictionary
505
    // Extract checker corners
-
 
506
    cv::aruco::detectMarkers(grayBlurred, dict, mc, mi, parameters);
-
 
507
    //std::vector<std::vector<cv::Point2f>> mc, rejecti;
501
    cv::Ptr<cv::aruco::Dictionary> dict = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_6X6_250);
508
    //cv::aruco::refineDetectedMarkers(gray0, board, mc0, mi0, rejecti0);
502
 
509
 
503
//    // The dictionary from the standalone Aruco library used to generate the original chessboards
510
    //cv::Mat cci, cidsi;
504
//    std::vector<uint64_t> ARUCO_MIP_36h12 = {0xd2b63a09dUL,0x6001134e5UL,0x1206fbe72UL,0xff8ad6cb4UL,0x85da9bc49UL,0xb461afe9cUL,0x6db51fe13UL,0x5248c541fUL,0x8f34503UL,0x8ea462eceUL,0xeac2be76dUL,0x1af615c44UL,0xb48a49f27UL,0x2e4e1283bUL,0x78b1f2fa8UL,0x27d34f57eUL,0x89222fff1UL,0x4c1669406UL,0xbf49b3511UL,0xdc191cd5dUL,0x11d7c3f85UL,0x16a130e35UL,0xe29f27effUL,0x428d8ae0cUL,0x90d548477UL,0x2319cbc93UL,0xc3b0c3dfcUL,0x424bccc9UL,0x2a081d630UL,0x762743d96UL,0xd0645bf19UL,0xf38d7fd60UL,0xc6cbf9a10UL,0x3c1be7c65UL,0x276f75e63UL,0x4490a3f63UL,0xda60acd52UL,0x3cc68df59UL,0xab46f9daeUL,0x88d533d78UL,0xb6d62ec21UL,0xb3c02b646UL,0x22e56d408UL,0xac5f5770aUL,0xaaa993f66UL,0x4caa07c8dUL,0x5c9b4f7b0UL,0xaa9ef0e05UL,0x705c5750UL,0xac81f545eUL,0x735b91e74UL,0x8cc35cee4UL,0xe44694d04UL,0xb5e121de0UL,0x261017d0fUL,0xf1d439eb5UL,0xa1a33ac96UL,0x174c62c02UL,0x1ee27f716UL,0x8b1c5ece9UL,0x6a05b0c6aUL,0xd0568dfcUL,0x192d25e5fUL,0x1adbeccc8UL,0xcfec87f00UL,0xd0b9dde7aUL,0x88dcef81eUL,0x445681cb9UL,0xdbb2ffc83UL,0xa48d96df1UL,0xb72cc2e7dUL,0xc295b53fUL,0xf49832704UL,0x9968edc29UL,0x9e4e1af85UL,0x8683e2d1bUL,0x810b45c04UL,0x6ac44bfe2UL,0x645346615UL,0x3990bd598UL,0x1c9ed0f6aUL,0xc26729d65UL,0x83993f795UL,0x3ac05ac5dUL,0x357adff3bUL,0xd5c05565UL,0x2f547ef44UL,0x86c115041UL,0x640fd9e5fUL,0xce08bbcf7UL,0x109bb343eUL,0xc21435c92UL,0x35b4dfce4UL,0x459752cf2UL,0xec915b82cUL,0x51881eed0UL,0x2dda7dc97UL,0x2e0142144UL,0x42e890f99UL,0x9a8856527UL,0x8e80d9d80UL,0x891cbcf34UL,0x25dd82410UL,0x239551d34UL,0x8fe8f0c70UL,0x94106a970UL,0x82609b40cUL,0xfc9caf36UL,0x688181d11UL,0x718613c08UL,0xf1ab7629UL,0xa357bfc18UL,0x4c03b7a46UL,0x204dedce6UL,0xad6300d37UL,0x84cc4cd09UL,0x42160e5c4UL,0x87d2adfa8UL,0x7850e7749UL,0x4e750fc7cUL,0xbf2e5dfdaUL,0xd88324da5UL,0x234b52f80UL,0x378204514UL,0xabdf2ad53UL,0x365e78ef9UL,0x49caa6ca2UL,0x3c39ddf3UL,0xc68c5385dUL,0x5bfcbbf67UL,0x623241e21UL,0xabc90d5ccUL,0x388c6fe85UL,0xda0e2d62dUL,0x10855dfe9UL,0x4d46efd6bUL,0x76ea12d61UL,0x9db377d3dUL,0xeed0efa71UL,0xe6ec3ae2fUL,0x441faee83UL,0xba19c8ff5UL,0x313035eabUL,0x6ce8f7625UL,0x880dab58dUL,0x8d3409e0dUL,0x2be92ee21UL,0xd60302c6cUL,0x469ffc724UL,0x87eebeed3UL,0x42587ef7aUL,0x7a8cc4e52UL,0x76a437650UL,0x999e41ef4UL,0x7d0969e42UL,0xc02baf46bUL,0x9259f3e47UL,0x2116a1dc0UL,0x9f2de4d84UL,0xeffac29UL,0x7b371ff8cUL,0x668339da9UL,0xd010aee3fUL,0x1cd00b4c0UL,0x95070fc3bUL,0xf84c9a770UL,0x38f863d76UL,0x3646ff045UL,0xce1b96412UL,0x7a5d45da8UL,0x14e00ef6cUL,0x5e95abfd8UL,0xb2e9cb729UL,0x36c47dd7UL,0xb8ee97c6bUL,0xe9e8f657UL,0xd4ad2ef1aUL,0x8811c7f32UL,0x47bde7c31UL,0x3adadfb64UL,0x6e5b28574UL,0x33e67cd91UL,0x2ab9fdd2dUL,0x8afa67f2bUL,0xe6a28fc5eUL,0x72049cdbdUL,0xae65dac12UL,0x1251a4526UL,0x1089ab841UL,0xe2f096ee0UL,0xb0caee573UL,0xfd6677e86UL,0x444b3f518UL,0xbe8b3a56aUL,0x680a75cfcUL,0xac02baea8UL,0x97d815e1cUL,0x1d4386e08UL,0x1a14f5b0eUL,0xe658a8d81UL,0xa3868efa7UL,0x3668a9673UL,0xe8fc53d85UL,0x2e2b7edd5UL,0x8b2470f13UL,0xf69795f32UL,0x4589ffc8eUL,0x2e2080c9cUL,0x64265f7dUL,0x3d714dd10UL,0x1692c6ef1UL,0x3e67f2f49UL,0x5041dad63UL,0x1a1503415UL,0x64c18c742UL,0xa72eec35UL,0x1f0f9dc60UL,0xa9559bc67UL,0xf32911d0dUL,0x21c0d4ffcUL,0xe01cef5b0UL,0x4e23a3520UL,0xaa4f04e49UL,0xe1c4fcc43UL,0x208e8f6e8UL,0x8486774a5UL,0x9e98c7558UL,0x2c59fb7dcUL,0x9446a4613UL,0x8292dcc2eUL,0x4d61631UL,0xd05527809UL,0xa0163852dUL,0x8f657f639UL,0xcca6c3e37UL,0xcb136bc7aUL,0xfc5a83e53UL,0x9aa44fc30UL,0xbdec1bd3cUL,0xe020b9f7cUL,0x4b8f35fb0UL,0xb8165f637UL,0x33dc88d69UL,0x10a2f7e4dUL,0xc8cb5ff53UL,0xde259ff6bUL,0x46d070dd4UL,0x32d3b9741UL,0x7075f1c04UL,0x4d58dbea0UL};
511
    cv::aruco::interpolateCornersCharuco(mc, mi, gray, board, qc, qci, cv::noArray(), cv::noArray(), 1);
505
//    int tau_MIP_3612 = 12;
-
 
506
 
512
 
507
//    // shuffle according to aruco_create_markermap code
513
    bool success = (qc.size() >= 4);
508
//    std::srand(0);
514
    if(success){
509
//    std::random_shuffle(ARUCO_MIP_36h12.begin(),ARUCO_MIP_36h12.end());
515
        cv::cornerSubPix(gray, qc, cv::Size(6, 6), cv::Size(1, 1), cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 20, 0.0001));
510
 
-
 
511
//    cv::Mat bytesList(250, 5, CV_8UC4);
-
 
512
//    for(int i=0; i<250; i++){
-
 
513
//        cv::Mat bits(6, 6, CV_8UC1);
516
        // Draw colored chessboard
514
//        for(int b=0; b<36; b++){
517
        if(frame.channels() == 1)
515
//            bits.at<char>(b) = getBit(ARUCO_MIP_36h12[i], b+1);
518
            cv::cvtColor(frame, frameResult, CV_BayerBG2RGB);
516
//        }
519
        else
517
//        //std::cout << bits << std::endl;
-
 
518
//        cv::Mat bytes = cv::aruco::Dictionary::getByteListFromBits(bits);
-
 
519
//        bytes.copyTo(bytesList.row(i));
520
            frameResult = frame.clone();
520
//    }
-
 
521
//    cv::Ptr<cv::aruco::Dictionary> dict = cv::makePtr<cv::aruco::Dictionary>(new cv::aruco::Dictionary(bytesList, 6, (tau_MIP_3612-1)/2));
-
 
522
 
-
 
523
 
-
 
524
//    for(int i=0; i<250; i++){
-
 
525
//        cv::Mat img;
-
 
526
//        dict->drawMarker(i, 100, img, 1);
-
 
527
//        cv::imwrite(QString("id%1.png").arg(i).toStdString(), img);
-
 
528
//    }
-
 
529
 
521
 
-
 
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
    }
-
 
528
 
-
 
529
    return success;
-
 
530
 
-
 
531
}
-
 
532
 
-
 
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);
530
    cv::Ptr<cv::aruco::CharucoBoard> board = cv::aruco::CharucoBoard::create(checkerCount.width+1, checkerCount.height+1, checkerSize, markerLength, dict);
542
    cv::Ptr<cv::aruco::CharucoBoard> board = cv::aruco::CharucoBoard::create(checkerCount.width+1, checkerCount.height+1, checkerSize, markerLength, dict);
531
 
543
 
532
//    cv::Mat boardImg;
544
    //    cv::Mat boardImg;
533
//    board->draw(cv::Size((saddlePointCountX+1)*100, (saddlePointCountY+1)*100), boardImg, 0, 1);
545
    //    board->draw(cv::Size((saddlePointCountX+1)*100, (saddlePointCountY+1)*100), boardImg, 0, 1);
534
//    cv::Mat boardImgRes;
546
    //    cv::Mat boardImgRes;
535
//    cv::resize(boardImg, boardImgRes, cv::Size((saddlePointCountX+1)*10, (saddlePointCountY+1)*10), 0, 0, cv::INTER_NEAREST);
547
    //    cv::resize(boardImg, boardImgRes, cv::Size((saddlePointCountX+1)*10, (saddlePointCountY+1)*10), 0, 0, cv::INTER_NEAREST);
536
//    cv::imwrite("boardImg.png", boardImg);
548
    //    cv::imwrite("boardImg.png", boardImg);
537
//    cv::imwrite("boardImgRes.png", boardImgRes);
549
    //    cv::imwrite("boardImgRes.png", boardImgRes);
538
 
550
 
539
    cv::Ptr<cv::aruco::DetectorParameters> parameters = cv::aruco::DetectorParameters::create();
551
    cv::Ptr<cv::aruco::DetectorParameters> parameters = cv::aruco::DetectorParameters::create();
540
    parameters->adaptiveThreshWinSizeMin = 3;
552
//    parameters->adaptiveThreshWinSizeMin = 3;
541
    parameters->adaptiveThreshWinSizeMax = 153;
553
//    parameters->adaptiveThreshWinSizeMax = 153;
542
    parameters->adaptiveThreshWinSizeStep = 3;
554
//    parameters->adaptiveThreshWinSizeStep = 5;
543
//    parameters->adaptiveThreshConstant = 20;
555
//    parameters->adaptiveThreshConstant = 20;
544
//    parameters->minMarkerPerimeterRate = 0.01;
556
//    parameters->minMarkerPerimeterRate = 0.01;
545
    parameters->maxMarkerPerimeterRate = 5.0;
557
    parameters->maxMarkerPerimeterRate = 5.0;
546
//    parameters->minCornerDistanceRate = 0.10;
558
//    parameters->minCornerDistanceRate = 0.10;
547
//    parameters->perspectiveRemovePixelPerCell = 6;
559
//    parameters->perspectiveRemovePixelPerCell = 6;
548
//    parameters->maxErroneousBitsInBorderRate = 0.8;
560
//    parameters->maxErroneousBitsInBorderRate = 0.8;
549
//    parameters->minOtsuStdDev = 1;
561
//    parameters->minOtsuStdDev = 1;
550
//    parameters->errorCorrectionRate = 0.1;
562
//    parameters->errorCorrectionRate = 0.1;
-
 
563
    parameters->cornerRefinementWinSize = 10;
551
 
564
 
552
    // Loop through calibration sets
-
 
553
    for(unsigned int i=0; i<nSets; i++){
-
 
554
 
-
 
555
        SMCalibrationSet calibrationSetI = calibrationData[i];
565
    bool success0 = detectCheckerBoardCornersCharuco(calibrationSet.frame0, dict, board, parameters, calibrationSet.frame0Result, calibrationSet.qc0, calibrationSet.qc0id);
556
 
-
 
557
        if(!calibrationSetI.selected)
-
 
558
            continue;
-
 
559
 
-
 
560
        // Camera 0
566
    if(!success0){
561
        std::vector<std::vector<cv::Point2f>> mc0, rejecti0;
567
        emit logMessage(QString("Could not detect  Charuco corners on set %1 camera0").arg(calibrationSet.id));
562
        std::vector<int> mi0;
-
 
563
 
-
 
564
        cv::Mat gray0;
-
 
565
        cv::cvtColor(calibrationSetI.frame0, gray0, CV_BayerBG2GRAY);
568
        std::cerr << "Could not detect Charuco corners on set " << calibrationSet.id << " camera0" << std::endl;
566
 
569
    }
567
        // Extract checker corners
-
 
568
        cv::aruco::detectMarkers(gray0, dict, mc0, mi0, parameters);
-
 
569
        cv::aruco::refineDetectedMarkers(gray0, board, mc0, mi0, rejecti0);
-
 
570
 
570
 
-
 
571
    bool success1 = detectCheckerBoardCornersCharuco(calibrationSet.frame1, dict, board, parameters, calibrationSet.frame1Result, calibrationSet.qc1, calibrationSet.qc1id);
571
        cv::Mat cci0, cidsi0;
572
    if(!success1){
572
        cv::aruco::interpolateCornersCharuco(mc0, mi0, gray0, board, cci0, cidsi0);
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
    }
573
 
576
 
574
        bool success0 = (cci0.rows >= 4);
-
 
575
        if(success0){
-
 
576
            cv::Mat color0;
-
 
577
            cv::cvtColor(calibrationSetI.frame0, color0, CV_BayerBG2RGB);
577
    emit newCheckerboardResult(calibrationSet.id, calibrationSet);
578
 
578
 
579
            // Draw colored chessboard
-
 
580
            drawDetectedMarkersCharuco(color0, mc0, mi0, cv::Scalar(0, 255, 0));
-
 
581
            drawDetectedCornersCharuco(color0, cci0, cidsi0, cv::Scalar(0, 255, 0));
-
 
-
 
579
}
582
 
580
 
583
            calibrationSetI.frame0Result = color0;
-
 
584
        } else {
-
 
585
            std::cerr << "Could not detect Charuco in camera 0, id " << calibrationSetI.id << std::endl;
581
void SMCalibrationWorker::cameraCalibrationCharuco(std::vector<SMCalibrationSet> calibrationData){
586
        }
-
 
587
 
582
 
-
 
583
    QSettings settings;
588
 
584
 
589
        // Camera 1
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()));
590
        std::vector<std::vector<cv::Point2f>> mc1, rejecti1;
587
    const float checkerSize = settings.value("calibration/squareSize", 10.0).toFloat();
591
        std::vector<int> mi1;
588
    float markerLength = 0.8f*checkerSize;
592
 
589
 
593
        cv::Mat gray1;
590
    cv::Ptr<cv::aruco::Dictionary> dict = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_6X6_250);
594
        cv::cvtColor(calibrationSetI.frame1, gray1, CV_BayerBG2GRAY);
591
    cv::Ptr<cv::aruco::CharucoBoard> board = cv::aruco::CharucoBoard::create(checkerCount.width+1, checkerCount.height+1, checkerSize, markerLength, dict);
595
 
592
 
596
        // Extract checker corners
593
    auto nSets = calibrationData.size();
597
        cv::aruco::detectMarkers(gray1, dict, mc1, mi1, parameters);
-
 
598
        cv::aruco::refineDetectedMarkers(gray1, board, mc1, mi1, rejecti1);
-
 
599
 
594
 
-
 
595
    // 2D Points collected for OpenCV's calibration procedures
600
        cv::Mat cci1, cidsi1;
596
    std::vector< std::vector<cv::Point2f> > qc0, qc1;
601
        cv::aruco::interpolateCornersCharuco(mc1, mi1, gray1, board, cci1, cidsi1);
597
    std::vector< std::vector<cv::Point2f> > qc0Stereo, qc1Stereo;
602
 
598
 
603
        bool success1 = (cci1.rows >= 4);
-
 
604
        if(success1){
-
 
605
            cv::Mat color1;
599
    // 3D object points
606
            cv::cvtColor(calibrationSetI.frame1, color1, CV_BayerBG2RGB);
600
    std::vector< std::vector<cv::Point3f> > Q0, Q1, QStereo;
607
 
601
 
608
            // Draw colored chessboard
602
    // Loop through calibration sets
609
            drawDetectedMarkersCharuco(color1, mc1, mi1, cv::Scalar(0, 255, 0));
-
 
610
            drawDetectedCornersCharuco(color1, cci1, cidsi1, cv::Scalar(0, 255, 0));
603
    for(unsigned int i=0; i<nSets; i++){
611
 
604
 
612
            calibrationSetI.frame1Result = color1;
605
        if(!calibrationData[i].selected)
613
        } else {
606
            continue;
614
            std::cerr << "Could not detect Charuco in camera 1, id " << calibrationSetI.id << std::endl;
-
 
615
        }
-
 
616
 
607
 
-
 
608
        bool success0 = !calibrationData[i].qc0.empty();
617
        emit newCheckerboardResult(calibrationSetI.id, calibrationSetI);
609
        bool success1 = !calibrationData[i].qc1.empty();
618
 
610
 
619
        if(success0){
611
        if(success0){
620
            std::vector<cv::Point2f> qc0i;
-
 
621
            std::vector<cv::Point3f> Q0i;
612
            std::vector<cv::Point3f> Q0i;
622
            for(int j=0; j<cci0.rows; j++){
613
            for(std::size_t j=0; j<calibrationData[i].qc0id.size(); j++){
623
                qc0i.push_back(cci0.at<cv::Point2f>(j));
-
 
624
                int id = cidsi0.at<int>(j);
614
                int id = calibrationData[i].qc0id[j];
625
                Q0i.push_back(board->chessboardCorners[id]);
615
                Q0i.push_back(board->chessboardCorners[id]);
626
            }
616
            }
627
 
617
 
628
            qc0.push_back(qc0i);
618
            qc0.push_back(calibrationData[i].qc0);
629
            Q0.push_back(Q0i);
619
            Q0.push_back(Q0i);
630
        }
620
        }
631
 
621
 
632
        if(success1){
622
        if(success1){
633
            std::vector<cv::Point2f> qc1i;
-
 
634
            std::vector<cv::Point3f> Q1i;
623
            std::vector<cv::Point3f> Q1i;
635
            for(int j=0; j<cci1.rows; j++){
624
            for(std::size_t j=0; j<calibrationData[i].qc1id.size(); j++){
636
                qc1i.push_back(cci1.at<cv::Point2f>(j));
-
 
637
                int id = cidsi1.at<int>(j);
625
                int id = calibrationData[i].qc1id[j];
638
                Q1i.push_back(board->chessboardCorners[id]);
626
                Q1i.push_back(board->chessboardCorners[id]);
639
            }
627
            }
640
 
628
 
641
            qc1.push_back(qc1i);
629
            qc1.push_back(calibrationData[i].qc1);
642
            Q1.push_back(Q1i);
630
            Q1.push_back(Q1i);
643
        }
631
        }
644
 
632
 
645
        if(success0 && success1){
633
        if(success0 && success1){
646
 
634
 
647
            std::vector<cv::Point2f> qc0iStereo, qc1iStereo;
635
            std::vector<cv::Point2f> qc0iStereo, qc1iStereo;
648
            std::vector<cv::Point3f> QiStereo;
636
            std::vector<cv::Point3f> QiStereo;
649
 
637
 
650
            int j0 = 0;
638
            int j0 = 0;
651
            int j1 = 0;
639
            int j1 = 0;
652
            while(j0<cci0.rows && j1<cci1.rows){
640
            while(j0<calibrationData[i].qc0.size() && j1<calibrationData[i].qc1.size()){
653
 
641
 
654
                int id0 = cidsi0.at<int>(j0);
642
                int id0 = calibrationData[i].qc0id[j0];
655
                int id1 = cidsi1.at<int>(j1);
643
                int id1 = calibrationData[i].qc1id[j1];
656
 
644
 
657
                if(id0 < id1)
645
                if(id0 < id1)
658
                    j0++;
646
                    j0++;
659
                else if (id1 < id0)
647
                else if (id1 < id0)
660
                    j1++;
648
                    j1++;
661
                else{
649
                else{
662
                    assert(id0 == id1);
650
                    assert(id0 == id1);
663
                    qc0iStereo.push_back(cci0.at<cv::Point2f>(j0));
651
                    qc0iStereo.push_back(calibrationData[i].qc0[j0]);
664
                    qc1iStereo.push_back(cci1.at<cv::Point2f>(j1));
652
                    qc1iStereo.push_back(calibrationData[i].qc1[j1]);
665
                    QiStereo.push_back(board->chessboardCorners[id0]);
653
                    QiStereo.push_back(board->chessboardCorners[id0]);
666
                    j0++;
654
                    j0++;
667
                    j1++;
655
                    j1++;
668
                }
656
                }
669
 
657
 
670
            }
658
            }
671
 
659
 
672
            if(QiStereo.size() > 0){
660
            if(QiStereo.size() > 0){
673
                qc0Stereo.push_back(qc0iStereo);
661
                qc0Stereo.push_back(qc0iStereo);
674
                qc1Stereo.push_back(qc1iStereo);
662
                qc1Stereo.push_back(qc1iStereo);
675
                QStereo.push_back(QiStereo);
663
                QStereo.push_back(QiStereo);
676
            }
664
            }
677
        }
665
        }
678
 
666
 
679
    }
667
    }
680
 
668
 
681
    size_t nValidSets = qc0Stereo.size();
669
    size_t nValidSets = qc0Stereo.size();
682
    if(nValidSets < 2){
670
    if(nValidSets < 2){
683
        std::cerr << "Not enough valid calibration sequences!" << std::endl;
671
        std::cerr << "Not enough valid calibration sequences!" << std::endl;
684
        emit done();
672
        emit done();
685
        return;
673
        return;
686
    }
674
    }
687
 
675
 
688
 
676
 
689
    // calibrate the cameras
677
    // calibrate the cameras
690
    SMCalibrationParameters cal;
678
    SMCalibrationParameters cal;
691
    cal.frameWidth = calibrationData[0].frame0.cols;
679
    cal.frameWidth = calibrationData[0].frame0.cols;
692
    cal.frameHeight = calibrationData[0].frame0.rows;
680
    cal.frameHeight = calibrationData[0].frame0.rows;
693
    cv::Size frameSize(cal.frameWidth, cal.frameHeight);
681
    cv::Size frameSize(cal.frameWidth, cal.frameHeight);
694
 
682
 
695
    // determine only k1, k2 for lens distortion
683
    // determine only k1, k2 for lens distortion
696
    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;
684
    int flags = cv::CALIB_FIX_ASPECT_RATIO + cv::CALIB_FIX_K3 + cv::CALIB_ZERO_TANGENT_DIST + cv::CALIB_FIX_PRINCIPAL_POINT;
697
 
685
 
698
    // Note: several of the output arguments below must be cv::Mat, otherwise segfault
686
    // Note: several of the output arguments below must be cv::Mat, otherwise segfault
699
    std::vector<cv::Mat> cam_rvecs0, cam_tvecs0;
687
    std::vector<cv::Mat> cam_rvecs0, cam_tvecs0;
700
    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,
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,
701
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
689
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
702
 
690
 
703
    std::vector<cv::Mat> cam_rvecs1, cam_tvecs1;
691
    std::vector<cv::Mat> cam_rvecs1, cam_tvecs1;
704
    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,
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,
705
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
693
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
706
 
694
 
707
    // stereo calibration
695
    // stereo calibration
708
    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;
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;
709
    cv::Mat E, F, R1, T1;
697
    cv::Mat E, F, R1, T1;
710
 
698
 
711
    #if CV_MAJOR_VERSION < 3
699
    #if CV_MAJOR_VERSION < 3
712
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
700
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
713
                                               frameSize, R1, T1, E, F,
701
                                               frameSize, R1, T1, E, F,
714
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON),
702
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON),
715
                                               flags_stereo);
703
                                               flags_stereo);
716
    #else
704
    #else
717
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
705
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
718
                                               frameSize, R1, T1, E, F, flags_stereo,
706
                                               frameSize, R1, T1, E, F, flags_stereo,
719
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON));
707
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON));
720
    #endif
708
    #endif
721
 
709
 
722
    cal.R1 = R1;
710
    cal.R1 = R1;
723
    cal.T1 = T1;
711
    cal.T1 = T1;
724
    cal.E = E;
712
    cal.E = E;
725
    cal.F = F;
713
    cal.F = F;
726
 
714
 
727
    // Print to log
715
    // Print to log
728
    std::stringstream out;
716
    std::stringstream out;
729
    out << "## Camera Calibration ##" << std::endl
717
    out << "## Camera Calibration ##" << std::endl
730
        << "No. images used for intrinsics of cam0: " << qc0.size() << std::endl
718
        << "No. images used for intrinsics of cam0: " << qc0.size() << std::endl
731
        << "No. images used for intrinsics of cam1: " << qc1.size() << std::endl
719
        << "No. images used for intrinsics of cam1: " << qc1.size() << std::endl
732
        << "No. images used for stereo calibration: " << qc0Stereo.size() << std::endl;
720
        << "No. images used for stereo calibration: " << qc0Stereo.size() << std::endl;
733
    cal.printCamera(out);
721
    cal.printCamera(out);
734
    out << std::endl << std::endl;
722
    out << std::endl << std::endl;
735
    emit logMessage(QString::fromStdString(out.str()));
723
    emit logMessage(QString::fromStdString(out.str()));
736
 
724
 
737
    // save to (reentrant qsettings object)
725
    // save to (reentrant qsettings object)
738
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
726
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
739
 
727
 
740
    emit done();
728
    emit done();
741
 
729
 
742
}
730
}
743
 
731
 
744
 
732
 
745
void SMCalibrationWorker::rotationStageCalibration(std::vector<SMCalibrationSet> calibrationData){
733
void SMCalibrationWorker::rotationStageCalibration(std::vector<SMCalibrationSet> calibrationData){
746
 
734
 
747
    int nSets = calibrationData.size();
735
    auto nSets = calibrationData.size();
748
 
736
 
749
    std::vector< std::vector<cv::Point2f> > qc0Stereo, qc1Stereo;
737
    std::vector< std::vector<cv::Point2f> > qc0Stereo, qc1Stereo;
750
    for(int i=0; i<nSets; i++){
738
    std::vector<cv::Point3f> Qi;
751
 
739
 
752
        if(!calibrationData[i].selected)
740
    QSettings settings;
753
            continue;
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();
754
 
744
 
-
 
745
    if(settings.value("calibration/method").toString() == "Charuco"){
-
 
746
 
755
        // Note: avoiding push_back has only minor theoretical value
747
        // Find id's which were detected in all images
-
 
748
        std::vector<int> ids;
-
 
749
 
756
        if(!calibrationData[i].qc0.empty() && !calibrationData[i].qc1.empty()){
750
        for(int i=0; i<calibrationData.size(); i++){
-
 
751
 
757
            qc0Stereo.push_back(calibrationData[i].qc0);
752
            if(!calibrationData[i].selected)
-
 
753
                continue;
-
 
754
 
-
 
755
            if(ids.empty()){
758
            qc1Stereo.push_back(calibrationData[i].qc1);
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;
759
        }
765
        }
760
    }
-
 
761
 
766
 
-
 
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
        }
-
 
771
 
-
 
772
        for(int i=0; i<calibrationData.size(); i++){
-
 
773
 
-
 
774
            if(!calibrationData[i].selected)
762
    QSettings settings;
775
                continue;
-
 
776
 
-
 
777
            std::vector<cv::Point2f> qc0StereoI, qc1StereoI;
-
 
778
            for(int j=0; j<ids.size(); j++){
-
 
779
 
-
 
780
                ptrdiff_t idx0 = std::find(calibrationData[i].qc0id.begin(), calibrationData[i].qc0id.end(), ids[j]) - calibrationData[i].qc0id.begin();
763
    SMCalibrationParameters cal = settings.value("calibration/parameters").value<SMCalibrationParameters>();
781
                ptrdiff_t idx1 = std::find(calibrationData[i].qc1id.begin(), calibrationData[i].qc1id.end(), ids[j]) - calibrationData[i].qc1id.begin();
-
 
782
 
-
 
783
                qc0StereoI.push_back(calibrationData[i].qc0[idx0]);
-
 
784
                qc1StereoI.push_back(calibrationData[i].qc1[idx1]);
-
 
785
 
-
 
786
            }
-
 
787
 
-
 
788
            qc0Stereo.push_back(qc0StereoI);
-
 
789
            qc1Stereo.push_back(qc1StereoI);
-
 
790
        }
-
 
791
 
-
 
792
        float markerLength = 0.8f*checkerSize;
-
 
793
 
-
 
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);
-
 
796
 
-
 
797
        for(int j=0; j<ids.size(); j++){
-
 
798
            Qi.push_back(board->chessboardCorners[ids[j]]);
-
 
799
        }
764
 
800
 
765
    if(qc0Stereo.size() > 2){
-
 
766
        // Generate world object coordinates [mm]
-
 
767
        const cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(),settings.value("calibration/patternSizeY", 13).toInt()));
-
 
768
        const float checkerSize = settings.value("calibration/squareSize", 10.0).toFloat();
-
 
769
        std::vector<cv::Point3f> Qi = generateWorldCoords(checkerCount, checkerSize);
-
 
770
 
-
 
771
        // Direct rotation axis calibration //
-
 
772
        // full camera matrices
-
 
773
        cv::Matx34f P0 = cv::Matx34f::eye();
-
 
774
        cv::Mat RT1(3, 4, CV_32F);
-
 
775
        cv::Mat(cal.R1).copyTo(RT1(cv::Range(0, 3), cv::Range(0, 3)));
-
 
776
        cv::Mat(cal.T1).copyTo(RT1(cv::Range(0, 3), cv::Range(3, 4)));
-
 
777
        cv::Matx34f P1 = cv::Matx34f(RT1);
-
 
778
 
-
 
779
        // calibration points in camera 0 frame
-
 
780
        std::vector< std::vector<cv::Point3f> > Qcam(qc0Stereo.size());
-
 
781
 
-
 
782
        #pragma omp parallel for
-
 
783
        for(unsigned int i=0; i<qc0Stereo.size(); i++){
-
 
784
            std::vector<cv::Point2f> qc0i, qc1i;
-
 
785
 
-
 
786
            cv::undistortPoints(qc0Stereo[i], qc0i, cal.K0, cal.k0);
-
 
787
            cv::undistortPoints(qc1Stereo[i], qc1i, cal.K1, cal.k1);
-
 
788
 
-
 
789
            cv::Mat Qhom, Qcami;
-
 
790
            cv::triangulatePoints(P0, P1, qc0i, qc1i, Qhom);
-
 
791
            cvtools::convertMatFromHomogeneous(Qhom, Qcami);
-
 
792
            std::vector<cv::Point3f> QcamiPoints;
-
 
793
            cvtools::matToPoints3f(Qcami, QcamiPoints);
-
 
794
 
-
 
795
            Qcam[i] = QcamiPoints;
-
 
796
        }
-
 
797
 
-
 
798
        cv::Vec3f axis, point;
-
 
799
        float rot_axis_error;
-
 
800
        rotationAxisEstimation(Qcam, Qi, axis, point);
-
 
801
        rotationAxisOptimization(Qcam, Qi, axis, point, rot_axis_error);
-
 
802
 
-
 
803
        // construct transformation matrix
-
 
804
        cv::Vec3f ex = axis.cross(cv::Vec3f(0,0,1.0));
-
 
805
        ex = cv::normalize(ex);
-
 
806
        cv::Vec3f ez = ex.cross(axis);
-
 
807
        ez = cv::normalize(ez);
-
 
808
 
-
 
809
        cv::Mat RrMat(3, 3, CV_32F);
-
 
810
        cv::Mat(ex).copyTo(RrMat.col(0));
-
 
811
        cv::Mat(axis).copyTo(RrMat.col(1));
-
 
812
        cv::Mat(ez).copyTo(RrMat.col(2));
-
 
813
 
-
 
814
        cal.Rr = cv::Matx33f(RrMat).t();
-
 
815
        cal.Tr = -cv::Matx33f(RrMat).t()*point;
-
 
816
        cal.rot_axis_error = rot_axis_error;
-
 
817
    } else {
801
    } else {
-
 
802
 
-
 
803
        // Normal checkerboard with all corners
818
        cal.Rr = cv::Matx33f::eye();
804
        for(auto i=0; i<nSets; i++){
-
 
805
 
819
        cal.Tr = cv::Vec3f(0,0,0);
806
            if(!calibrationData[i].selected)
820
        cal.rot_axis_error = -1;
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);
821
        return;
812
            }
-
 
813
        }
-
 
814
 
-
 
815
        Qi = generateWorldCoords(checkerCount, checkerSize);
-
 
816
 
822
    }
817
    }
823
 
818
 
-
 
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
 
824
    // Print to log
880
    // Print to log
825
    std::stringstream out;
881
    std::stringstream out;
826
    out << "## Rotation Stage Calibration ##" << std::endl
882
    out << "## Rotation Stage Calibration ##" << std::endl
827
        << "No. images used for calibration: " << qc0Stereo.size() << std::endl;
883
        << "No. images used for calibration: " << qc0Stereo.size() << std::endl;
828
    cal.printRotationStage(out);
884
    cal.printRotationStage(out);
829
    out << std::endl << std::endl;
885
    out << std::endl << std::endl;
830
    emit logMessage(QString::fromStdString(out.str()));
886
    emit logMessage(QString::fromStdString(out.str()));
831
 
887
 
832
    // Save to (reentrant) qsettings object
888
    // Save to (reentrant) qsettings object
833
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
889
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
834
 
890
 
835
    emit done();
891
    emit done();
836
}
892
}
837
 
893