Subversion Repositories seema-scanner

Rev

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

Rev Author Line No. Line
182 jakw 1
//
2
// Gray Code Structured Light
3
//
4
// This implementation closely follows Henrik Aanaes, "Lecture Notes on Computer Vision" (2014).
5
//
6
 
41 jakw 7
#include "AlgorithmGrayCode.h"
4 jakw 8
#include <cmath>
42 jakw 9
#include "cvtools.h"
182 jakw 10
#include "algorithmtools.h"
4 jakw 11
 
36 jakw 12
// Algorithm
70 jakw 13
AlgorithmGrayCode::AlgorithmGrayCode(unsigned int _screenCols, unsigned int _screenRows) : Algorithm(_screenCols, _screenRows){
4 jakw 14
 
255 - 15
    Nbits = 6;
42 jakw 16
    N = 2 + Nbits*2;
41 jakw 17
 
18
    // all on pattern
42 jakw 19
    cv::Mat allOn(1, screenCols, CV_8UC3, cv::Scalar::all(255));
20
    patterns.push_back(allOn);
41 jakw 21
 
22
    // all off pattern
42 jakw 23
    cv::Mat allOff(1, screenCols, CV_8UC3, cv::Scalar::all(0));
24
    patterns.push_back(allOff);
41 jakw 25
 
4 jakw 26
 
42 jakw 27
    // horizontally encoding patterns
28
    for(unsigned int p=0; p<Nbits; p++){
29
        cv::Mat pattern(1, screenCols, CV_8UC3);
30
        cv::Mat patternInv(1, screenCols, CV_8UC3);
4 jakw 31
 
42 jakw 32
        for(unsigned int j=0; j<screenCols; j++){
4 jakw 33
 
42 jakw 34
            unsigned int jGray = binaryToGray(j);
35
            // Amplitude of channels
133 jakw 36
            int bit = (int)getBit(jGray, Nbits-p+1);
42 jakw 37
            pattern.at<cv::Vec3b>(0,j) = cv::Vec3b(255.0*bit,255.0*bit,255.0*bit);
38
            int invBit = bit^1;
39
            patternInv.at<cv::Vec3b>(0,j) = cv::Vec3b(255.0*invBit,255.0*invBit,255.0*invBit);
4 jakw 40
        }
42 jakw 41
        patterns.push_back(pattern);
42
        patterns.push_back(patternInv);
4 jakw 43
    }
42 jakw 44
 
255 - 45
    std::cout << "N patterns" << patterns.size() << std::endl;
4 jakw 46
}
47
 
36 jakw 48
cv::Mat AlgorithmGrayCode::getEncodingPattern(unsigned int depth){
4 jakw 49
    return patterns[depth];
50
}
51
 
52
 
47 jakw 53
bool sortingLarger(cv::Vec4i i,cv::Vec4i j){ return (i[3]<j[3]);}
54
bool sortingEqual(cv::Vec4i i,cv::Vec4i j){ return (i[3]==j[3]);}
55
void getEdgeLabels(const cv::Mat& scanLine, int Nbits, std::vector<cv::Vec4i>& edges){
4 jakw 56
 
41 jakw 57
    int nCols = scanLine.cols;
45 jakw 58
    const int *data = scanLine.ptr<const int>(0);
41 jakw 59
 
45 jakw 60
    int labelLeft;
61
    int labelRight = data[0];
41 jakw 62
 
43 jakw 63
    // collect edges
42 jakw 64
    for(int col=1; col<nCols; col++){
41 jakw 65
 
42 jakw 66
        labelLeft = labelRight;
67
        labelRight = data[col];
68
 
255 - 69
        // labels need to be non-background
70
        if(labelLeft != -1 && labelRight != -1) {
71
            unsigned int binLeft = grayToBinary(labelLeft);
72
            unsigned int binRight = grayToBinary(labelRight);
73
            // and differ in exactly one bit
74
            if (binRight + 1 == binLeft || binRight == binLeft + 1) {
75
                int orderingRelation = (labelLeft << Nbits) + labelRight;
76
                // store left label column
77
                edges.push_back(cv::Vec4i(col-1, labelLeft, labelRight, orderingRelation));
78
            }
41 jakw 79
        }
80
    }
81
 
42 jakw 82
    // sort
41 jakw 83
    std::sort(edges.begin(), edges.end(), sortingLarger);
42 jakw 84
 
85
    // remove duplicates
47 jakw 86
    std::vector<cv::Vec4i>::iterator it;
42 jakw 87
    it = std::unique(edges.begin(), edges.end(), sortingEqual);
88
    edges.resize(std::distance(edges.begin(),it));
4 jakw 89
}
90
 
245 jakw 91
void AlgorithmGrayCode::get3DPoints(const SMCalibrationParameters &calibration, const std::vector<cv::Mat>& frames0, const std::vector<cv::Mat>& frames1, std::vector<cv::Point3f>& Q, std::vector<cv::Vec3f>& color){
4 jakw 92
 
41 jakw 93
    assert(frames0.size() == N);
94
    assert(frames1.size() == N);
4 jakw 95
 
42 jakw 96
    int frameRows = frames0[0].rows;
97
    int frameCols = frames0[0].cols;
98
 
99
    // rectifying homographies (rotation+projections)
100
    cv::Size frameSize(frameCols, frameRows);
101
    cv::Mat R, T;
102
    // stereoRectify segfaults unless R is double precision
103
    cv::Mat(calibration.R1).convertTo(R, CV_64F);
104
    cv::Mat(calibration.T1).convertTo(T, CV_64F);
105
    cv::Mat R0, R1, P0, P1, QRect;
106
    cv::stereoRectify(calibration.K0, calibration.k0, calibration.K1, calibration.k1, frameSize, R, T, R0, R1, P0, P1, QRect, 0);
107
 
41 jakw 108
    // interpolation maps
109
    cv::Mat map0X, map0Y, map1X, map1Y;
42 jakw 110
    cv::initUndistortRectifyMap(calibration.K0, calibration.k0, R0, P0, frameSize, CV_32F, map0X, map0Y);
111
    cv::initUndistortRectifyMap(calibration.K1, calibration.k1, R1, P1, frameSize, CV_32F, map1X, map1Y);
41 jakw 112
 
43 jakw 113
    // gray-scale and remap
114
    std::vector<cv::Mat> frames0Rect(N);
115
    std::vector<cv::Mat> frames1Rect(N);
167 jakw 116
    for(unsigned int i=0; i<N; i++){
43 jakw 117
        cv::Mat temp;
245 jakw 118
        cv::cvtColor(frames0[i], temp, CV_RGB2GRAY);
114 jakw 119
        cv::remap(temp, frames0Rect[i], map0X, map0Y, CV_INTER_LINEAR);
245 jakw 120
        cv::cvtColor(frames1[i], temp, CV_RGB2GRAY);
114 jakw 121
        cv::remap(temp, frames1Rect[i], map1X, map1Y, CV_INTER_LINEAR);
43 jakw 122
    }
41 jakw 123
 
245 jakw 124
    // color remap
43 jakw 125
    cv::Mat color0Rect, color1Rect;
245 jakw 126
    cv::remap(frames0[0], color0Rect, map0X, map0Y, CV_INTER_LINEAR);
127
    cv::remap(frames1[0], color1Rect, map1X, map1Y, CV_INTER_LINEAR);
41 jakw 128
 
43 jakw 129
    int frameRectRows = frames0Rect[0].rows;
130
    int frameRectCols = frames0Rect[0].cols;
42 jakw 131
 
47 jakw 132
    // occlusion masks
43 jakw 133
    cv::Mat occlusion0Rect, occlusion1Rect;
134
    cv::subtract(frames0Rect[0], frames0Rect[1], occlusion0Rect);
245 jakw 135
    occlusion0Rect = (occlusion0Rect > 0.1) & (occlusion0Rect < 0.99);
43 jakw 136
    cv::subtract(frames1Rect[0], frames1Rect[1], occlusion1Rect);
245 jakw 137
    occlusion1Rect = (occlusion1Rect > 0.1) & (occlusion1Rect < 0.99);
47 jakw 138
 
139
    // erode occlusion masks
114 jakw 140
    cv::Mat strel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(2,2));
47 jakw 141
    cv::erode(occlusion0Rect, occlusion0Rect, strel);
142
    cv::erode(occlusion1Rect, occlusion1Rect, strel);
143
 
120 jakw 144
//    // correct for projector inversion error
145
//    cv::Mat W;
146
//    cv::add(frames0Rect[0], frames0Rect[1], W, cv::noArray(), CV_32F);
147
//    for(int i=2; i<N; i+=2){
148
//        cv::Mat S, E;
149
//        cv::add(frames0Rect[i], frames0Rect[i+1], S, cv::noArray(), CV_32F);
150
//        cv::subtract(W, S, E, cv::noArray(), CV_32F);
151
//        E *= 0.5;
152
//        cv::add(frames0Rect[i], E, frames0Rect[i], cv::noArray(), CV_16UC1);
153
//        cv::add(frames0Rect[i+1], E, frames0Rect[i+1], cv::noArray(), CV_16UC1);
154
//    }
155
 
133 jakw 156
//    // correct for texture modulation and ambient
157
//    cv::Mat A0 = frames0Rect[1];
158
//    cv::Mat M0 = frames0Rect[0]-frames0Rect[1];
159
//    cv::divide(256.0, M0, M0, CV_32F);
160
//    cv::Mat A1 = frames1Rect[1];
161
//    cv::Mat M1 = frames1Rect[0]-frames1Rect[1];
162
//    cv::divide(256.0, M1, M1, CV_32F);
120 jakw 163
 
133 jakw 164
//    for(int i=2; i<N; i++){
165
//        cv::multiply(frames0Rect[i]-A0, M0, frames0Rect[i], 1.0, CV_8UC1);
166
//        cv::multiply(frames1Rect[i]-A1, M1, frames1Rect[i], 1.0, CV_8UC1);
167
//    }
120 jakw 168
 
43 jakw 169
    // decode patterns
78 jakw 170
    cv::Mat code0Rect(frameRectRows, frameRectCols, CV_32S, cv::Scalar(0));
171
    cv::Mat code1Rect(frameRectRows, frameRectCols, CV_32S, cv::Scalar(0));
43 jakw 172
 
45 jakw 173
    // into gray code
167 jakw 174
    for(unsigned int i=0; i<Nbits; i++){
120 jakw 175
        cv::Mat temp, bit0, bit1;
176
 
177
        cv::compare(frames0Rect[i*2+2], frames0Rect[i*2+3], temp, cv::CMP_GT);
178
        temp.convertTo(bit0, CV_32S, 1.0/255.0);
179
        cv::add(code0Rect, bit0*twopowi(Nbits-i-1), code0Rect, cv::noArray(), CV_32S);
180
 
181
        cv::compare(frames1Rect[i*2+2], frames1Rect[i*2+3], temp, cv::CMP_GT);
182
        temp.convertTo(bit1, CV_32S, 1.0/255.0);
183
        cv::add(code1Rect, bit1*twopowi(Nbits-i-1), code1Rect, cv::noArray(), CV_32S);
43 jakw 184
    }
185
 
255 - 186
 
121 jakw 187
//cvtools::writeMat(code0Rect, "code0Rect.mat", "code0Rect");
188
//cvtools::writeMat(code1Rect, "code1Rect.mat", "code1Rect");
43 jakw 189
 
78 jakw 190
 
245 jakw 191
    #ifdef QT_DEBUG
236 jakw 192
        // convert to standard binary
193
        cv::Mat code0Binary(code0Rect.rows, code0Rect.cols, CV_32F);
194
        cv::Mat code1Binary(code1Rect.rows, code1Rect.cols, CV_32F);
195
        for(int r=0; r<frameRectRows; r++){
196
            for(int c=0; c<frameRectCols; c++){
197
                if(code0Rect.at<int>(r,c) != -1)
198
                    code0Binary.at<float>(r,c) = grayToBinary(code0Rect.at<int>(r,c));
199
                if(code1Rect.at<int>(r,c) != -1)
200
                    code1Binary.at<float>(r,c) = grayToBinary(code1Rect.at<int>(r,c));
201
            }
202
        }
45 jakw 203
 
236 jakw 204
        cvtools::writeMat(code0Binary, "code0Binary.mat", "code0Binary");
205
        cvtools::writeMat(code1Binary, "code1Binary.mat", "code1Binary");
206
    #endif
45 jakw 207
 
78 jakw 208
//    // threshold on vertical discontinuities (due to imperfect rectification)
209
//    cv::Mat edges0;
210
//    cv::Sobel(code0Binary, edges0, -1, 0, 1, 5);
211
//    occlusion0Rect = occlusion0Rect & (abs(edges0) < 50);
212
 
213
//    cv::Mat edges1;
214
//    cv::Sobel(code1Binary, edges1, -1, 0, 1, 5);
215
//    occlusion1Rect = occlusion1Rect & (abs(edges1) < 50);
216
 
217
 
218
    // set occluded pixels to -1
219
    for(int r=0; r<frameRectRows; r++){
220
        for(int c=0; c<frameRectCols; c++){
120 jakw 221
            if(occlusion0Rect.at<unsigned char>(r,c) == 0)
222
                code0Rect.at<int>(r,c) = -1;
223
            if(occlusion1Rect.at<unsigned char>(r,c) == 0)
224
                code1Rect.at<int>(r,c) = -1;
78 jakw 225
        }
226
    }
227
 
255 - 228
 
229
#ifdef QT_DEBUG
230
    cv::imwrite("code0Rect.png", code0Rect);
231
    cv::imwrite("code1Rect.png", code1Rect);
232
#endif
233
 
245 jakw 234
    #ifdef QT_DEBUG
236 jakw 235
        cvtools::writeMat(code0Rect, "code0Rect.mat", "code0Rect");
245 jakw 236
        cvtools::writeMat(code1Rect, "code1Rect.mat", "code1Rect");
236 jakw 237
    #endif
120 jakw 238
 
41 jakw 239
    // matching
236 jakw 240
    std::vector<cv::Vec2f> q0, q1;
43 jakw 241
    for(int row=0; row<frameRectRows; row++){
41 jakw 242
 
95 jakw 243
        // edge data structure containing [floor(column), labelLeft, labelRight, orderingRelation]
47 jakw 244
        std::vector<cv::Vec4i> edges0, edges1;
41 jakw 245
 
43 jakw 246
        // sorted, unique edges
42 jakw 247
        getEdgeLabels(code0Rect.row(row), Nbits, edges0);
248
        getEdgeLabels(code1Rect.row(row), Nbits, edges1);
41 jakw 249
 
47 jakw 250
        // match edges
251
        std::vector<cv::Vec4i> matchedEdges0, matchedEdges1;
167 jakw 252
        unsigned int i=0, j=0;
41 jakw 253
        while(i<edges0.size() && j<edges1.size()){
254
 
255
            if(edges0[i][3] == edges1[j][3]){
47 jakw 256
                matchedEdges0.push_back(edges0[i]);
257
                matchedEdges1.push_back(edges1[j]);
41 jakw 258
                i += 1;
259
                j += 1;
42 jakw 260
            } else if(edges0[i][3] < edges1[j][3]){
41 jakw 261
                i += 1;
42 jakw 262
            } else if(edges0[i][3] > edges1[j][3]){
41 jakw 263
                j += 1;
264
            }
265
        }
266
 
47 jakw 267
        // crude subpixel refinement
268
        // finds the intersection of linear interpolants in the positive/negative pattern
167 jakw 269
        for(unsigned int i=0; i<matchedEdges0.size(); i++){
41 jakw 270
 
47 jakw 271
            int level = Nbits - leastSignificantBitSet(matchedEdges0[i][1]^matchedEdges0[i][2]);
272
 
273
            // refine for camera 0
274
            float c0 = matchedEdges0[i][0];
275
            float c1 = c0+1;
276
 
245 jakw 277
            float pos0 = frames0Rect[2*level+2].at<float>(row, c0);
278
            float pos1 = frames0Rect[2*level+2].at<float>(row, c1);
279
            float neg0 = frames0Rect[2*level+3].at<float>(row, c0);
280
            float neg1 = frames0Rect[2*level+3].at<float>(row, c1);
47 jakw 281
 
282
            float col = c0 + (pos0 - neg0)/(neg1 - neg0 - pos1 + pos0);
236 jakw 283
            q0.push_back(cv::Point2f(col, row));
47 jakw 284
 
285
            // refine for camera 1
286
            c0 = matchedEdges1[i][0];
287
            c1 = c0+1;
288
 
245 jakw 289
            pos0 = frames1Rect[2*level+2].at<float>(row, c0);
290
            pos1 = frames1Rect[2*level+2].at<float>(row, c1);
291
            neg0 = frames1Rect[2*level+3].at<float>(row, c0);
292
            neg1 = frames1Rect[2*level+3].at<float>(row, c1);
47 jakw 293
 
294
            col = c0 + (pos0 - neg0)/(neg1 - neg0 - pos1 + pos0);
236 jakw 295
            q1.push_back(cv::Point2f(col, row));
47 jakw 296
 
297
        }
298
 
41 jakw 299
    }
300
 
236 jakw 301
    int nMatches = q0.size();
63 jakw 302
 
303
    if(nMatches < 1){
304
        Q.resize(0);
305
        color.resize(0);
306
 
307
        return;
308
    }
309
 
95 jakw 310
    // retrieve color information (at integer coordinates)
41 jakw 311
    color.resize(nMatches);
312
    for(int i=0; i<nMatches; i++){
313
 
245 jakw 314
        cv::Vec3f c0 = color0Rect.at<cv::Vec3f>(q0[i][1], q0[i][0]);
315
        cv::Vec3f c1 = color1Rect.at<cv::Vec3f>(q1[i][1], q1[i][0]);
41 jakw 316
 
44 jakw 317
        color[i] = 0.5*c0 + 0.5*c1;
41 jakw 318
    }
319
 
231 jakw 320
    // Triangulate by means of disparity projection
236 jakw 321
    Q.resize(q0.size());
231 jakw 322
    cv::Matx44f QRectx = cv::Matx44f(QRect);
323
    cv::Matx33f R0invx = cv::Matx33f(cv::Mat(R0.t()));
324
 
325
    #pragma omp parallel for
236 jakw 326
    for(unsigned int i=0; i<q0.size(); i++){
327
        float disparity = q0[i][0]-q1[i][0];
328
        cv::Vec4f Qih = QRectx*cv::Vec4f(q0[i][0], q0[i][1], disparity, 1.0);
231 jakw 329
        float winv = float(1.0)/Qih[3];
330
        Q[i] = R0invx * cv::Point3f(Qih[0]*winv, Qih[1]*winv, Qih[2]*winv);
331
    }
332
 
4 jakw 333
}