Subversion Repositories seema-scanner

Rev

Rev 236 | Rev 249 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 236 Rev 242
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 <QSettings>
6
#include <QSettings>
7
#include <QTextStream>
7
#include <QTextStream>
8
 
8
 
9
#include <ceres/ceres.h>
9
#include <ceres/ceres.h>
10
 
10
 
11
// Closed form solution to solve for the rotation axis from sets of 3D point coordinates of flat pattern feature points
11
// Closed form solution to solve for the rotation axis from sets of 3D point coordinates of flat pattern feature points
12
// Algorithm according to Chen et al., Rotation axis calibration of a turntable using constrained global optimization, Optik 2014
12
// Algorithm according to Chen et al., Rotation axis calibration of a turntable using constrained global optimization, Optik 2014
13
// DTU, 2014, Jakob Wilm
13
// DTU, 2014, Jakob Wilm
14
static void rotationAxisEstimation(const std::vector< std::vector<cv::Point3f> > Qcam,
14
static void rotationAxisEstimation(const std::vector< std::vector<cv::Point3f> > Qcam,
15
                                   const std::vector<cv::Point3f> Qobj,
15
                                   const std::vector<cv::Point3f> Qobj,
16
                                   cv::Vec3f &axis, cv::Vec3f &point){
16
                                   cv::Vec3f &axis, cv::Vec3f &point){
17
    assert(Qobj.size() == Qcam[0].size());
17
    assert(Qobj.size() == Qcam[0].size());
18
 
18
 
19
    // number of frames (points on each arch)
19
    // number of frames (points on each arch)
20
    int l = Qcam.size();
20
    int l = Qcam.size();
21
 
21
 
22
    // number of points in each frame
22
    // number of points in each frame
23
    size_t mn = Qobj.size();
23
    size_t mn = Qobj.size();
24
 
24
 
25
    // construct matrix for axis determination
25
    // construct matrix for axis determination
26
    cv::Mat M(6, 6, CV_32F, cv::Scalar(0));
26
    cv::Mat M(6, 6, CV_32F, cv::Scalar(0));
27
 
27
 
28
    for(int k=0; k<l; k++){
28
    for(int k=0; k<l; k++){
29
        for(unsigned int idx=0; idx<mn; idx++){
29
        for(unsigned int idx=0; idx<mn; idx++){
30
 
30
 
31
            //            float i = Qobj[idx].x+4;
31
            //            float i = Qobj[idx].x+4;
32
            //            float j = Qobj[idx].y+4;
32
            //            float j = Qobj[idx].y+4;
33
            float i = Qobj[idx].x;
33
            float i = Qobj[idx].x;
34
            float j = Qobj[idx].y;
34
            float j = Qobj[idx].y;
35
 
35
 
36
            float x = Qcam[k][idx].x;
36
            float x = Qcam[k][idx].x;
37
            float y = Qcam[k][idx].y;
37
            float y = Qcam[k][idx].y;
38
            float z = Qcam[k][idx].z;
38
            float z = Qcam[k][idx].z;
39
 
39
 
40
            M += (cv::Mat_<float>(6,6) << x*x, x*y, x*z, x, i*x, j*x,
40
            M += (cv::Mat_<float>(6,6) << x*x, x*y, x*z, x, i*x, j*x,
41
                  0, y*y, y*z, y, i*y, j*y,
41
                  0, y*y, y*z, y, i*y, j*y,
42
                  0,   0, z*z, z, i*z, j*z,
42
                  0,   0, z*z, z, i*z, j*z,
43
                  0,   0,   0, 1,   i,   j,
43
                  0,   0,   0, 1,   i,   j,
44
                  0,   0,   0, 0, i*i, i*j,
44
                  0,   0,   0, 0, i*i, i*j,
45
                  0,   0,   0, 0,   0, j*j);
45
                  0,   0,   0, 0,   0, j*j);
46
 
46
 
47
        }
47
        }
48
    }
48
    }
49
 
49
 
50
    cv::completeSymm(M, false);
50
    cv::completeSymm(M, false);
51
 
51
 
52
    // solve for axis
52
    // solve for axis
53
    std::vector<float> lambda;
53
    std::vector<float> lambda;
54
    cv::Mat u;
54
    cv::Mat u;
55
    cv::eigen(M, lambda, u);
55
    cv::eigen(M, lambda, u);
56
 
56
 
57
    float minLambda = std::abs(lambda[0]);
57
    float minLambda = std::abs(lambda[0]);
58
    int idx = 0;
58
    int idx = 0;
59
    for(unsigned int i=1; i<lambda.size(); i++){
59
    for(unsigned int i=1; i<lambda.size(); i++){
60
        if(abs(lambda[i]) < minLambda){
60
        if(abs(lambda[i]) < minLambda){
61
            minLambda = lambda[i];
61
            minLambda = lambda[i];
62
            idx = i;
62
            idx = i;
63
        }
63
        }
64
    }
64
    }
65
 
65
 
66
    axis = u.row(idx).colRange(0, 3);
66
    axis = u.row(idx).colRange(0, 3);
67
    axis = cv::normalize(axis);
67
    axis = cv::normalize(axis);
68
 
68
 
69
    float nx = u.at<float>(idx, 0);
69
    float nx = u.at<float>(idx, 0);
70
    float ny = u.at<float>(idx, 1);
70
    float ny = u.at<float>(idx, 1);
71
    float nz = u.at<float>(idx, 2);
71
    float nz = u.at<float>(idx, 2);
72
    //float d  = u.at<float>(idx, 3);
72
    //float d  = u.at<float>(idx, 3);
73
    float dh = u.at<float>(idx, 4);
73
    float dh = u.at<float>(idx, 4);
74
    float dv = u.at<float>(idx, 5);
74
    float dv = u.at<float>(idx, 5);
75
 
75
 
76
    // Paper version: c is initially eliminated
76
    // Paper version: c is initially eliminated
77
    /*cv::Mat A(l*mn, mn+2, CV_32F, cv::Scalar(0.0));
77
    /*cv::Mat A(l*mn, mn+2, CV_32F, cv::Scalar(0.0));
78
        cv::Mat bb(l*mn, 1, CV_32F);
78
        cv::Mat bb(l*mn, 1, CV_32F);
79
 
79
 
80
        for(int k=0; k<l; k++){
80
        for(int k=0; k<l; k++){
81
            for(unsigned int idx=0; idx<mn; idx++){
81
            for(unsigned int idx=0; idx<mn; idx++){
82
 
82
 
83
                float i = Qobj[idx].x;
83
                float i = Qobj[idx].x;
84
                float j = Qobj[idx].y;
84
                float j = Qobj[idx].y;
85
 
85
 
86
                float x = Qcam[k][idx].x;
86
                float x = Qcam[k][idx].x;
87
                float y = Qcam[k][idx].y;
87
                float y = Qcam[k][idx].y;
88
                float z = Qcam[k][idx].z;
88
                float z = Qcam[k][idx].z;
89
 
89
 
90
                float f = x*x + y*y + z*z + (2*x*nx + 2*y*ny + 2*z*nz)*(i*dh + j*dv);
90
                float f = x*x + y*y + z*z + (2*x*nx + 2*y*ny + 2*z*nz)*(i*dh + j*dv);
91
 
91
 
92
                int row = k*mn+idx;
92
                int row = k*mn+idx;
93
                A.at<float>(row, 0) = 2*x - (2*z*nx)/nz;
93
                A.at<float>(row, 0) = 2*x - (2*z*nx)/nz;
94
                A.at<float>(row, 1) = 2*y - (2*z*ny)/nz;
94
                A.at<float>(row, 1) = 2*y - (2*z*ny)/nz;
95
                A.at<float>(row, idx+2) = 1.0;
95
                A.at<float>(row, idx+2) = 1.0;
96
 
96
 
97
                bb.at<float>(row, 0) = f + (2*z*d)/nz;
97
                bb.at<float>(row, 0) = f + (2*z*d)/nz;
98
            }
98
            }
99
        }
99
        }
100
 
100
 
101
        // solve for point
101
        // solve for point
102
        cv::Mat abe;
102
        cv::Mat abe;
103
        cv::solve(A, bb, abe, cv::DECOMP_SVD);
103
        cv::solve(A, bb, abe, cv::DECOMP_SVD);
104
 
104
 
105
        float a = abe.at<float>(0, 0);
105
        float a = abe.at<float>(0, 0);
106
        float b = abe.at<float>(1, 0);
106
        float b = abe.at<float>(1, 0);
107
        float c = -(nx*a+ny*b+d)/nz;
107
        float c = -(nx*a+ny*b+d)/nz;
108
        */
108
        */
109
 
109
 
110
    // Our version: solve simultanously for a,b,c
110
    // Our version: solve simultanously for a,b,c
111
    cv::Mat A(l*mn, mn+3, CV_32F, cv::Scalar(0.0));
111
    cv::Mat A(l*mn, mn+3, CV_32F, cv::Scalar(0.0));
112
    cv::Mat bb(l*mn, 1, CV_32F);
112
    cv::Mat bb(l*mn, 1, CV_32F);
113
 
113
 
114
    for(int k=0; k<l; k++){
114
    for(int k=0; k<l; k++){
115
        for(unsigned int idx=0; idx<mn; idx++){
115
        for(unsigned int idx=0; idx<mn; idx++){
116
 
116
 
117
            float i = Qobj[idx].x;
117
            float i = Qobj[idx].x;
118
            float j = Qobj[idx].y;
118
            float j = Qobj[idx].y;
119
 
119
 
120
            float x = Qcam[k][idx].x;
120
            float x = Qcam[k][idx].x;
121
            float y = Qcam[k][idx].y;
121
            float y = Qcam[k][idx].y;
122
            float z = Qcam[k][idx].z;
122
            float z = Qcam[k][idx].z;
123
 
123
 
124
            float f = x*x + y*y + z*z + (2*x*nx + 2*y*ny + 2*z*nz)*(i*dh + j*dv);
124
            float f = x*x + y*y + z*z + (2*x*nx + 2*y*ny + 2*z*nz)*(i*dh + j*dv);
125
 
125
 
126
            int row = k*mn+idx;
126
            int row = k*mn+idx;
127
            A.at<float>(row, 0) = 2*x;
127
            A.at<float>(row, 0) = 2*x;
128
            A.at<float>(row, 1) = 2*y;
128
            A.at<float>(row, 1) = 2*y;
129
            A.at<float>(row, 2) = 2*z;
129
            A.at<float>(row, 2) = 2*z;
130
            A.at<float>(row, idx+3) = 1.0;
130
            A.at<float>(row, idx+3) = 1.0;
131
 
131
 
132
            bb.at<float>(row, 0) = f;
132
            bb.at<float>(row, 0) = f;
133
        }
133
        }
134
    }
134
    }
135
 
135
 
136
    // solve for point
136
    // solve for point
137
    cv::Mat abe;
137
    cv::Mat abe;
138
    cv::solve(A, bb, abe, cv::DECOMP_SVD);
138
    cv::solve(A, bb, abe, cv::DECOMP_SVD);
139
 
139
 
140
    float a = abe.at<float>(0, 0);
140
    float a = abe.at<float>(0, 0);
141
    float b = abe.at<float>(1, 0);
141
    float b = abe.at<float>(1, 0);
142
    float c = abe.at<float>(2, 0);
142
    float c = abe.at<float>(2, 0);
143
 
143
 
144
    point[0] = a;
144
    point[0] = a;
145
    point[1] = b;
145
    point[1] = b;
146
    point[2] = c;
146
    point[2] = c;
147
 
147
 
148
}
148
}
149
 
149
 
150
struct CircleResidual {
150
struct CircleResidual {
151
    CircleResidual(std::vector<cv::Point3f> _pointsOnArc)
151
    CircleResidual(std::vector<cv::Point3f> _pointsOnArc)
152
        : pointsOnArc(_pointsOnArc) {}
152
        : pointsOnArc(_pointsOnArc) {}
153
 
153
 
154
    template <typename T>
154
    template <typename T>
155
    bool operator()(const T* point, const T* axis, T* residual) const {
155
    bool operator()(const T* point, const T* axis, T* residual) const {
156
 
156
 
157
        T axisSqNorm = axis[0]*axis[0] + axis[1]*axis[1] + axis[2]*axis[2];
157
        T axisSqNorm = axis[0]*axis[0] + axis[1]*axis[1] + axis[2]*axis[2];
158
 
158
 
159
        unsigned int l = pointsOnArc.size();
159
        unsigned int l = pointsOnArc.size();
160
        std::vector<T> dI(l);
160
        std::vector<T> dI(l);
161
 
161
 
162
        // note, this is automatically initialized to 0
162
        // note, this is automatically initialized to 0
163
        T sum(0.0);
163
        T sum(0.0);
164
 
164
 
165
        for(unsigned int i=0; i<l; i++){
165
        for(unsigned int i=0; i<l; i++){
166
            cv::Point3d p = pointsOnArc[i];
166
            cv::Point3d p = pointsOnArc[i];
167
            //T p[3] = {pointsOnArc[i].x, pointsOnArc[i].y, pointsOnArc[i].z};
167
            //T p[3] = {pointsOnArc[i].x, pointsOnArc[i].y, pointsOnArc[i].z};
168
 
168
 
169
            // point to line distance
169
            // point to line distance
170
            T dotProd = (point[0]-p.x)*axis[0] + (point[1]-p.y)*axis[1] + (point[2]-p.z)*axis[2];
170
            T dotProd = (point[0]-p.x)*axis[0] + (point[1]-p.y)*axis[1] + (point[2]-p.z)*axis[2];
171
            T dIx = point[0] - p.x - (dotProd*axis[0]/axisSqNorm);
171
            T dIx = point[0] - p.x - (dotProd*axis[0]/axisSqNorm);
172
            T dIy = point[1] - p.y - (dotProd*axis[1]/axisSqNorm);
172
            T dIy = point[1] - p.y - (dotProd*axis[1]/axisSqNorm);
173
            T dIz = point[2] - p.z - (dotProd*axis[2]/axisSqNorm);
173
            T dIz = point[2] - p.z - (dotProd*axis[2]/axisSqNorm);
174
            dI[i] = ceres::sqrt(dIx*dIx + dIy*dIy + dIz*dIz);
174
            dI[i] = ceres::sqrt(dIx*dIx + dIy*dIy + dIz*dIz);
175
 
175
 
176
            sum += dI[i];
176
            sum += dI[i];
177
        }
177
        }
178
 
178
 
179
        T mean = sum / double(l);
179
        T mean = sum / double(l);
180
 
180
 
181
        for(unsigned int i=0; i<l; i++){
181
        for(unsigned int i=0; i<l; i++){
182
            residual[i] = dI[i] - mean;
182
            residual[i] = dI[i] - mean;
183
        }
183
        }
184
 
184
 
185
        return true;
185
        return true;
186
    }
186
    }
187
 
187
 
188
    private:
188
    private:
189
        // Observations for one checkerboard corner.
189
        // Observations for one checkerboard corner.
190
        const std::vector<cv::Point3f> pointsOnArc;
190
        const std::vector<cv::Point3f> pointsOnArc;
191
};
191
};
192
 
192
 
193
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){
193
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){
194
 
194
 
195
    // number of frames (points on each arch)
195
    // number of frames (points on each arch)
196
    size_t l = Qcam.size();
196
    size_t l = Qcam.size();
197
 
197
 
198
    // number of points in each frame
198
    // number of points in each frame
199
    size_t mn = Qobj.size();
199
    size_t mn = Qobj.size();
200
 
200
 
201
    // read initial guess
201
    // read initial guess
202
    double pointArray[] = {point[0], point[1], point[2]};
202
    double pointArray[] = {point[0], point[1], point[2]};
203
    double axisArray[] = {axis[0], axis[1], axis[2]};
203
    double axisArray[] = {axis[0], axis[1], axis[2]};
204
 
204
 
205
    ceres::Problem problem;
205
    ceres::Problem problem;
206
 
206
 
207
    // loop through saddle points
207
    // loop through saddle points
208
    for(unsigned int idx=0; idx<mn; idx++){
208
    for(unsigned int idx=0; idx<mn; idx++){
209
        std::vector<cv::Point3f> pointsOnArch(l);
209
        std::vector<cv::Point3f> pointsOnArch(l);
210
        for(unsigned int k=0; k<l; k++){
210
        for(unsigned int k=0; k<l; k++){
211
            pointsOnArch[k] = Qcam[k][idx];
211
            pointsOnArch[k] = Qcam[k][idx];
212
        }
212
        }
213
        ceres::CostFunction* cost_function =
213
        ceres::CostFunction* cost_function =
214
                new ceres::AutoDiffCostFunction<CircleResidual, ceres::DYNAMIC, 3, 3>(
214
                new ceres::AutoDiffCostFunction<CircleResidual, ceres::DYNAMIC, 3, 3>(
215
                    new CircleResidual(pointsOnArch), l);
215
                    new CircleResidual(pointsOnArch), l);
216
        problem.AddResidualBlock(cost_function, NULL, pointArray, axisArray);
216
        problem.AddResidualBlock(cost_function, NULL, pointArray, axisArray);
217
    }
217
    }
218
 
218
 
219
    // Run the solver!
219
    // Run the solver!
220
    ceres::Solver::Options options;
220
    ceres::Solver::Options options;
221
    options.linear_solver_type = ceres::DENSE_QR;
221
    options.linear_solver_type = ceres::DENSE_QR;
222
    options.minimizer_progress_to_stdout = true;
222
    options.minimizer_progress_to_stdout = true;
223
    ceres::Solver::Summary summary;
223
    ceres::Solver::Summary summary;
224
    ceres::Solve(options, &problem, &summary);
224
    ceres::Solve(options, &problem, &summary);
225
 
225
 
226
    std::cout << summary.BriefReport() << "\n";
226
    std::cout << summary.BriefReport() << "\n";
227
 
227
 
228
    point = cv::Vec3f(pointArray[0], pointArray[1], pointArray[2]);
228
    point = cv::Vec3f(pointArray[0], pointArray[1], pointArray[2]);
229
    axis = cv::Vec3f(axisArray[0], axisArray[1], axisArray[2]);
229
    axis = cv::Vec3f(axisArray[0], axisArray[1], axisArray[2]);
230
    axis /= cv::norm(axis);
230
    axis /= cv::norm(axis);
231
 
231
 
232
 
232
 
233
    // Error estimate (sum of squared differences)
233
    // Error estimate (sum of squared differences)
234
    error = 0;
234
    error = 0;
235
    // loop through saddle points
235
    // loop through saddle points
236
    for(unsigned int idx=0; idx<mn; idx++){
236
    for(unsigned int idx=0; idx<mn; idx++){
237
 
237
 
238
        // vector of distances from rotation axis
238
        // vector of distances from rotation axis
239
        std::vector<float> dI(l);
239
        std::vector<float> dI(l);
240
        // loop through angular positions
240
        // loop through angular positions
241
        for(unsigned int k=0; k<l; k++){
241
        for(unsigned int k=0; k<l; k++){
242
            cv::Vec3f p = cv::Vec3f(Qcam[k][idx]);
242
            cv::Vec3f p = cv::Vec3f(Qcam[k][idx]);
243
            // point to line distance
243
            // point to line distance
244
            dI[k] = cv::norm((point-p)-(point-p).dot(axis)*axis);
244
            dI[k] = cv::norm((point-p)-(point-p).dot(axis)*axis);
245
        }
245
        }
246
        float sum = std::accumulate(dI.begin(), dI.end(), 0.0);
246
        float sum = std::accumulate(dI.begin(), dI.end(), 0.0);
247
        float mean = sum / dI.size();
247
        float mean = sum / dI.size();
248
        float meanDev = 0;
248
        float meanDev = 0;
249
        for(unsigned int k=0; k<l; k++){
249
        for(unsigned int k=0; k<l; k++){
250
            meanDev += std::abs(dI[k] - mean);
250
            meanDev += std::abs(dI[k] - mean);
251
        }
251
        }
252
        meanDev /= l;
252
        meanDev /= l;
253
        error += meanDev;
253
        error += meanDev;
254
    }
254
    }
255
    error /= mn;
255
    error /= mn;
256
}
256
}
257
 
257
 
258
static std::vector<cv::Point3f> generateWorldCoords(const cv::Size checkerCount, const float checkerSize){
258
static std::vector<cv::Point3f> generateWorldCoords(const cv::Size checkerCount, const float checkerSize){
259
 
259
 
260
    std::vector<cv::Point3f> Qi;
260
    std::vector<cv::Point3f> Qi;
261
    for (int h=0; h<checkerCount.height; h++)
261
    for (int h=0; h<checkerCount.height; h++)
262
        for (int w=0; w<checkerCount.width; w++)
262
        for (int w=0; w<checkerCount.width; w++)
263
            Qi.push_back(cv::Point3f(checkerSize * w, checkerSize* h, 0.0));
263
            Qi.push_back(cv::Point3f(checkerSize * w, checkerSize* h, 0.0));
264
 
264
 
265
    return Qi;
265
    return Qi;
266
}
266
}
267
 
267
 
268
static bool detectCheckerBoardCorners(const cv::Size & checkerCount,
268
static bool detectCheckerBoardCorners(const cv::Size & checkerCount,
269
                                    const cv::Mat & frame,
269
                                    const cv::Mat & frame,
270
                                    cv::Mat & frameResult,
270
                                    cv::Mat & frameResult,
271
                                    std::vector<cv::Point2f> & qc){
271
                                    std::vector<cv::Point2f> & qc){
272
    // Convert to grayscale
272
    // Convert to grayscale
273
    cv::Mat gray;
273
    cv::Mat gray;
274
    if(frame.channels() == 1)
274
    if(frame.channels() == 1)
275
        cv::cvtColor(frame, gray, CV_BayerBG2GRAY);
275
        cv::cvtColor(frame, gray, CV_BayerBG2GRAY);
276
    else
276
    else
277
        cv::cvtColor(frame, gray, CV_RGB2GRAY);
277
        cv::cvtColor(frame, gray, CV_RGB2GRAY);
278
 
278
 
279
    // Extract checker corners
279
    // Extract checker corners
280
    bool success = cv::findChessboardCorners(gray, checkerCount, qc, cv::CALIB_CB_ADAPTIVE_THRESH + cv::CALIB_CB_FAST_CHECK);
280
    bool success = cv::findChessboardCorners(gray, checkerCount, qc, cv::CALIB_CB_ADAPTIVE_THRESH + cv::CALIB_CB_FAST_CHECK);
281
    if(success){
281
    if(success){
282
        cv::cornerSubPix(gray, qc, cv::Size(6, 6), cv::Size(1, 1), cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 20, 0.0001));
282
        cv::cornerSubPix(gray, qc, cv::Size(6, 6), cv::Size(1, 1), cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 20, 0.0001));
283
        // Draw colored chessboard
283
        // Draw colored chessboard
284
        if(frame.channels() == 1)
284
        if(frame.channels() == 1)
285
            cv::cvtColor(frame, frameResult, CV_BayerBG2RGB);
285
            cv::cvtColor(frame, frameResult, CV_BayerBG2RGB);
286
        else
286
        else
287
            frameResult = frame.clone();
287
            frameResult = frame.clone();
288
 
288
 
289
        cvtools::drawChessboardCorners(frameResult, checkerCount, qc, success, 10);
289
        cvtools::drawChessboardCorners(frameResult, checkerCount, qc, success, 10);
290
    } else {
290
    } else {
291
        qc.clear();
291
        qc.clear();
292
    }
292
    }
293
    return success;
293
    return success;
294
}
294
}
295
 
295
 
296
void SMCalibrationWorker::checkerboardDetection(SMCalibrationSet calibrationSet){
296
void SMCalibrationWorker::checkerboardDetection(SMCalibrationSet calibrationSet){
297
 
297
 
298
    QSettings settings;
298
    QSettings settings;
299
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
299
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
300
 
300
 
301
    bool success0 = detectCheckerBoardCorners(checkerCount, calibrationSet.frame0, calibrationSet.frame0Result, calibrationSet.qc0);
301
    bool success0 = detectCheckerBoardCorners(checkerCount, calibrationSet.frame0, calibrationSet.frame0Result, calibrationSet.qc0);
302
    if(!success0){
302
    if(!success0){
303
//        calibrationSet.qc0.clear();
303
//        calibrationSet.qc0.clear();
304
        emit logMessage(QString("Could not detect checkerboard on set %1 camera0").arg(calibrationSet.id));
304
        emit logMessage(QString("Could not detect checkerboard on set %1 camera0").arg(calibrationSet.id));
-
 
305
        std::cerr << "Could not detect checkerboard on set " << calibrationSet.id << " camera0" << std::endl;
305
    }
306
    }
306
 
307
 
307
    bool success1 = detectCheckerBoardCorners(checkerCount, calibrationSet.frame1, calibrationSet.frame1Result, calibrationSet.qc1);
308
    bool success1 = detectCheckerBoardCorners(checkerCount, calibrationSet.frame1, calibrationSet.frame1Result, calibrationSet.qc1);
308
    if(!success1){
309
    if(!success1){
309
//        calibrationSet.qc1.clear();
310
//        calibrationSet.qc1.clear();
310
        emit logMessage(QString("Could not detect checkerboard on set %1 camera1").arg(calibrationSet.id));
311
        emit logMessage(QString("Could not detect checkerboard on set %1 camera1").arg(calibrationSet.id));
-
 
312
        std::cerr << "Could not detect checkerboard on set " << calibrationSet.id << " camera1" << std::endl;
311
    }
313
    }
312
 
314
 
313
    emit newCheckerboardResult(calibrationSet.id, calibrationSet);
315
    emit newCheckerboardResult(calibrationSet.id, calibrationSet);
314
 
316
 
315
}
317
}
316
 
318
 
317
void SMCalibrationWorker::cameraCalibration(std::vector<SMCalibrationSet> calibrationData){
319
void SMCalibrationWorker::cameraCalibration(std::vector<SMCalibrationSet> calibrationData){
318
 
320
 
319
    QSettings settings;
321
    QSettings settings;
320
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
322
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
321
 
323
 
322
    unsigned int nSets = calibrationData.size();
324
    unsigned int nSets = calibrationData.size();
323
 
325
 
324
    // 2D Points collected for OpenCV's calibration procedures
326
    // 2D Points collected for OpenCV's calibration procedures
325
    std::vector< std::vector<cv::Point2f> > qc0, qc1, qc0Stereo, qc1Stereo;
327
    std::vector< std::vector<cv::Point2f> > qc0, qc1, qc0Stereo, qc1Stereo;
326
 
328
 
327
    for(unsigned int i=0; i<nSets; i++){
329
    for(unsigned int i=0; i<nSets; i++){
328
 
330
 
329
        if(!calibrationData[i].selected)
331
        if(!calibrationData[i].selected)
330
            continue;
332
            continue;
331
 
333
 
332
        // Note: avoiding push_back has only minor theoretical value
334
        // Note: avoiding push_back has only minor theoretical value
333
        if(!calibrationData[i].qc0.empty())
335
        if(!calibrationData[i].qc0.empty())
334
            qc0.push_back(calibrationData[i].qc0);
336
            qc0.push_back(calibrationData[i].qc0);
335
 
337
 
336
        if(!calibrationData[i].qc1.empty())
338
        if(!calibrationData[i].qc1.empty())
337
            qc1.push_back(calibrationData[i].qc1);
339
            qc1.push_back(calibrationData[i].qc1);
338
 
340
 
339
        if(!calibrationData[i].qc0.empty() && !calibrationData[i].qc1.empty()){
341
        if(!calibrationData[i].qc0.empty() && !calibrationData[i].qc1.empty()){
340
            qc0Stereo.push_back(calibrationData[i].qc0);
342
            qc0Stereo.push_back(calibrationData[i].qc0);
341
            qc1Stereo.push_back(calibrationData[i].qc1);
343
            qc1Stereo.push_back(calibrationData[i].qc1);
342
        }
344
        }
343
    }
345
    }
344
 
346
 
345
    // Generate world object coordinates [mm]
347
    // Generate world object coordinates [mm]
346
    std::vector<cv::Point3f> Qi = generateWorldCoords(checkerCount, settings.value("calibration/squareSize", 10.0).toFloat());
348
    std::vector<cv::Point3f> Qi = generateWorldCoords(checkerCount, settings.value("calibration/squareSize", 10.0).toFloat());
347
 
349
 
348
    std::vector< std::vector<cv::Point3f> > Q0(qc0.size(), Qi), Q1(qc1.size(), Qi), QStereo(qc0Stereo.size(), Qi);
350
    std::vector< std::vector<cv::Point3f> > Q0(qc0.size(), Qi), Q1(qc1.size(), Qi), QStereo(qc0Stereo.size(), Qi);
349
 
351
 
350
    // Calibrate the cameras
352
    // Calibrate the cameras
351
    SMCalibrationParameters cal;
353
    SMCalibrationParameters cal;
352
    cal.frameWidth = calibrationData[0].frame0.cols;
354
    cal.frameWidth = calibrationData[0].frame0.cols;
353
    cal.frameHeight = calibrationData[0].frame0.rows;
355
    cal.frameHeight = calibrationData[0].frame0.rows;
354
    cv::Size frameSize(cal.frameWidth, cal.frameHeight);
356
    cv::Size frameSize(cal.frameWidth, cal.frameHeight);
355
 
357
 
356
    // determine only k1, k2 for lens distortion
358
    // determine only k1, k2 for lens distortion
357
    int flags = cv::CALIB_FIX_ASPECT_RATIO + cv::CALIB_FIX_K3 + cv::CALIB_ZERO_TANGENT_DIST + cv::CALIB_FIX_PRINCIPAL_POINT;
359
    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;
358
 
360
 
359
    std::vector<cv::Mat> cam_rvecs0, cam_tvecs0;
361
    std::vector<cv::Mat> cam_rvecs0, cam_tvecs0;
360
 
362
 
361
    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,
363
    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,
362
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
364
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
363
 
365
 
364
    std::vector<cv::Mat> cam_rvecs1, cam_tvecs1;
366
    std::vector<cv::Mat> cam_rvecs1, cam_tvecs1;
365
    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,
367
    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,
366
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
368
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
367
 
369
 
368
    // Stereo calibration
370
    // Stereo calibration
369
    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;
371
    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;
370
    cv::Mat E, F, R1, T1;
372
    cv::Mat E, F, R1, T1;
371
 
373
 
372
    #if CV_MAJOR_VERSION < 3
374
    #if CV_MAJOR_VERSION < 3
373
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
375
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
374
                                               frameSize, R1, T1, E, F,
376
                                               frameSize, R1, T1, E, F,
375
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON),
377
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON),
376
                                               flags_stereo);
378
                                               flags_stereo);
377
    #else
379
    #else
378
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
380
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
379
                                               frameSize, R1, T1, E, F, flags_stereo,
381
                                               frameSize, R1, T1, E, F, flags_stereo,
380
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON));
382
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON));
381
    #endif
383
    #endif
382
 
384
 
383
    cal.R1 = R1;
385
    cal.R1 = R1;
384
    cal.T1 = T1;
386
    cal.T1 = T1;
385
    cal.E = E;
387
    cal.E = E;
386
    cal.F = F;
388
    cal.F = F;
387
 
389
 
388
    // Print to log
390
    // Print to log
389
    std::stringstream out;
391
    std::stringstream out;
390
    out << "## Camera Calibration ##" << std::endl
392
    out << "## Camera Calibration ##" << std::endl
391
        << "No. images used for intrinsics of cam0: " << qc0.size() << std::endl
393
        << "No. images used for intrinsics of cam0: " << qc0.size() << std::endl
392
        << "No. images used for intrinsics of cam1: " << qc1.size() << std::endl
394
        << "No. images used for intrinsics of cam1: " << qc1.size() << std::endl
393
        << "No. images used for stereo calibration: " << qc0Stereo.size() << std::endl;
395
        << "No. images used for stereo calibration: " << qc0Stereo.size() << std::endl;
394
    cal.printCamera(out);
396
    cal.printCamera(out);
395
    out << std::endl << std::endl;
397
    out << std::endl << std::endl;
396
    emit logMessage(QString::fromStdString(out.str()));
398
    emit logMessage(QString::fromStdString(out.str()));
397
 
399
 
398
    // save to (reentrant) qsettings object
400
    // save to (reentrant) qsettings object
399
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
401
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
400
 
402
 
401
    emit done();
403
    emit done();
402
}
404
}
403
 
405
 
404
 
406
 
405
void SMCalibrationWorker::rotationStageCalibration(std::vector<SMCalibrationSet> calibrationData){
407
void SMCalibrationWorker::rotationStageCalibration(std::vector<SMCalibrationSet> calibrationData){
406
 
408
 
407
    int nSets = calibrationData.size();
409
    int nSets = calibrationData.size();
408
 
410
 
409
    std::vector< std::vector<cv::Point2f> > qc0Stereo, qc1Stereo;
411
    std::vector< std::vector<cv::Point2f> > qc0Stereo, qc1Stereo;
410
    for(int i=0; i<nSets; i++){
412
    for(int i=0; i<nSets; i++){
411
 
413
 
412
        if(!calibrationData[i].selected)
414
        if(!calibrationData[i].selected)
413
            continue;
415
            continue;
414
 
416
 
415
        // Note: avoiding push_back has only minor theoretical value
417
        // Note: avoiding push_back has only minor theoretical value
416
        if(!calibrationData[i].qc0.empty() && !calibrationData[i].qc1.empty()){
418
        if(!calibrationData[i].qc0.empty() && !calibrationData[i].qc1.empty()){
417
            qc0Stereo.push_back(calibrationData[i].qc0);
419
            qc0Stereo.push_back(calibrationData[i].qc0);
418
            qc1Stereo.push_back(calibrationData[i].qc1);
420
            qc1Stereo.push_back(calibrationData[i].qc1);
419
        }
421
        }
420
    }
422
    }
421
 
423
 
422
    QSettings settings;
424
    QSettings settings;
423
    SMCalibrationParameters cal = settings.value("calibration/parameters").value<SMCalibrationParameters>();
425
    SMCalibrationParameters cal = settings.value("calibration/parameters").value<SMCalibrationParameters>();
424
 
426
 
425
    if(qc0Stereo.size() > 2){
427
    if(qc0Stereo.size() > 2){
426
        // Generate world object coordinates [mm]
428
        // Generate world object coordinates [mm]
427
        const cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(),settings.value("calibration/patternSizeY", 13).toInt()));
429
        const cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(),settings.value("calibration/patternSizeY", 13).toInt()));
428
        const float checkerSize = settings.value("calibration/squareSize", 10.0).toFloat();
430
        const float checkerSize = settings.value("calibration/squareSize", 10.0).toFloat();
429
        std::vector<cv::Point3f> Qi = generateWorldCoords(checkerCount, checkerSize);
431
        std::vector<cv::Point3f> Qi = generateWorldCoords(checkerCount, checkerSize);
430
 
432
 
431
        // Direct rotation axis calibration //
433
        // Direct rotation axis calibration //
432
        // full camera matrices
434
        // full camera matrices
433
        cv::Matx34f P0 = cv::Matx34f::eye();
435
        cv::Matx34f P0 = cv::Matx34f::eye();
434
        cv::Mat RT1(3, 4, CV_32F);
436
        cv::Mat RT1(3, 4, CV_32F);
435
        cv::Mat(cal.R1).copyTo(RT1(cv::Range(0, 3), cv::Range(0, 3)));
437
        cv::Mat(cal.R1).copyTo(RT1(cv::Range(0, 3), cv::Range(0, 3)));
436
        cv::Mat(cal.T1).copyTo(RT1(cv::Range(0, 3), cv::Range(3, 4)));
438
        cv::Mat(cal.T1).copyTo(RT1(cv::Range(0, 3), cv::Range(3, 4)));
437
        cv::Matx34f P1 = cv::Matx34f(RT1);
439
        cv::Matx34f P1 = cv::Matx34f(RT1);
438
 
440
 
439
        // calibration points in camera 0 frame
441
        // calibration points in camera 0 frame
440
        std::vector< std::vector<cv::Point3f> > Qcam(qc0Stereo.size());
442
        std::vector< std::vector<cv::Point3f> > Qcam(qc0Stereo.size());
441
 
443
 
442
        #pragma omp parallel for
444
        #pragma omp parallel for
443
        for(unsigned int i=0; i<qc0Stereo.size(); i++){
445
        for(unsigned int i=0; i<qc0Stereo.size(); i++){
444
            std::vector<cv::Point2f> qc0i, qc1i;
446
            std::vector<cv::Point2f> qc0i, qc1i;
445
 
447
 
446
            cv::undistortPoints(qc0Stereo[i], qc0i, cal.K0, cal.k0);
448
            cv::undistortPoints(qc0Stereo[i], qc0i, cal.K0, cal.k0);
447
            cv::undistortPoints(qc1Stereo[i], qc1i, cal.K1, cal.k1);
449
            cv::undistortPoints(qc1Stereo[i], qc1i, cal.K1, cal.k1);
448
 
450
 
449
            cv::Mat Qhom, Qcami;
451
            cv::Mat Qhom, Qcami;
450
            cv::triangulatePoints(P0, P1, qc0i, qc1i, Qhom);
452
            cv::triangulatePoints(P0, P1, qc0i, qc1i, Qhom);
451
            cvtools::convertMatFromHomogeneous(Qhom, Qcami);
453
            cvtools::convertMatFromHomogeneous(Qhom, Qcami);
452
            std::vector<cv::Point3f> QcamiPoints;
454
            std::vector<cv::Point3f> QcamiPoints;
453
            cvtools::matToPoints3f(Qcami, QcamiPoints);
455
            cvtools::matToPoints3f(Qcami, QcamiPoints);
454
 
456
 
455
            Qcam[i] = QcamiPoints;
457
            Qcam[i] = QcamiPoints;
456
        }
458
        }
457
 
459
 
458
        cv::Vec3f axis, point;
460
        cv::Vec3f axis, point;
459
        float rot_axis_error;
461
        float rot_axis_error;
460
        rotationAxisEstimation(Qcam, Qi, axis, point);
462
        rotationAxisEstimation(Qcam, Qi, axis, point);
461
        rotationAxisOptimization(Qcam, Qi, axis, point, rot_axis_error);
463
        rotationAxisOptimization(Qcam, Qi, axis, point, rot_axis_error);
462
 
464
 
463
        // construct transformation matrix
465
        // construct transformation matrix
464
        cv::Vec3f ex = axis.cross(cv::Vec3f(0,0,1.0));
466
        cv::Vec3f ex = axis.cross(cv::Vec3f(0,0,1.0));
465
        ex = cv::normalize(ex);
467
        ex = cv::normalize(ex);
466
        cv::Vec3f ez = ex.cross(axis);
468
        cv::Vec3f ez = ex.cross(axis);
467
        ez = cv::normalize(ez);
469
        ez = cv::normalize(ez);
468
 
470
 
469
        cv::Mat RrMat(3, 3, CV_32F);
471
        cv::Mat RrMat(3, 3, CV_32F);
470
        cv::Mat(ex).copyTo(RrMat.col(0));
472
        cv::Mat(ex).copyTo(RrMat.col(0));
471
        cv::Mat(axis).copyTo(RrMat.col(1));
473
        cv::Mat(axis).copyTo(RrMat.col(1));
472
        cv::Mat(ez).copyTo(RrMat.col(2));
474
        cv::Mat(ez).copyTo(RrMat.col(2));
473
 
475
 
474
        cal.Rr = cv::Matx33f(RrMat).t();
476
        cal.Rr = cv::Matx33f(RrMat).t();
475
        cal.Tr = -cv::Matx33f(RrMat).t()*point;
477
        cal.Tr = -cv::Matx33f(RrMat).t()*point;
476
        cal.rot_axis_error = rot_axis_error;
478
        cal.rot_axis_error = rot_axis_error;
477
    } else {
479
    } else {
478
        cal.Rr = cv::Matx33f::eye();
480
        cal.Rr = cv::Matx33f::eye();
479
        cal.Tr = cv::Vec3f(0,0,0);
481
        cal.Tr = cv::Vec3f(0,0,0);
480
        cal.rot_axis_error = -1;
482
        cal.rot_axis_error = -1;
481
        return;
483
        return;
482
    }
484
    }
483
 
485
 
484
    // Print to log
486
    // Print to log
485
    std::stringstream out;
487
    std::stringstream out;
486
    out << "## Rotation Stage Calibration ##" << std::endl
488
    out << "## Rotation Stage Calibration ##" << std::endl
487
        << "No. images used for calibration: " << qc0Stereo.size() << std::endl;
489
        << "No. images used for calibration: " << qc0Stereo.size() << std::endl;
488
    cal.printRotationStage(out);
490
    cal.printRotationStage(out);
489
    out << std::endl << std::endl;
491
    out << std::endl << std::endl;
490
    emit logMessage(QString::fromStdString(out.str()));
492
    emit logMessage(QString::fromStdString(out.str()));
491
 
493
 
492
    // Save to (reentrant) qsettings object
494
    // Save to (reentrant) qsettings object
493
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
495
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
494
 
496
 
495
    emit done();
497
    emit done();
496
}
498
}
497
 
499