Subversion Repositories seema-scanner

Rev

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

Rev 225 Rev 228
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 {
-
 
291
        qc.clear();
290
    }
292
    }
291
    return success;
293
    return success;
292
}
294
}
293
 
295
 
294
void SMCalibrationWorker::checkerboardDetection(SMCalibrationSet calibrationSet){
296
void SMCalibrationWorker::checkerboardDetection(SMCalibrationSet calibrationSet){
295
 
297
 
296
    QSettings settings;
298
    QSettings settings;
297
    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()));
298
 
300
 
299
    bool success0 = detectCheckerBoardCorners(checkerCount, calibrationSet.frame0, calibrationSet.frame0Result, calibrationSet.qc0);
301
    bool success0 = detectCheckerBoardCorners(checkerCount, calibrationSet.frame0, calibrationSet.frame0Result, calibrationSet.qc0);
300
    if(!success0)
302
    if(!success0){
-
 
303
//        calibrationSet.qc0.clear();
301
        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
    }
302
 
306
 
303
    bool success1 = detectCheckerBoardCorners(checkerCount, calibrationSet.frame1, calibrationSet.frame1Result, calibrationSet.qc1);
307
    bool success1 = detectCheckerBoardCorners(checkerCount, calibrationSet.frame1, calibrationSet.frame1Result, calibrationSet.qc1);
304
    if(!success1)
308
    if(!success1){
-
 
309
//        calibrationSet.qc1.clear();
305
        emit logMessage(QString("Could not detect checkerboard on set %1 camera1").arg(calibrationSet.id));
310
        emit logMessage(QString("Could not detect checkerboard on set %1 camera1").arg(calibrationSet.id));
-
 
311
    }
306
 
312
 
307
    emit newCheckerboardResult(calibrationSet.id, calibrationSet);
313
    emit newCheckerboardResult(calibrationSet.id, calibrationSet);
308
 
314
 
309
}
315
}
310
 
316
 
311
void SMCalibrationWorker::cameraCalibration(std::vector<SMCalibrationSet> calibrationData){
317
void SMCalibrationWorker::cameraCalibration(std::vector<SMCalibrationSet> calibrationData){
312
 
318
 
313
    QSettings settings;
319
    QSettings settings;
314
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
320
    cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(), settings.value("calibration/patternSizeY", 13).toInt()));
315
 
321
 
316
    unsigned int nSets = calibrationData.size();
322
    unsigned int nSets = calibrationData.size();
317
 
323
 
318
    // 2D Points collected for OpenCV's calibration procedures
324
    // 2D Points collected for OpenCV's calibration procedures
319
    std::vector< std::vector<cv::Point2f> > qc0, qc1, qc0Stereo, qc1Stereo;
325
    std::vector< std::vector<cv::Point2f> > qc0, qc1, qc0Stereo, qc1Stereo;
320
 
326
 
321
    for(int i=0; i<nSets; i++){
327
    for(int i=0; i<nSets; i++){
322
 
328
 
323
        if(!calibrationData[i].selected)
329
        if(!calibrationData[i].selected)
324
            continue;
330
            continue;
325
 
331
 
326
        // Note: avoiding push_back has only minor theoretical value
332
        // Note: avoiding push_back has only minor theoretical value
327
        if(!calibrationData[i].qc0.empty())
333
        if(!calibrationData[i].qc0.empty())
328
            qc0.push_back(calibrationData[i].qc0);
334
            qc0.push_back(calibrationData[i].qc0);
329
 
335
 
330
        if(!calibrationData[i].qc1.empty())
336
        if(!calibrationData[i].qc1.empty())
331
            qc1.push_back(calibrationData[i].qc1);
337
            qc1.push_back(calibrationData[i].qc1);
332
 
338
 
333
        if(!calibrationData[i].qc0.empty() && !calibrationData[i].qc1.empty()){
339
        if(!calibrationData[i].qc0.empty() && !calibrationData[i].qc1.empty()){
334
            qc0Stereo.push_back(calibrationData[i].qc0);
340
            qc0Stereo.push_back(calibrationData[i].qc0);
335
            qc1Stereo.push_back(calibrationData[i].qc1);
341
            qc1Stereo.push_back(calibrationData[i].qc1);
336
        }
342
        }
337
    }
343
    }
338
 
344
 
339
    // Generate world object coordinates [mm]
345
    // Generate world object coordinates [mm]
340
    std::vector<cv::Point3f> Qi = generateWorldCoords(checkerCount, settings.value("calibration/squareSize", 10.0).toFloat());
346
    std::vector<cv::Point3f> Qi = generateWorldCoords(checkerCount, settings.value("calibration/squareSize", 10.0).toFloat());
341
 
347
 
342
    std::vector< std::vector<cv::Point3f> > Q0(qc0.size(), Qi), Q1(qc1.size(), Qi), QStereo(qc0Stereo.size(), Qi);
348
    std::vector< std::vector<cv::Point3f> > Q0(qc0.size(), Qi), Q1(qc1.size(), Qi), QStereo(qc0Stereo.size(), Qi);
343
 
349
 
344
    // Calibrate the cameras
350
    // Calibrate the cameras
345
    SMCalibrationParameters cal;
351
    SMCalibrationParameters cal;
346
    cal.frameWidth = calibrationData[0].frame0.cols;
352
    cal.frameWidth = calibrationData[0].frame0.cols;
347
    cal.frameHeight = calibrationData[0].frame0.rows;
353
    cal.frameHeight = calibrationData[0].frame0.rows;
348
    cv::Size frameSize(cal.frameWidth, cal.frameHeight);
354
    cv::Size frameSize(cal.frameWidth, cal.frameHeight);
349
 
355
 
350
    // determine only k1, k2 for lens distortion
356
    // determine only k1, k2 for lens distortion
351
    int flags = cv::CALIB_FIX_ASPECT_RATIO + cv::CALIB_FIX_K3 + cv::CALIB_ZERO_TANGENT_DIST + cv::CALIB_FIX_PRINCIPAL_POINT;
357
    int flags = cv::CALIB_FIX_ASPECT_RATIO + cv::CALIB_FIX_K3 + cv::CALIB_ZERO_TANGENT_DIST + cv::CALIB_FIX_PRINCIPAL_POINT;
352
 
358
 
353
    std::vector<cv::Mat> cam_rvecs0, cam_tvecs0;
359
    std::vector<cv::Mat> cam_rvecs0, cam_tvecs0;
354
 
360
 
355
    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,
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,
356
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
362
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
357
 
363
 
358
    std::vector<cv::Mat> cam_rvecs1, cam_tvecs1;
364
    std::vector<cv::Mat> cam_rvecs1, cam_tvecs1;
359
    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,
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,
360
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
366
                                         cv::TermCriteria(cv::TermCriteria::COUNT+cv::TermCriteria::EPS, 100, DBL_EPSILON));
361
 
367
 
362
    // Stereo calibration
368
    // Stereo calibration
363
    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;
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;
364
    cv::Mat E, F, R1, T1;
370
    cv::Mat E, F, R1, T1;
365
 
371
 
366
    #if CV_MAJOR_VERSION < 3
372
    #if CV_MAJOR_VERSION < 3
367
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
373
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
368
                                               frameSize, R1, T1, E, F,
374
                                               frameSize, R1, T1, E, F,
369
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON),
375
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON),
370
                                               flags_stereo);
376
                                               flags_stereo);
371
    #else
377
    #else
372
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
378
        cal.stereo_error = cv::stereoCalibrate(QStereo, qc0Stereo, qc1Stereo, cal.K0, cal.k0, cal.K1, cal.k1,
373
                                               frameSize, R1, T1, E, F, flags_stereo,
379
                                               frameSize, R1, T1, E, F, flags_stereo,
374
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON));
380
                                               cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 200, DBL_EPSILON));
375
    #endif
381
    #endif
376
 
382
 
377
    cal.R1 = R1;
383
    cal.R1 = R1;
378
    cal.T1 = T1;
384
    cal.T1 = T1;
379
    cal.E = E;
385
    cal.E = E;
380
    cal.F = F;
386
    cal.F = F;
381
 
387
 
382
    // Print to log
388
    // Print to log
383
    std::stringstream out;
389
    std::stringstream out;
384
    out << "## Camera Calibration ##" << std::endl
390
    out << "## Camera Calibration ##" << std::endl
385
        << "No. images used for intrinsics of cam0: " << qc0.size() << std::endl
391
        << "No. images used for intrinsics of cam0: " << qc0.size() << std::endl
386
        << "No. images used for intrinsics of cam1: " << qc1.size() << std::endl
392
        << "No. images used for intrinsics of cam1: " << qc1.size() << std::endl
387
        << "No. images used for stereo calibration: " << qc0Stereo.size() << std::endl;
393
        << "No. images used for stereo calibration: " << qc0Stereo.size() << std::endl;
388
    cal.printCamera(out);
394
    cal.printCamera(out);
389
    out << std::endl << std::endl;
395
    out << std::endl << std::endl;
390
    emit logMessage(QString::fromStdString(out.str()));
396
    emit logMessage(QString::fromStdString(out.str()));
391
 
397
 
392
    // save to (reentrant) qsettings object
398
    // save to (reentrant) qsettings object
393
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
399
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
394
 
400
 
395
    emit done();
401
    emit done();
396
}
402
}
397
 
403
 
398
 
404
 
399
void SMCalibrationWorker::rotationStageCalibration(std::vector<SMCalibrationSet> calibrationData){
405
void SMCalibrationWorker::rotationStageCalibration(std::vector<SMCalibrationSet> calibrationData){
400
 
406
 
401
    int nSets = calibrationData.size();
407
    int nSets = calibrationData.size();
402
 
408
 
403
    std::vector< std::vector<cv::Point2f> > qc0Stereo, qc1Stereo;
409
    std::vector< std::vector<cv::Point2f> > qc0Stereo, qc1Stereo;
404
    for(int i=0; i<nSets; i++){
410
    for(int i=0; i<nSets; i++){
405
 
411
 
406
        if(!calibrationData[i].selected)
412
        if(!calibrationData[i].selected)
407
            continue;
413
            continue;
408
 
414
 
409
        // Note: avoiding push_back has only minor theoretical value
415
        // Note: avoiding push_back has only minor theoretical value
410
        if(!calibrationData[i].qc0.empty() && !calibrationData[i].qc1.empty()){
416
        if(!calibrationData[i].qc0.empty() && !calibrationData[i].qc1.empty()){
411
            qc0Stereo.push_back(calibrationData[i].qc0);
417
            qc0Stereo.push_back(calibrationData[i].qc0);
412
            qc1Stereo.push_back(calibrationData[i].qc1);
418
            qc1Stereo.push_back(calibrationData[i].qc1);
413
        }
419
        }
414
    }
420
    }
415
 
421
 
416
    QSettings settings;
422
    QSettings settings;
417
    SMCalibrationParameters cal = settings.value("calibration/parameters").value<SMCalibrationParameters>();
423
    SMCalibrationParameters cal = settings.value("calibration/parameters").value<SMCalibrationParameters>();
418
 
424
 
419
    if(qc0Stereo.size() > 2){
425
    if(qc0Stereo.size() > 2){
420
        // Generate world object coordinates [mm]
426
        // Generate world object coordinates [mm]
421
        const cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(),settings.value("calibration/patternSizeY", 13).toInt()));
427
        const cv::Size checkerCount(cv::Size(settings.value("calibration/patternSizeX", 22).toInt(),settings.value("calibration/patternSizeY", 13).toInt()));
422
        const float checkerSize = settings.value("calibration/squareSize", 10.0).toFloat();
428
        const float checkerSize = settings.value("calibration/squareSize", 10.0).toFloat();
423
        std::vector<cv::Point3f> Qi = generateWorldCoords(checkerCount, checkerSize);
429
        std::vector<cv::Point3f> Qi = generateWorldCoords(checkerCount, checkerSize);
424
 
430
 
425
        // Direct rotation axis calibration //
431
        // Direct rotation axis calibration //
426
        // full camera matrices
432
        // full camera matrices
427
        cv::Matx34f P0 = cv::Matx34f::eye();
433
        cv::Matx34f P0 = cv::Matx34f::eye();
428
        cv::Mat RT1(3, 4, CV_32F);
434
        cv::Mat RT1(3, 4, CV_32F);
429
        cv::Mat(cal.R1).copyTo(RT1(cv::Range(0, 3), cv::Range(0, 3)));
435
        cv::Mat(cal.R1).copyTo(RT1(cv::Range(0, 3), cv::Range(0, 3)));
430
        cv::Mat(cal.T1).copyTo(RT1(cv::Range(0, 3), cv::Range(3, 4)));
436
        cv::Mat(cal.T1).copyTo(RT1(cv::Range(0, 3), cv::Range(3, 4)));
431
        cv::Matx34f P1 = cv::Matx34f(RT1);
437
        cv::Matx34f P1 = cv::Matx34f(RT1);
432
 
438
 
433
        // calibration points in camera 0 frame
439
        // calibration points in camera 0 frame
434
        std::vector< std::vector<cv::Point3f> > Qcam(qc0Stereo.size());
440
        std::vector< std::vector<cv::Point3f> > Qcam(qc0Stereo.size());
435
 
441
 
436
        #pragma omp parallel for
442
        #pragma omp parallel for
437
        for(unsigned int i=0; i<qc0Stereo.size(); i++){
443
        for(unsigned int i=0; i<qc0Stereo.size(); i++){
438
            std::vector<cv::Point2f> qc0i, qc1i;
444
            std::vector<cv::Point2f> qc0i, qc1i;
439
 
445
 
440
            cv::undistortPoints(qc0Stereo[i], qc0i, cal.K0, cal.k0);
446
            cv::undistortPoints(qc0Stereo[i], qc0i, cal.K0, cal.k0);
441
            cv::undistortPoints(qc1Stereo[i], qc1i, cal.K1, cal.k1);
447
            cv::undistortPoints(qc1Stereo[i], qc1i, cal.K1, cal.k1);
442
 
448
 
443
            cv::Mat Qhom, Qcami;
449
            cv::Mat Qhom, Qcami;
444
            cv::triangulatePoints(P0, P1, qc0i, qc1i, Qhom);
450
            cv::triangulatePoints(P0, P1, qc0i, qc1i, Qhom);
445
            cvtools::convertMatFromHomogeneous(Qhom, Qcami);
451
            cvtools::convertMatFromHomogeneous(Qhom, Qcami);
446
            std::vector<cv::Point3f> QcamiPoints;
452
            std::vector<cv::Point3f> QcamiPoints;
447
            cvtools::matToPoints3f(Qcami, QcamiPoints);
453
            cvtools::matToPoints3f(Qcami, QcamiPoints);
448
 
454
 
449
            Qcam[i] = QcamiPoints;
455
            Qcam[i] = QcamiPoints;
450
        }
456
        }
451
 
457
 
452
        cv::Vec3f axis, point;
458
        cv::Vec3f axis, point;
453
        float rot_axis_error;
459
        float rot_axis_error;
454
        rotationAxisEstimation(Qcam, Qi, axis, point);
460
        rotationAxisEstimation(Qcam, Qi, axis, point);
455
        rotationAxisOptimization(Qcam, Qi, axis, point, rot_axis_error);
461
        rotationAxisOptimization(Qcam, Qi, axis, point, rot_axis_error);
456
 
462
 
457
        // construct transformation matrix
463
        // construct transformation matrix
458
        cv::Vec3f ex = axis.cross(cv::Vec3f(0,0,1.0));
464
        cv::Vec3f ex = axis.cross(cv::Vec3f(0,0,1.0));
459
        ex = cv::normalize(ex);
465
        ex = cv::normalize(ex);
460
        cv::Vec3f ez = ex.cross(axis);
466
        cv::Vec3f ez = ex.cross(axis);
461
        ez = cv::normalize(ez);
467
        ez = cv::normalize(ez);
462
 
468
 
463
        cv::Mat RrMat(3, 3, CV_32F);
469
        cv::Mat RrMat(3, 3, CV_32F);
464
        cv::Mat(ex).copyTo(RrMat.col(0));
470
        cv::Mat(ex).copyTo(RrMat.col(0));
465
        cv::Mat(axis).copyTo(RrMat.col(1));
471
        cv::Mat(axis).copyTo(RrMat.col(1));
466
        cv::Mat(ez).copyTo(RrMat.col(2));
472
        cv::Mat(ez).copyTo(RrMat.col(2));
467
 
473
 
468
        cal.Rr = cv::Matx33f(RrMat).t();
474
        cal.Rr = cv::Matx33f(RrMat).t();
469
        cal.Tr = -cv::Matx33f(RrMat).t()*point;
475
        cal.Tr = -cv::Matx33f(RrMat).t()*point;
470
        cal.rot_axis_error = rot_axis_error;
476
        cal.rot_axis_error = rot_axis_error;
471
    } else {
477
    } else {
472
        cal.Rr = cv::Matx33f::eye();
478
        cal.Rr = cv::Matx33f::eye();
473
        cal.Tr = cv::Vec3f(0,0,0);
479
        cal.Tr = cv::Vec3f(0,0,0);
474
        cal.rot_axis_error = -1;
480
        cal.rot_axis_error = -1;
475
        return;
481
        return;
476
    }
482
    }
477
 
483
 
478
    // Print to log
484
    // Print to log
479
    std::stringstream out;
485
    std::stringstream out;
480
    out << "## Rotation Stage Calibration ##" << std::endl
486
    out << "## Rotation Stage Calibration ##" << std::endl
481
        << "No. images used for calibration: " << qc0Stereo.size() << std::endl;
487
        << "No. images used for calibration: " << qc0Stereo.size() << std::endl;
482
    cal.printRotationStage(out);
488
    cal.printRotationStage(out);
483
    out << std::endl << std::endl;
489
    out << std::endl << std::endl;
484
    emit logMessage(QString::fromStdString(out.str()));
490
    emit logMessage(QString::fromStdString(out.str()));
485
 
491
 
486
    // Save to (reentrant) qsettings object
492
    // Save to (reentrant) qsettings object
487
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
493
    settings.setValue("calibration/parameters", QVariant::fromValue(cal));
488
 
494
 
489
    emit done();
495
    emit done();
490
}
496
}
491
 
497