Subversion Repositories seema-scanner

Rev

Rev 247 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
181 jakw 1
//
2
// Two Frequency Phase Shifting using the Heterodyne Principle
3
//
234 sorgre 4
// This implementation follows "Reich, Ritter, Thesing, White light heterodyne
5
// principle for 3D-measurement", SPIE (1997).
6
//
181 jakw 7
// Different from the paper, it uses only two different frequencies.
8
//
234 sorgre 9
// The number of periods in the primary frequency can be chosen freely, but
10
// small changes can have a considerable impact on quality. The number of
11
// phase shifts can be chosen freely (min. 3), and higher values reduce the
12
// effects of image noise.They also allow us to filter bad points based on
13
// energy at non-primary frequencies.
181 jakw 14
//
15
 
128 jakw 16
#include "AlgorithmPhaseShiftTwoFreq.h"
4 jakw 17
#include <math.h>
18
 
19
#include "cvtools.h"
182 jakw 20
#include "algorithmtools.h"
4 jakw 21
 
231 jakw 22
#include <omp.h>
23
 
143 jakw 24
static unsigned int nStepsPrimary = 16; // number of shifts/steps in primary
25
static unsigned int nStepsSecondary = 8; // number of shifts/steps in secondary
190 jakw 26
static float nPeriodsPrimary = 40; // primary period
4 jakw 27
 
234 sorgre 28
AlgorithmPhaseShiftTwoFreq::AlgorithmPhaseShiftTwoFreq(unsigned int _screenCols,
29
                                                       unsigned int _screenRows)
30
    : Algorithm(_screenCols, _screenRows) {
4 jakw 31
 
72 jakw 32
    // Set N
118 jakw 33
    N = 2+nStepsPrimary+nStepsSecondary;
72 jakw 34
 
190 jakw 35
    // Determine the secondary (wider) period to fulfill the heterodyne condition
36
    float nPeriodsSecondary = nPeriodsPrimary + 1;
74 jakw 37
 
70 jakw 38
    // all on pattern
39
    cv::Mat allOn(1, screenCols, CV_8UC3, cv::Scalar::all(255));
40
    patterns.push_back(allOn);
41
 
42
    // all off pattern
43
    cv::Mat allOff(1, screenCols, CV_8UC3, cv::Scalar::all(0));
44
    patterns.push_back(allOff);
45
 
74 jakw 46
    // Primary encoding patterns
118 jakw 47
    for(unsigned int i=0; i<nStepsPrimary; i++){
192 jakw 48
        float phase = 2.0*CV_PI/nStepsPrimary * i;
190 jakw 49
        float pitch = screenCols/nPeriodsPrimary;
70 jakw 50
        cv::Mat patternI(1,1,CV_8U);
51
        patternI = computePhaseVector(screenCols, phase, pitch);
52
        patterns.push_back(patternI.t());
53
    }
4 jakw 54
 
74 jakw 55
    // Secondary encoding patterns
118 jakw 56
    for(unsigned int i=0; i<nStepsSecondary; i++){
192 jakw 57
        float phase = 2.0*CV_PI/nStepsSecondary * i;
190 jakw 58
        float pitch = screenCols/nPeriodsSecondary;
72 jakw 59
        cv::Mat patternI(1,1,CV_8U);
70 jakw 60
        patternI = computePhaseVector(screenCols, phase, pitch);
61
        patterns.push_back(patternI.t());
4 jakw 62
    }
63
 
72 jakw 64
 
4 jakw 65
}
66
 
128 jakw 67
cv::Mat AlgorithmPhaseShiftTwoFreq::getEncodingPattern(unsigned int depth){
4 jakw 68
    return patterns[depth];
69
}
70
 
233 - 71
 
72
struct StereoRectifyier {
73
    cv::Mat map0X, map0Y, map1X, map1Y;
74
    cv::Mat R0, R1, P0, P1, QRect;
75
};
244 jakw 76
void getStereoRectifier(const SMCalibrationParameters &calibration,
77
                         const cv::Size& frameSize,
78
                         StereoRectifyier& stereoRect){
233 - 79
 
244 jakw 80
    // cv::stereoRectify segfaults unless R is double precision
81
    cv::Mat R, T;
82
    cv::Mat(calibration.R1).convertTo(R, CV_64F);
83
    cv::Mat(calibration.T1).convertTo(T, CV_64F);
233 - 84
 
244 jakw 85
    cv::stereoRectify(calibration.K0, calibration.k0,
86
                      calibration.K1, calibration.k1,
87
                      frameSize, R, T,
88
                      stereoRect.R0, stereoRect.R1,
89
                      stereoRect.P0, stereoRect.P1,
90
                      stereoRect.QRect, 0);
91
 
92
    // Interpolation maps (lens distortion and rectification)
93
    cv::initUndistortRectifyMap(calibration.K0, calibration.k0,
94
                                stereoRect.R0, stereoRect.P0,
95
                                frameSize, CV_32F,
96
                                stereoRect.map0X, stereoRect.map0Y);
97
    cv::initUndistortRectifyMap(calibration.K1, calibration.k1,
98
                                stereoRect.R1, stereoRect.P1,
99
                                frameSize, CV_32F,
100
                                stereoRect.map1X, stereoRect.map1Y);
101
}
102
 
103
void determineAmplitudePhaseEnergy(std::vector<cv::Mat>& frames,
104
                                   cv::Mat& amplitude,
105
                                   cv::Mat& phase,
106
                                   cv::Mat& energy) {
107
 
108
    std::vector<cv::Mat> fourier = getDFTComponents(frames);
109
 
110
    cv::phase(fourier[2], -fourier[3], phase);
111
 
112
    // Signal energy at unit frequency
113
    cv::magnitude(fourier[2], -fourier[3], amplitude);
114
 
115
    // Collected signal energy at higher frequencies
116
    energy = cv::Mat(phase.rows, phase.cols, CV_32F, cv::Scalar(0.0));
117
 
118
    for(unsigned int i=0; i<frames.size()-1; i++){
119
        cv::Mat magnitude;
120
        cv::magnitude(fourier[i*2 + 2], fourier[i*2 + 3], magnitude);
121
        cv::add(energy, magnitude, energy, cv::noArray(), CV_32F);
122
    }
123
 
124
    frames.clear();
125
}
126
 
127
void unWrapPhaseMap(const cv::Mat& phasePrimary,
128
                   const cv::Mat& phaseSecondary,
129
                   cv::Mat& phase) {
130
    cv::Mat phaseEquivalent = phaseSecondary - phasePrimary;
131
    phaseEquivalent = cvtools::modulo(phaseEquivalent, 2.0*CV_PI);
132
    phase = unwrapWithCue(phasePrimary, phaseEquivalent, nPeriodsPrimary);
133
    phase *= phasePrimary.cols/(2.0*CV_PI);
134
}
135
 
136
 
137
void matchPhaseMaps(const cv::Mat& occlusion0, const cv::Mat& occlusion1,
138
                    const cv::Mat& phase0, const cv::Mat& phase1,
139
                    std::vector<cv::Vec2f>& q0, std::vector<cv::Vec2f>& q1) {
140
 
141
    #pragma omp parallel for
142
    for(int row=0; row<occlusion0.rows; row++){
143
        for(int col=0; col<occlusion0.cols; col++){
144
 
145
            if(!occlusion0.at<char>(row,col))
146
                continue;
147
 
148
            float phase0i = phase0.at<float>(row,col);
149
            for(int col1=0; col1<phase1.cols-1; col1++){
150
 
151
                if(!occlusion1.at<char>(row,col1) || !occlusion1.at<char>(row,col1+1))
152
                    continue;
153
 
154
                float phase1Left = phase1.at<float>(row,col1);
155
                float phase1Right = phase1.at<float>(row,col1+1);
156
 
157
                bool match = (phase1Left <= phase0i)
158
                              && (phase0i <= phase1Right)
159
                              && (phase0i-phase1Left < 1.0)
160
                              && (phase1Right-phase0i < 1.0)
161
                              && (phase1Right-phase1Left > 0.1);
162
 
163
                if(match){
164
 
165
                    float col1i = col1 + (phase0i-phase1Left)/(phase1Right-phase1Left);
166
 
167
                    #pragma omp critical
168
                    {
169
                    q0.push_back(cv::Point2f(col, row));
170
                    q1.push_back(cv::Point2f(col1i, row));
171
                    }
172
                    break;
173
                }
174
            }
175
        }
176
    }
177
 
178
}
179
 
180
void triangulate(const StereoRectifyier& stereoRect,
181
                 const std::vector<cv::Vec2f>& q0,
182
                 const std::vector<cv::Vec2f>& q1,
183
                 std::vector<cv::Point3f>& Q) {
184
 
185
    // cv::Mat QMatHomogenous, QMat;
186
    // cv::triangulatePoints(P0, P1, q0, q1, QMatHomogenous);
187
    // cvtools::convertMatFromHomogeneous(QMatHomogenous, QMat);
188
 
189
    // // Undo rectification
190
    // cv::Mat R0Inv;
191
    // cv::Mat(R0.t()).convertTo(R0Inv, CV_32F);
192
    // QMat = R0Inv*QMat;
193
 
194
    // cvtools::matToPoints3f(QMat, Q);
195
 
196
 
197
    // Triangulate by means of disparity projection
198
    Q.resize(q0.size());
199
    cv::Matx44f QRectx = cv::Matx44f(stereoRect.QRect);
200
    cv::Matx33f R0invx = cv::Matx33f(cv::Mat(stereoRect.R0.t()));
201
 
202
    #pragma omp parallel for
203
    for(unsigned int i=0; i < q0.size(); i++){
204
        float disparity = q0[i][0] - q1[i][0];
205
        cv::Vec4f Qih = QRectx*cv::Vec4f(q0[i][0], q0[i][1], disparity, 1.0);
206
        float winv = float(1.0) / Qih[3];
207
        Q[i] = R0invx * cv::Point3f(Qih[0]*winv, Qih[1]*winv, Qih[2]*winv);
208
    }
209
}
210
 
234 sorgre 211
void AlgorithmPhaseShiftTwoFreq::
212
    get3DPoints(const SMCalibrationParameters & calibration,
213
                const std::vector<cv::Mat>& frames0,
214
                const std::vector<cv::Mat>& frames1,
215
                std::vector<cv::Point3f>& Q,
247 jakw 216
                std::vector<cv::Vec3f>& color){
4 jakw 217
 
70 jakw 218
    assert(frames0.size() == N);
219
    assert(frames1.size() == N);
220
 
233 - 221
    StereoRectifyier stereoRect;
244 jakw 222
    getStereoRectifier(calibration,
234 sorgre 223
                        cv::Size(frames0[0].cols, frames0[0].rows),
224
                        stereoRect);
231 jakw 225
 
233 - 226
    // // Erode occlusion masks
227
    // cv::Mat strel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(5,5));
228
 
229
    cv::Mat up0, up1;
230
    cv::Mat occlusion0, occlusion1;
231
    cv::Mat color0, color1;
232
 
233
    #pragma omp parallel sections
231 jakw 234
    {
233 - 235
        #pragma omp section
236
        {
70 jakw 237
 
233 - 238
            // Gray-scale and remap/rectify
239
            std::vector<cv::Mat> frames0Rect(N);
178 jakw 240
 
233 - 241
            for(unsigned int i=0; i<N; i++){
242
                cv::Mat temp;
251 - 243
                if(frames0[i].depth() == CV_8U)
244
                    cv::cvtColor(frames0[i], temp, CV_BayerBG2GRAY);
244 jakw 245
                else
251 - 246
                    temp = frames0[i];
234 sorgre 247
                cv::remap(temp, frames0Rect[i],
248
                          stereoRect.map0X, stereoRect.map0Y,
249
                          CV_INTER_LINEAR);
233 - 250
            }
207 flgw 251
 
244 jakw 252
            // If images are HDR (float), we need to convert to uchar
247 jakw 253
            frames0Rect[0].convertTo(color0, CV_32FC3);
234 sorgre 254
 
233 - 255
            // Occlusion masks
256
            cv::subtract(frames0Rect[0], frames0Rect[1], occlusion0);
257
            occlusion0 = (occlusion0 > 25) & (occlusion0 < 250);
182 jakw 258
 
233 - 259
            // Decode camera0
234 sorgre 260
            std::vector<cv::Mat> frames0Primary(frames0Rect.begin()+2,
261
                                                frames0Rect.begin()+2+nStepsPrimary);
262
            std::vector<cv::Mat> frames0Secondary(frames0Rect.begin()+2+nStepsPrimary,
263
                                                  frames0Rect.end());
70 jakw 264
 
233 - 265
            frames0Rect.clear();
182 jakw 266
 
233 - 267
            cv::Mat amplitude0Primary, amplitude0Secondary;
268
            cv::Mat up0Primary, up0Secondary;
269
            cv::Mat energy0Primary, energy0Secondary;
270
            determineAmplitudePhaseEnergy(frames0Primary,
234 sorgre 271
                                          amplitude0Primary,
272
                                          up0Primary,
273
                                          energy0Primary);
233 - 274
            determineAmplitudePhaseEnergy(frames0Secondary,
234 sorgre 275
                                          amplitude0Secondary,
276
                                          up0Secondary,
277
                                          energy0Secondary);
207 flgw 278
 
244 jakw 279
            unWrapPhaseMap(up0Primary, up0Secondary, up0);
231 jakw 280
 
233 - 281
            // Threshold on energy at primary frequency
282
            occlusion0 = occlusion0 & (amplitude0Primary > 5.0*nStepsPrimary);
283
            // Threshold on energy ratios
284
            occlusion0 = occlusion0 & (amplitude0Primary > 0.25*energy0Primary);
285
            occlusion0 = occlusion0 & (amplitude0Secondary > 0.25*energy0Secondary);
231 jakw 286
 
233 - 287
            // // Erode occlusion masks
288
            // cv::erode(occlusion0, occlusion0, strel);
231 jakw 289
 
244 jakw 290
            // Threshold on vertical gradient of phase
233 - 291
            cv::Mat edges0;
292
            cv::Sobel(up0, edges0, -1, 1, 1, 5);
293
            occlusion0 = occlusion0 & (abs(edges0) < 10);
182 jakw 294
 
233 - 295
            #ifdef SM_DEBUG
296
                cvtools::writeMat(up0Primary, "up0Primary.mat", "up0Primary");
297
                cvtools::writeMat(up0Secondary, "up0Secondary.mat", "up0Secondary");
298
                cvtools::writeMat(up0, "up0.mat", "up0");
234 sorgre 299
                cvtools::writeMat(amplitude0Primary,
300
                                  "amplitude0Primary.mat", "amplitude0Primary");
301
                cvtools::writeMat(amplitude0Secondary,
302
                                  "amplitude0Secondary.mat", "amplitude0Secondary");
303
                cvtools::writeMat(energy0Primary,
304
                                  "energy0Primary.mat", "energy0Primary");
305
                cvtools::writeMat(energy0Secondary,
306
                                  "energy0Secondary.mat", "energy0Secondary");
233 - 307
                cvtools::writeMat(edges0, "edges0.mat", "edges0");
308
                cvtools::writeMat(occlusion0, "occlusion0.mat", "occlusion0");
234 sorgre 309
                cvtools::writeMat(color0, "color0.mat", "color0");
233 - 310
            #endif
182 jakw 311
 
233 - 312
        }
313
        #pragma omp section
314
        {
70 jakw 315
 
233 - 316
            // Gray-scale and remap
317
            std::vector<cv::Mat> frames1Rect(N);
200 jakw 318
 
233 - 319
            for(unsigned int i=0; i<N; i++){
320
                cv::Mat temp;
244 jakw 321
                if(frames1[i].depth() == CV_8U)
322
                    cv::cvtColor(frames1[i], temp, CV_BayerBG2GRAY);
323
                else
324
                    temp = frames1[i];
234 sorgre 325
                cv::remap(temp, frames1Rect[i],
326
                          stereoRect.map1X, stereoRect.map1Y,
327
                          CV_INTER_LINEAR);
233 - 328
            }
182 jakw 329
 
244 jakw 330
            // If images are HDR (float), we need to convert to uchar
247 jakw 331
            frames1Rect[0].convertTo(color1, CV_32FC3);
234 sorgre 332
 
233 - 333
            // Occlusion masks
334
            cv::subtract(frames1Rect[0], frames1Rect[1], occlusion1);
335
            occlusion1 = (occlusion1 > 25) & (occlusion1 < 250);
336
 
337
            // Decode camera1
234 sorgre 338
            std::vector<cv::Mat> frames1Primary(frames1Rect.begin()+2,
339
                                                frames1Rect.begin()+2+nStepsPrimary);
340
            std::vector<cv::Mat> frames1Secondary(frames1Rect.begin()+2+nStepsPrimary,
341
                                                  frames1Rect.end());
233 - 342
 
343
            frames1Rect.clear();
344
 
345
            cv::Mat amplitude1Primary, amplitude1Secondary;
346
            cv::Mat up1Primary, up1Secondary;
347
            cv::Mat energy1Primary, energy1Secondary;
348
            determineAmplitudePhaseEnergy(frames1Primary,
234 sorgre 349
                                          amplitude1Primary,
350
                                          up1Primary,
351
                                          energy1Primary);
233 - 352
            determineAmplitudePhaseEnergy(frames1Secondary,
234 sorgre 353
                                          amplitude1Secondary,
354
                                          up1Secondary,
355
                                          energy1Secondary);
233 - 356
 
244 jakw 357
            unWrapPhaseMap(up1Primary, up1Secondary, up1);
233 - 358
 
359
            // Threshold on energy at primary frequency
360
            occlusion1 = occlusion1 & (amplitude1Primary > 5.0*nStepsPrimary);
361
            // Threshold on energy ratios
362
            occlusion1 = occlusion1 & (amplitude1Primary > 0.25*energy1Primary);
363
            occlusion1 = occlusion1 & (amplitude1Secondary > 0.25*energy1Secondary);
364
 
365
            // // Erode occlusion masks
366
            // cv::erode(occlusion1, occlusion1, strel);
367
 
368
 
244 jakw 369
            // Threshold on vertical gradient of phase
233 - 370
            cv::Mat edges1;
371
            cv::Sobel(up1, edges1, -1, 1, 1, 5);
372
            occlusion1 = occlusion1 & (abs(edges1) < 10);
373
 
374
            #ifdef SM_DEBUG
375
                cvtools::writeMat(up1Primary, "up1Primary.mat", "up1Primary");
376
                cvtools::writeMat(up1Secondary, "up1Secondary.mat", "up1Secondary");
377
                cvtools::writeMat(up1, "up1.mat", "up1");
234 sorgre 378
                cvtools::writeMat(amplitude1Primary,
379
                                  "amplitude1Primary.mat", "amplitude1Primary");
380
                cvtools::writeMat(amplitude1Secondary,
381
                                  "amplitude1Secondary.mat", "amplitude1Secondary");
382
                cvtools::writeMat(energy1Primary,
383
                                  "energy1Primary.mat", "energy1Primary");
384
                cvtools::writeMat(energy1Secondary,
385
                                  "energy1Secondary.mat", "energy1Secondary");
233 - 386
                cvtools::writeMat(edges1, "edges1.mat", "edges1");
387
                cvtools::writeMat(occlusion1, "occlusion1.mat", "occlusion1");
234 sorgre 388
                cvtools::writeMat(color1, "color1.mat", "color1");
233 - 389
            #endif
390
 
391
        }
182 jakw 392
    }
393
 
207 flgw 394
 
233 - 395
    // Match phase maps
185 jakw 396
 
233 - 397
    // camera0 against camera1
398
    std::vector<cv::Vec2f> q0, q1;
399
    matchPhaseMaps(occlusion0, occlusion1, up0, up1, q0, q1);
231 jakw 400
 
233 - 401
    size_t nMatches = q0.size();
402
 
403
    if(nMatches < 1){
404
        Q.resize(0);
405
        color.resize(0);
406
 
407
        return;
231 jakw 408
    }
234 sorgre 409
    else {
233 - 410
        // Retrieve color information
411
        color.resize(nMatches);
412
        for(unsigned int i=0; i<nMatches; i++){
413
 
247 jakw 414
            cv::Vec3f c0 = color0.at<cv::Vec3f>(int(q0[i][1]), int(q0[i][0]));
415
            cv::Vec3f c1 = color1.at<cv::Vec3f>(int(q1[i][1]), int(q1[i][0]));
233 - 416
 
417
            color[i] = 0.5*c0 + 0.5*c1;
418
        }
231 jakw 419
    }
207 flgw 420
 
233 - 421
    // Triangulate points
422
    triangulate(stereoRect, q0, q1, Q);
207 flgw 423
 
233 - 424
}
207 flgw 425