Subversion Repositories seema-scanner

Rev

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

Rev Author Line No. Line
103 jakw 1
#include "AlgorithmGrayCodeHorzVert.h"
95 jakw 2
#include <cmath>
96 jakw 3
#include <assert.h>
95 jakw 4
#include "cvtools.h"
5
 
6
#ifndef log2f
7
#define log2f(x) (log(x)/log(2.0))
8
#endif
9
 
10
//using namespace std;
11
 
12
/*
13
 * The purpose of this function is to convert an unsigned
14
 * binary number to reflected binary Gray code.
15
 *
16
 * The operator >> is shift right. The operator ^ is exclusive or.
17
 * Source: http://en.wikipedia.org/wiki/Gray_code
18
 */
19
static unsigned int binaryToGray(unsigned int num) {
20
    return (num >> 1) ^ num;
21
}
22
 
23
/*
24
 * From Wikipedia: http://en.wikipedia.org/wiki/Gray_code
25
 * The purpose of this function is to convert a reflected binary
26
 * Gray code number to a binary number.
27
 */
28
static unsigned int grayToBinary(unsigned int num){
29
    unsigned int mask;
30
    for(mask = num >> 1; mask != 0; mask = mask >> 1)
31
        num = num ^ mask;
32
    return num;
33
}
34
 
35
/*
36
 * Return the Nth bit of an unsigned integer number
37
 */
38
static bool getBit(int decimal, int N){
39
 
40
    return decimal & 1 << (N-1);
41
}
42
 
167 jakw 43
///*
44
// * Return the number of bits set in an integer
45
// */
46
//static int countBits(int n) {
47
//  unsigned int c; // c accumulates the total bits set in v
48
//  for (c = 0; n>0; c++)
49
//    n &= n - 1; // clear the least significant bit set
50
//  return c;
51
//}
95 jakw 52
 
53
/*
54
 * Return the position of the least significant bit that is set
55
 */
56
static int leastSignificantBitSet(int x){
57
  if(x == 0)
58
      return 0;
59
 
60
  int val = 1;
61
  while(x>>=1)
62
      val++;
63
 
64
  return val;
65
}
66
 
67
//static int get_bit(int decimal, int N){
68
 
69
//    // Shifting the 1 for N-1 bits
70
//    int constant = 1 << (N-1);
71
 
72
//    // If the bit is set, return 1
73
//    if( decimal & constant )
74
//        return 1;
75
//    else
76
//        return 0;
77
//}
78
 
79
static inline unsigned int powi(int num, unsigned int exponent){
80
 
81
    if(exponent == 0)
82
        return 1;
83
 
84
    float res = num;
85
    for(unsigned int i=0; i<exponent-1; i++)
86
        res *= num;
87
 
88
    return res;
89
}
90
 
91
static inline unsigned int twopowi(unsigned int exponent){
92
 
93
    return 1 << exponent;
94
}
95
 
96
// Algorithm
103 jakw 97
AlgorithmGrayCodeHorzVert::AlgorithmGrayCodeHorzVert(unsigned int _screenCols, unsigned int _screenRows) : Algorithm(_screenCols, _screenRows){
95 jakw 98
 
99
    NbitsHorz = ceilf(log2f((float)screenCols));
100
    NbitsVert =  ceilf(log2f((float)screenRows));
101
    N = 2 + (NbitsHorz+NbitsVert)*2;
102
 
103
    // all on pattern
104
    cv::Mat allOn(1, screenCols, CV_8UC3, cv::Scalar::all(255));
105
    patterns.push_back(allOn);
106
 
107
    // all off pattern
108
    cv::Mat allOff(1, screenCols, CV_8UC3, cv::Scalar::all(0));
109
    patterns.push_back(allOff);
110
 
111
 
112
    // horizontally encoding patterns
113
    for(unsigned int p=0; p<NbitsHorz; p++){
114
        cv::Mat pattern(1, screenCols, CV_8UC3);
115
        cv::Mat patternInv(1, screenCols, CV_8UC3);
116
 
117
        for(unsigned int j=0; j<screenCols; j++){
118
 
119
            unsigned int jGray = binaryToGray(j);
120
            // Amplitude of channels
96 jakw 121
            int bit = (int)getBit(jGray, NbitsHorz-p);
95 jakw 122
            pattern.at<cv::Vec3b>(0,j) = cv::Vec3b(255.0*bit,255.0*bit,255.0*bit);
123
            int invBit = bit^1;
124
            patternInv.at<cv::Vec3b>(0,j) = cv::Vec3b(255.0*invBit,255.0*invBit,255.0*invBit);
125
        }
126
        patterns.push_back(pattern);
127
        patterns.push_back(patternInv);
128
    }
129
 
130
    // vertical encoding patterns
131
    for(unsigned int p=0; p<NbitsVert; p++){
132
        cv::Mat pattern(screenRows, 1, CV_8UC3);
133
        cv::Mat patternInv(screenRows, 1, CV_8UC3);
134
 
135
        for(unsigned int j=0; j<screenRows; j++){
136
 
137
            unsigned int jGray = binaryToGray(j);
138
            // Amplitude of channels
96 jakw 139
            int bit = (int)getBit(jGray, NbitsVert-p);
95 jakw 140
            pattern.at<cv::Vec3b>(j,0) = cv::Vec3b(255.0*bit,255.0*bit,255.0*bit);
141
            int invBit = bit^1;
142
            patternInv.at<cv::Vec3b>(j,0) = cv::Vec3b(255.0*invBit,255.0*invBit,255.0*invBit);
143
        }
144
        patterns.push_back(pattern);
145
        patterns.push_back(patternInv);
146
    }
147
 
148
}
149
 
103 jakw 150
cv::Mat AlgorithmGrayCodeHorzVert::getEncodingPattern(unsigned int depth){
95 jakw 151
    return patterns[depth];
152
}
153
 
154
 
107 jakw 155
typedef struct intersection{
156
    unsigned int row;
157
    unsigned int col;
109 jakw 158
    // 64 bit integer (long long)
107 jakw 159
    unsigned long id;
108 jakw 160
    intersection() : row(0), col(0), id(0){}
161
    intersection(unsigned int _row, unsigned int _col, unsigned long long _id) :
162
        row(_row), col(_col), id(_id){}
107 jakw 163
} intersection;
95 jakw 164
 
165
 
107 jakw 166
static bool sortingLarger(intersection i,intersection j){ return (i.id<j.id);}
167
static bool sortingEqual(intersection i,intersection j){ return (i.id==j.id);}
168
 
108 jakw 169
static void getIntersectionLabels(const cv::Mat& codeHorz, const cv::Mat& codeVert, const int NbitsHorz, const int NbitsVert, std::vector<intersection>& intersections){
107 jakw 170
 
96 jakw 171
    int nRows = codeHorz.rows;
172
    int nCols = codeHorz.cols;
95 jakw 173
 
96 jakw 174
    int labelHorz;
175
    int labelVert;
176
    int labelHorzRight;
177
    int labelVertBelow;
95 jakw 178
 
96 jakw 179
    // collect intersections
109 jakw 180
    for(int row=0; row<nRows-1; row++){
181
        for(int col=0; col<nCols-1; col++){
95 jakw 182
 
96 jakw 183
            labelHorz = codeHorz.at<int>(row, col);
184
            labelHorzRight = codeHorz.at<int>(row, col+1);
185
 
186
            labelVert = codeVert.at<int>(row, col);
187
            labelVertBelow = codeVert.at<int>(row+1, col);
188
 
189
            // labels need to be non-background, and differ in exactly one bit
190
            if(labelHorz != -1 && labelHorzRight != -1 &&
122 jakw 191
               (grayToBinary(labelHorzRight) == grayToBinary(labelHorz)+1) &&
96 jakw 192
               labelVert != -1 && labelVertBelow != -1 &&
122 jakw 193
               (grayToBinary(labelVertBelow) == grayToBinary(labelVert)+1)){
96 jakw 194
 
108 jakw 195
                // shift together labels to form unique intersection id
109 jakw 196
                unsigned long id = ((ulong)labelHorz << (NbitsHorz+2*NbitsVert)) + ((ulong)labelHorzRight << (2*NbitsVert)) +
197
                                   ((ulong)labelVert << NbitsVert) + (ulong)labelVertBelow;
108 jakw 198
 
199
                // store intersection
200
                intersections.push_back(intersection(row, col, id));
96 jakw 201
            }
95 jakw 202
        }
203
    }
204
    // sort
96 jakw 205
    std::sort(intersections.begin(), intersections.end(), sortingLarger);
95 jakw 206
 
207
    // remove duplicates
107 jakw 208
    std::vector<intersection>::iterator it;
96 jakw 209
    it = std::unique(intersections.begin(), intersections.end(), sortingEqual);
210
    intersections.resize(std::distance(intersections.begin(),it));
95 jakw 211
}
212
 
108 jakw 213
static void getSubpixelCoordinates(const std::vector<intersection>& matches, const std::vector<cv::Mat>& frames, const int NbitsHorz, const int NbitsVert, std::vector<cv::Point2f> &q){
214
 
215
    int nMatches = matches.size();
216
    q.resize(nMatches);
217
 
218
    // subpixel refinement finds the intersection of linear interpolants in the positive/negative pattern
219
    for(int i=0; i<nMatches; i++){
220
 
221
        // shift the labels back out from id
109 jakw 222
        int labelHorz = (matches[i].id >> (NbitsHorz+2*NbitsVert)) & ((1 << NbitsHorz) - 1);
223
        int labelHorzRight = (matches[i].id >> (2*NbitsVert)) & ((1 << NbitsHorz) - 1);
224
        int labelVert = (matches[i].id >> NbitsVert) & ((1 << NbitsVert) - 1);
225
        int labelVertBelow = matches[i].id  & ((1 << NbitsVert) - 1);
108 jakw 226
 
109 jakw 227
//        std::cout << "id: " << matches[i].id << std::endl;
228
//        std::cout << "labelHorz: " << labelHorz << std::endl;
229
//        std::cout << "labelHorzRight: " << labelHorzRight << std::endl;
230
//        std::cout << "labelVert: " << labelVert << std::endl;
231
//        std::cout << "labelVertBelow: " << labelVertBelow << std::endl;
232
 
108 jakw 233
        // determine the levels at which the edges exists
234
        int levelHorz = NbitsHorz - leastSignificantBitSet(labelHorz^labelHorzRight);
235
        int levelVert = NbitsVert - leastSignificantBitSet(labelVert^labelVertBelow);
236
 
237
        // interpolate horizontal coordinate
238
        float row = matches[i].row;
239
        float col = matches[i].col;
240
        float colRight = col+1;
241
 
121 jakw 242
        float posHorz = frames[2*levelHorz+2].at<unsigned char>(row, col);
243
        float negHorz = frames[2*levelHorz+3].at<unsigned char>(row, col);
244
        float posHorzRight = frames[2*levelHorz+2].at<unsigned char>(row, colRight);
245
        float negHorzRight = frames[2*levelHorz+3].at<unsigned char>(row, colRight);
108 jakw 246
 
247
        float x = col + (posHorz - negHorz)/(negHorzRight - negHorz - posHorzRight + posHorz);
248
 
249
        // interpolate vertical coordinate
250
        float rowBelow = row+1;
251
 
121 jakw 252
        float posVert = frames[2*NbitsHorz+2*levelVert+2].at<unsigned char>(row, col);
253
        float negVert = frames[2*NbitsHorz+2*levelVert+3].at<unsigned char>(row, col);
254
        float posVertBelow = frames[2*NbitsHorz+2*levelVert+2].at<unsigned char>(rowBelow, col);
255
        float negVertBelow = frames[2*NbitsHorz+2*levelVert+3].at<unsigned char>(rowBelow, col);
108 jakw 256
 
257
        float y = row + (posVert - negVert)/(negVertBelow - negVert - posVertBelow + posVert);
258
 
259
        // write into return vector
109 jakw 260
        q[i] = cv::Point2f(x, y);
108 jakw 261
 
262
    }
263
}
264
 
167 jakw 265
//static cv::Vec3b getColorSubpix(const cv::Mat& img, cv::Point2f pt){
266
//    assert(!img.empty());
267
//    assert(img.channels() == 3);
95 jakw 268
 
167 jakw 269
//    int x = (int)pt.x;
270
//    int y = (int)pt.y;
95 jakw 271
 
167 jakw 272
//    int x0 = cv::borderInterpolate(x,   img.cols, cv::BORDER_REFLECT_101);
273
//    int x1 = cv::borderInterpolate(x+1, img.cols, cv::BORDER_REFLECT_101);
274
//    int y0 = cv::borderInterpolate(y,   img.rows, cv::BORDER_REFLECT_101);
275
//    int y1 = cv::borderInterpolate(y+1, img.rows, cv::BORDER_REFLECT_101);
95 jakw 276
 
167 jakw 277
//    float a = pt.x - (float)x;
278
//    float c = pt.y - (float)y;
95 jakw 279
 
167 jakw 280
//    uchar b = (uchar)cvRound((img.at<cv::Vec3b>(y0, x0)[0] * (1.f - a) + img.at<cv::Vec3b>(y0, x1)[0] * a) * (1.f - c)
281
//                           + (img.at<cv::Vec3b>(y1, x0)[0] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[0] * a) * c);
282
//    uchar g = (uchar)cvRound((img.at<cv::Vec3b>(y0, x0)[1] * (1.f - a) + img.at<cv::Vec3b>(y0, x1)[1] * a) * (1.f - c)
283
//                           + (img.at<cv::Vec3b>(y1, x0)[1] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[1] * a) * c);
284
//    uchar r = (uchar)cvRound((img.at<cv::Vec3b>(y0, x0)[2] * (1.f - a) + img.at<cv::Vec3b>(y0, x1)[2] * a) * (1.f - c)
285
//                           + (img.at<cv::Vec3b>(y1, x0)[2] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[2] * a) * c);
95 jakw 286
 
167 jakw 287
//    return cv::Vec3b(b, g, r);
288
//}
95 jakw 289
 
103 jakw 290
void AlgorithmGrayCodeHorzVert::get3DPoints(SMCalibrationParameters calibration, const std::vector<cv::Mat>& frames0, const std::vector<cv::Mat>& frames1, std::vector<cv::Point3f>& Q, std::vector<cv::Vec3b>& color){
95 jakw 291
 
292
    assert(frames0.size() == N);
293
    assert(frames1.size() == N);
294
 
295
    int frameRows = frames0[0].rows;
296
    int frameCols = frames0[0].cols;
297
 
298
    // gray-scale
299
    std::vector<cv::Mat> frames0Gray(N);
300
    std::vector<cv::Mat> frames1Gray(N);
167 jakw 301
    for(unsigned int i=0; i<N; i++){
113 jakw 302
        cv::cvtColor(frames0[i], frames0Gray[i], CV_BayerBG2GRAY);
303
        cv::cvtColor(frames1[i], frames1Gray[i], CV_BayerBG2GRAY);
95 jakw 304
    }
305
 
306
    // colors
113 jakw 307
    cv::Mat color0;
121 jakw 308
//    frames0[0].convertTo(color0, CV_8UC3, 1.0/256.0);
309
    cv::cvtColor(frames0[0], color0, CV_BayerBG2RGB);
113 jakw 310
    cv::Mat color1;
121 jakw 311
//    frames1[0].convertTo(color1, CV_8UC3, 1.0/256.0);
312
    cv::cvtColor(frames1[0], color1, CV_BayerBG2RGB);
95 jakw 313
 
314
    // occlusion masks
315
    cv::Mat occlusion0, occlusion1;
120 jakw 316
    cv::subtract(frames0[0], frames0[1], occlusion0);
121 jakw 317
    occlusion0 = (occlusion0 > 20) & (occlusion0 < 250);
120 jakw 318
    cv::subtract(frames1[0], frames1[1], occlusion1);
121 jakw 319
    occlusion1 = (occlusion1 > 20) & (occlusion1 < 250);
95 jakw 320
 
321
    // erode occlusion masks
322
    cv::Mat strel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3,3));
323
    cv::erode(occlusion0, occlusion0, strel);
324
    cv::erode(occlusion1, occlusion1, strel);
325
 
326
//cvtools::writeMat(occlusion0, "occlusion0.mat", "occlusion0");
327
//cvtools::writeMat(occlusion1, "occlusion1.mat", "occlusion1");
328
 
329
    // decode patterns
330
    cv::Mat code0Horz(frameRows, frameCols, CV_32S, cv::Scalar(0));
331
    cv::Mat code1Horz(frameRows, frameCols, CV_32S, cv::Scalar(0));
332
    cv::Mat code0Vert(frameRows, frameCols, CV_32S, cv::Scalar(0));
333
    cv::Mat code1Vert(frameRows, frameCols, CV_32S, cv::Scalar(0));
334
 
335
    // horizontal codes into gray code
167 jakw 336
    for(unsigned int i=0; i<NbitsHorz; i++){
95 jakw 337
        cv::Mat bit0;
120 jakw 338
        cv::compare(frames0Gray[i*2+2], frames0Gray[i*2+3], bit0, cv::CMP_GT);
95 jakw 339
        bit0.convertTo(bit0, CV_32S, 1.0/255.0);
96 jakw 340
        cv::add(code0Horz, bit0*twopowi(NbitsHorz-i-1), code0Horz, cv::Mat(), CV_32S);
95 jakw 341
 
342
        cv::Mat bit1;
120 jakw 343
        cv::compare(frames1Gray[i*2+2], frames1Gray[i*2+3], bit1, cv::CMP_GT);
95 jakw 344
        bit1.convertTo(bit1, CV_32S, 1.0/255.0);
96 jakw 345
        cv::add(code1Horz, bit1*twopowi(NbitsHorz-i-1), code1Horz, cv::Mat(), CV_32S);
95 jakw 346
    }
347
 
348
    // vertical codes into gray code
167 jakw 349
    for(unsigned int i=0; i<NbitsVert; i++){
95 jakw 350
        cv::Mat bit0;
120 jakw 351
        cv::compare(frames0Gray[i*2+2*NbitsHorz+2], frames0Gray[i*2+2*NbitsHorz+3], bit0, cv::CMP_GT);
95 jakw 352
        bit0.convertTo(bit0, CV_32S, 1.0/255.0);
96 jakw 353
        cv::add(code0Vert, bit0*twopowi(NbitsVert-i-1), code0Vert, cv::Mat(), CV_32S);
95 jakw 354
 
355
        cv::Mat bit1;
120 jakw 356
        cv::compare(frames1Gray[i*2+2*NbitsHorz+2], frames1Gray[i*2+2*NbitsHorz+3], bit1, cv::CMP_GT);
95 jakw 357
        bit1.convertTo(bit1, CV_32S, 1.0/255.0);
96 jakw 358
        cv::add(code1Vert, bit1*twopowi(NbitsVert-i-1), code1Vert, cv::Mat(), CV_32S);
95 jakw 359
    }
360
 
361
    // set occluded pixels to -1
362
    for(int r=0; r<frameRows; r++){
363
        for(int c=0; c<frameCols; c++){
364
            if(occlusion0.at<char>(r,c) == 0){
109 jakw 365
                code0Horz.at<int>(r,c) = -1;
366
                code0Vert.at<int>(r,c) = -1;
95 jakw 367
            }
368
            if(occlusion1.at<char>(r,c) == 0){
109 jakw 369
                code1Horz.at<int>(r,c) = -1;
370
                code1Vert.at<int>(r,c) = -1;
95 jakw 371
            }
372
        }
373
    }
374
 
109 jakw 375
//    cvtools::writeMat(code0Horz, "code0Horz.mat", "code0Horz");
376
//    cvtools::writeMat(code1Horz, "code1Horz.mat", "code1Horz");
377
//    cvtools::writeMat(code0Vert, "code0Vert.mat", "code0Vert");
378
//    cvtools::writeMat(code1Vert, "code1Vert.mat", "code1Vert");
379
 
380
    // get intersections
107 jakw 381
    std::vector<intersection> intersections0, intersections1;
96 jakw 382
    getIntersectionLabels(code0Horz, code0Vert, NbitsHorz, NbitsVert, intersections0);
383
    getIntersectionLabels(code1Horz, code1Vert, NbitsHorz, NbitsVert, intersections1);
95 jakw 384
 
96 jakw 385
    // match intersections
107 jakw 386
    std::vector<intersection> matches0, matches1;
167 jakw 387
    unsigned int i=0, j=0;
95 jakw 388
 
96 jakw 389
    while(i<intersections0.size() && j<intersections1.size()){
107 jakw 390
        if(intersections0[i].id == intersections1[j].id){
96 jakw 391
            matches0.push_back(intersections0[i]);
392
            matches1.push_back(intersections1[j]);
393
            i += 1;
394
            j += 1;
107 jakw 395
        } else if(intersections0[i].id < intersections1[j].id){
96 jakw 396
            i += 1;
107 jakw 397
        } else if(intersections0[i].id > intersections1[j].id){
96 jakw 398
            j += 1;
399
        }
400
    }
95 jakw 401
 
98 jakw 402
    int nMatches = matches0.size();
95 jakw 403
 
98 jakw 404
    if(nMatches < 1){
405
        Q.resize(0);
406
        color.resize(0);
407
 
408
        return;
409
    }
410
 
108 jakw 411
    std::vector<cv::Point2f> q0(nMatches), q1(nMatches);
98 jakw 412
 
107 jakw 413
//    for(int i=0; i<nMatches; i++){
109 jakw 414
//        q0[i] = cv::Point2f(matches0[i].col, matches0[i].row);
415
//        q1[i] = cv::Point2f(matches1[i].col, matches1[i].row);
107 jakw 416
//    }
98 jakw 417
 
108 jakw 418
    // subpixel refinement
109 jakw 419
    getSubpixelCoordinates(matches0, frames0Gray, NbitsHorz, NbitsVert, q0);
420
    getSubpixelCoordinates(matches1, frames1Gray, NbitsHorz, NbitsVert, q1);
95 jakw 421
 
108 jakw 422
    // retrieve color information (at subpixel coordinates)
96 jakw 423
    color.resize(nMatches);
424
    for(int i=0; i<nMatches; i++){
109 jakw 425
        cv::Vec3b c0 = color0.at<cv::Vec3b>(std::floor(q0[i].y), std::floor(q0[i].x));
426
        cv::Vec3b c1 = color1.at<cv::Vec3b>(std::floor(q1[i].y), std::floor(q1[i].x));
427
//        cv::Vec3b c0 = getColorSubpix(color0, q0[i]);
428
//        cv::Vec3b c1 = getColorSubpix(color1, q1[i]);
95 jakw 429
 
96 jakw 430
        color[i] = 0.5*c0 + 0.5*c1;
431
    }
95 jakw 432
 
114 jakw 433
    //cv::correctMatches(calibration.F, q0, q1, q0, q1);
120 jakw 434
    // correct for lens distortion
114 jakw 435
    cv::undistortPoints(q0, q0, calibration.K0, calibration.k0, cv::noArray(), calibration.K0);
436
    cv::undistortPoints(q1, q1, calibration.K1, calibration.k1, cv::noArray(), calibration.K1);
437
    cv::correctMatches(calibration.F, q0, q1, q0, q1);
438
 
96 jakw 439
    // triangulate points
440
    cv::Mat P0(3, 4, CV_32F, cv::Scalar(0.0));
441
    cv::Mat(calibration.K0).copyTo(P0.colRange(0, 3));
95 jakw 442
 
96 jakw 443
    cv::Mat P1(3, 4, CV_32F), temp(3,4,CV_32F);
444
    cv::Mat(calibration.R1).copyTo(temp(cv::Range(0,3), cv::Range(0,3)));
445
    cv::Mat(calibration.T1).copyTo(temp(cv::Range(0,3), cv::Range(3,4)));
446
    P1 = cv::Mat(calibration.K1) * temp;
95 jakw 447
 
96 jakw 448
    cv::Mat QMatHomogenous, QMat;
449
    cv::triangulatePoints(P0, P1, q0, q1, QMatHomogenous);
95 jakw 450
 
96 jakw 451
    cvtools::convertMatFromHomogeneous(QMatHomogenous, QMat);
452
    cvtools::matToPoints3f(QMat, Q);
95 jakw 453
 
454
}