Subversion Repositories seema-scanner

Rev

Rev 107 | Rev 109 | 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
 
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
}
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;
158
    unsigned long id;
108 jakw 159
    intersection() : row(0), col(0), id(0){}
160
    intersection(unsigned int _row, unsigned int _col, unsigned long long _id) :
161
        row(_row), col(_col), id(_id){}
107 jakw 162
} intersection;
95 jakw 163
 
164
 
107 jakw 165
static bool sortingLarger(intersection i,intersection j){ return (i.id<j.id);}
166
static bool sortingEqual(intersection i,intersection j){ return (i.id==j.id);}
167
 
108 jakw 168
static void getIntersectionLabels(const cv::Mat& codeHorz, const cv::Mat& codeVert, const int NbitsHorz, const int NbitsVert, std::vector<intersection>& intersections){
107 jakw 169
 
96 jakw 170
    int nRows = codeHorz.rows;
171
    int nCols = codeHorz.cols;
95 jakw 172
 
96 jakw 173
    int labelHorz;
174
    int labelVert;
175
    int labelHorzRight;
176
    int labelVertBelow;
95 jakw 177
 
96 jakw 178
    // collect intersections
179
    for(int row=0; row<nRows+1; row++){
180
        for(int col=0; col<nCols+1; col++){
95 jakw 181
 
96 jakw 182
            labelHorz = codeHorz.at<int>(row, col);
183
            labelHorzRight = codeHorz.at<int>(row, col+1);
184
 
185
            labelVert = codeVert.at<int>(row, col);
186
            labelVertBelow = codeVert.at<int>(row+1, col);
187
 
188
            // labels need to be non-background, and differ in exactly one bit
189
            if(labelHorz != -1 && labelHorzRight != -1 &&
190
               countBits(labelHorz^labelHorzRight) == 1 &&
191
               labelVert != -1 && labelVertBelow != -1 &&
192
               countBits(labelVert^labelVertBelow) == 1){
193
 
108 jakw 194
                // shift together labels to form unique intersection id
195
                unsigned long id = (labelHorz << NbitsHorz+2*NbitsVert) + (labelHorzRight << 2*NbitsVert) +
196
                                   (labelVert << NbitsVert) + labelVertBelow;
197
 
198
                // store intersection
199
                intersections.push_back(intersection(row, col, id));
96 jakw 200
            }
95 jakw 201
        }
202
    }
203
    // sort
96 jakw 204
    std::sort(intersections.begin(), intersections.end(), sortingLarger);
95 jakw 205
 
206
    // remove duplicates
107 jakw 207
    std::vector<intersection>::iterator it;
96 jakw 208
    it = std::unique(intersections.begin(), intersections.end(), sortingEqual);
209
    intersections.resize(std::distance(intersections.begin(),it));
95 jakw 210
}
211
 
108 jakw 212
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){
213
 
214
    int nMatches = matches.size();
215
    q.resize(nMatches);
216
 
217
    // subpixel refinement finds the intersection of linear interpolants in the positive/negative pattern
218
    for(int i=0; i<nMatches; i++){
219
 
220
        // shift the labels back out from id
221
        int labelHorz = (matches[i].id >> NbitsHorz+2*NbitsVert) & (1 << (NbitsHorz+1) - 1);
222
        int labelHorzRight = (matches[i].id >> 2*NbitsVert) & (1 << (NbitsHorz+1) - 1);
223
        int labelVert = (matches[i].id >> NbitsVert) & (1 << (NbitsVert+1) - 1);
224
        int labelVertBelow = matches[i].id  & (1 << (NbitsVert+1) - 1);
225
 
226
        // determine the levels at which the edges exists
227
        int levelHorz = NbitsHorz - leastSignificantBitSet(labelHorz^labelHorzRight);
228
        int levelVert = NbitsVert - leastSignificantBitSet(labelVert^labelVertBelow);
229
 
230
        // interpolate horizontal coordinate
231
        float row = matches[i].row;
232
        float col = matches[i].col;
233
        float colRight = col+1;
234
 
235
        float posHorz = frames0[2*levelHorz+2].at<char>(row, col);
236
        float negHorz = frames0[2*levelHorz+3].at<char>(row, col);
237
        float posHorzRight = frames0[2*levelHorz+2].at<char>(row, colRight);
238
        float negHorzRight = frames0[2*levelHorz+3].at<char>(row, colRight);
239
 
240
        float x = col + (posHorz - negHorz)/(negHorzRight - negHorz - posHorzRight + posHorz);
241
 
242
        // interpolate vertical coordinate
243
        float rowBelow = row+1;
244
 
245
        float posVert = frames[2*NbitsHorz+2*levelVert+2].at<char>(rowBelow, col);
246
        float negVert = frames[2*NbitsHorz+2*levelVert+3].at<char>(rowBelow, col);
247
        float posVertBelow = frames[2*NbitsHorz+2*levelVert+2].at<char>(rowBelow, col);
248
        float negVertBelow = frames[2*NbitsHorz+2*levelVert+3].at<char>(rowBelow, col);
249
 
250
        float y = row + (posVert - negVert)/(negVertBelow - negVert - posVertBelow + posVert);
251
 
252
        // write into return vector
253
        q[i] = cv::Vec2f(x, y);
254
 
255
    }
256
}
257
 
98 jakw 258
static cv::Vec3b getColorSubpix(const cv::Mat& img, cv::Point2f pt){
95 jakw 259
    assert(!img.empty());
260
    assert(img.channels() == 3);
261
 
262
    int x = (int)pt.x;
263
    int y = (int)pt.y;
264
 
265
    int x0 = cv::borderInterpolate(x,   img.cols, cv::BORDER_REFLECT_101);
266
    int x1 = cv::borderInterpolate(x+1, img.cols, cv::BORDER_REFLECT_101);
267
    int y0 = cv::borderInterpolate(y,   img.rows, cv::BORDER_REFLECT_101);
268
    int y1 = cv::borderInterpolate(y+1, img.rows, cv::BORDER_REFLECT_101);
269
 
270
    float a = pt.x - (float)x;
271
    float c = pt.y - (float)y;
272
 
273
    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)
274
                           + (img.at<cv::Vec3b>(y1, x0)[0] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[0] * a) * c);
275
    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)
276
                           + (img.at<cv::Vec3b>(y1, x0)[1] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[1] * a) * c);
277
    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)
278
                           + (img.at<cv::Vec3b>(y1, x0)[2] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[2] * a) * c);
279
 
280
    return cv::Vec3b(b, g, r);
281
}
282
 
103 jakw 283
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 284
 
285
    assert(frames0.size() == N);
286
    assert(frames1.size() == N);
287
 
288
    int frameRows = frames0[0].rows;
289
    int frameCols = frames0[0].cols;
290
 
291
    // gray-scale
292
    std::vector<cv::Mat> frames0Gray(N);
293
    std::vector<cv::Mat> frames1Gray(N);
294
    for(int i=0; i<N; i++){
98 jakw 295
        cv::cvtColor(frames0[i], frames0Gray[i], CV_RGB2GRAY);
296
        cv::cvtColor(frames1[i], frames1Gray[i], CV_RGB2GRAY);
95 jakw 297
    }
298
 
299
    // colors
300
    cv::Mat color0 = frames0[0];
301
    cv::Mat color1 = frames1[0];
302
 
303
    // occlusion masks
304
    cv::Mat occlusion0, occlusion1;
305
    cv::subtract(frames0Gray[0], frames0Gray[1], occlusion0);
306
    occlusion0 = occlusion0 > 25;
307
    cv::subtract(frames1Gray[0], frames1Gray[1], occlusion1);
308
    occlusion1 = occlusion1 > 25;
309
 
310
    // erode occlusion masks
311
    cv::Mat strel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3,3));
312
    cv::erode(occlusion0, occlusion0, strel);
313
    cv::erode(occlusion1, occlusion1, strel);
314
 
315
//cvtools::writeMat(occlusion0, "occlusion0.mat", "occlusion0");
316
//cvtools::writeMat(occlusion1, "occlusion1.mat", "occlusion1");
317
 
318
    // decode patterns
319
    cv::Mat code0Horz(frameRows, frameCols, CV_32S, cv::Scalar(0));
320
    cv::Mat code1Horz(frameRows, frameCols, CV_32S, cv::Scalar(0));
321
    cv::Mat code0Vert(frameRows, frameCols, CV_32S, cv::Scalar(0));
322
    cv::Mat code1Vert(frameRows, frameCols, CV_32S, cv::Scalar(0));
323
 
324
    // horizontal codes into gray code
325
    for(int i=0; i<NbitsHorz; i++){
326
        cv::Mat bit0;
327
        cv::subtract(frames0Gray[i*2+2], frames0Gray[i*2+3], bit0);
328
        bit0 = bit0 > 0;
329
        bit0.convertTo(bit0, CV_32S, 1.0/255.0);
96 jakw 330
        cv::add(code0Horz, bit0*twopowi(NbitsHorz-i-1), code0Horz, cv::Mat(), CV_32S);
95 jakw 331
 
332
        cv::Mat bit1;
333
        cv::subtract(frames1Gray[i*2+2], frames1Gray[i*2+3], bit1);
334
        bit1 = bit1 > 0;
335
        bit1.convertTo(bit1, CV_32S, 1.0/255.0);
96 jakw 336
        cv::add(code1Horz, bit1*twopowi(NbitsHorz-i-1), code1Horz, cv::Mat(), CV_32S);
95 jakw 337
    }
338
 
339
    // vertical codes into gray code
340
    for(int i=0; i<NbitsVert; i++){
341
        cv::Mat bit0;
342
        cv::subtract(frames0Gray[i*2+NbitsHorz+2], frames0Gray[i*2+NbitsHorz+3], bit0);
343
        bit0 = bit0 > 0;
344
        bit0.convertTo(bit0, CV_32S, 1.0/255.0);
96 jakw 345
        cv::add(code0Vert, bit0*twopowi(NbitsVert-i-1), code0Vert, cv::Mat(), CV_32S);
95 jakw 346
 
347
        cv::Mat bit1;
348
        cv::subtract(frames1Gray[i*2+NbitsHorz+2], frames1Gray[i*2+NbitsHorz+3], bit1);
349
        bit1 = bit1 > 0;
350
        bit1.convertTo(bit1, CV_32S, 1.0/255.0);
96 jakw 351
        cv::add(code1Vert, bit1*twopowi(NbitsVert-i-1), code1Vert, cv::Mat(), CV_32S);
95 jakw 352
    }
353
 
354
//cvtools::writeMat(code0Horz, "code0Horz.mat", "code0Horz");
355
//cvtools::writeMat(code1Horz, "code1Horz.mat", "code1Horz");
356
//cvtools::writeMat(code0Vert, "code0Vert.mat", "code0Vert");
357
//cvtools::writeMat(code1Vert, "code1Vert.mat", "code1Vert");
358
 
359
    // set occluded pixels to -1
360
    for(int r=0; r<frameRows; r++){
361
        for(int c=0; c<frameCols; c++){
362
            if(occlusion0.at<char>(r,c) == 0){
363
                code0Horz.at<float>(r,c) = -1;
364
                code0Vert.at<float>(r,c) = -1;
365
            }
366
            if(occlusion1.at<char>(r,c) == 0){
367
                code1Horz.at<float>(r,c) = -1;
368
                code1Vert.at<float>(r,c) = -1;
369
            }
370
        }
371
    }
372
 
96 jakw 373
    // matching
107 jakw 374
    std::vector<intersection> intersections0, intersections1;
95 jakw 375
 
107 jakw 376
    // intersection data structure containing [floor(row), floor(column), id]
96 jakw 377
    getIntersectionLabels(code0Horz, code0Vert, NbitsHorz, NbitsVert, intersections0);
378
    getIntersectionLabels(code1Horz, code1Vert, NbitsHorz, NbitsVert, intersections1);
95 jakw 379
 
96 jakw 380
    // match intersections
107 jakw 381
    std::vector<intersection> matches0, matches1;
96 jakw 382
    int i=0, j=0;
95 jakw 383
 
96 jakw 384
    while(i<intersections0.size() && j<intersections1.size()){
107 jakw 385
        if(intersections0[i].id == intersections1[j].id){
96 jakw 386
            matches0.push_back(intersections0[i]);
387
            matches1.push_back(intersections1[j]);
388
            i += 1;
389
            j += 1;
107 jakw 390
        } else if(intersections0[i].id < intersections1[j].id){
96 jakw 391
            i += 1;
107 jakw 392
        } else if(intersections0[i].id > intersections1[j].id){
96 jakw 393
            j += 1;
394
        }
395
    }
95 jakw 396
 
98 jakw 397
    int nMatches = matches0.size();
95 jakw 398
 
98 jakw 399
    if(nMatches < 1){
400
        Q.resize(0);
401
        color.resize(0);
402
 
403
        return;
404
    }
405
 
108 jakw 406
    std::vector<cv::Point2f> q0(nMatches), q1(nMatches);
98 jakw 407
 
107 jakw 408
//    for(int i=0; i<nMatches; i++){
409
//        q0[i] = cv::Vec2f(matches0[i].col, matches0[i].row);
410
//        q1[i] = cv::Vec2f(matches1[i].col, matches1[i].row);
411
//    }
98 jakw 412
 
108 jakw 413
    // subpixel refinement
414
    getSubpixelCoordinates(matches0, frames0, NbitsHorz, NbitsVert,q0);
415
    getSubpixelCoordinates(matches1, frames1, NbitsHorz, NbitsVert,q1);
95 jakw 416
 
417
 
108 jakw 418
    // retrieve color information (at subpixel coordinates)
96 jakw 419
    color.resize(nMatches);
420
    for(int i=0; i<nMatches; i++){
95 jakw 421
 
98 jakw 422
//        cv::Vec3b c0 = color0.at<cv::Vec3b>(q0[i][1], q0[i][0]);
423
//        cv::Vec3b c1 = color1.at<cv::Vec3b>(q1[i][1], q1[i][0]);
424
        cv::Vec3b c0 = getColorSubpix(color0, q0[i]);
425
        cv::Vec3b c1 = getColorSubpix(color1, q1[i]);
95 jakw 426
 
96 jakw 427
        color[i] = 0.5*c0 + 0.5*c1;
428
    }
95 jakw 429
 
96 jakw 430
    // triangulate points
431
    cv::Mat P0(3, 4, CV_32F, cv::Scalar(0.0));
432
    cv::Mat(calibration.K0).copyTo(P0.colRange(0, 3));
95 jakw 433
 
96 jakw 434
    cv::Mat P1(3, 4, CV_32F), temp(3,4,CV_32F);
435
    cv::Mat(calibration.R1).copyTo(temp(cv::Range(0,3), cv::Range(0,3)));
436
    cv::Mat(calibration.T1).copyTo(temp(cv::Range(0,3), cv::Range(3,4)));
437
    P1 = cv::Mat(calibration.K1) * temp;
95 jakw 438
 
108 jakw 439
    //cv::correctMatches(calibration.F, q0, q1, q0, q1);
95 jakw 440
 
96 jakw 441
    cv::Mat QMatHomogenous, QMat;
442
    cv::triangulatePoints(P0, P1, q0, q1, QMatHomogenous);
95 jakw 443
 
96 jakw 444
    cvtools::convertMatFromHomogeneous(QMatHomogenous, QMat);
445
    cvtools::matToPoints3f(QMat, Q);
95 jakw 446
 
447
}