Subversion Repositories seema-scanner

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
95 jakw 1
#include "AlgorithmGrayCodeHQ.h"
2
#include <cmath>
3
#include "cvtools.h"
4
 
5
#ifndef log2f
6
#define log2f(x) (log(x)/log(2.0))
7
#endif
8
 
9
//using namespace std;
10
 
11
/*
12
 * The purpose of this function is to convert an unsigned
13
 * binary number to reflected binary Gray code.
14
 *
15
 * The operator >> is shift right. The operator ^ is exclusive or.
16
 * Source: http://en.wikipedia.org/wiki/Gray_code
17
 */
18
static unsigned int binaryToGray(unsigned int num) {
19
    return (num >> 1) ^ num;
20
}
21
 
22
/*
23
 * From Wikipedia: http://en.wikipedia.org/wiki/Gray_code
24
 * The purpose of this function is to convert a reflected binary
25
 * Gray code number to a binary number.
26
 */
27
static unsigned int grayToBinary(unsigned int num){
28
    unsigned int mask;
29
    for(mask = num >> 1; mask != 0; mask = mask >> 1)
30
        num = num ^ mask;
31
    return num;
32
}
33
 
34
/*
35
 * Return the Nth bit of an unsigned integer number
36
 */
37
static bool getBit(int decimal, int N){
38
 
39
    return decimal & 1 << (N-1);
40
}
41
 
42
/*
43
 * Return the number of bits set in an integer
44
 */
45
static int countBits(int n) {
46
  unsigned int c; // c accumulates the total bits set in v
47
  for (c = 0; n>0; c++)
48
    n &= n - 1; // clear the least significant bit set
49
  return c;
50
}
51
 
52
/*
53
 * Return the position of the least significant bit that is set
54
 */
55
static int leastSignificantBitSet(int x){
56
  if(x == 0)
57
      return 0;
58
 
59
  int val = 1;
60
  while(x>>=1)
61
      val++;
62
 
63
  return val;
64
}
65
 
66
//static int get_bit(int decimal, int N){
67
 
68
//    // Shifting the 1 for N-1 bits
69
//    int constant = 1 << (N-1);
70
 
71
//    // If the bit is set, return 1
72
//    if( decimal & constant )
73
//        return 1;
74
//    else
75
//        return 0;
76
//}
77
 
78
static inline unsigned int powi(int num, unsigned int exponent){
79
 
80
    if(exponent == 0)
81
        return 1;
82
 
83
    float res = num;
84
    for(unsigned int i=0; i<exponent-1; i++)
85
        res *= num;
86
 
87
    return res;
88
}
89
 
90
static inline unsigned int twopowi(unsigned int exponent){
91
 
92
    return 1 << exponent;
93
}
94
 
95
// Algorithm
96
AlgorithmGrayCodeHQ::AlgorithmGrayCodeHQ(unsigned int _screenCols, unsigned int _screenRows) : Algorithm(_screenCols, _screenRows){
97
 
98
    NbitsHorz = ceilf(log2f((float)screenCols));
99
    NbitsVert =  ceilf(log2f((float)screenRows));
100
    N = 2 + (NbitsHorz+NbitsVert)*2;
101
 
102
    // all on pattern
103
    cv::Mat allOn(1, screenCols, CV_8UC3, cv::Scalar::all(255));
104
    patterns.push_back(allOn);
105
 
106
    // all off pattern
107
    cv::Mat allOff(1, screenCols, CV_8UC3, cv::Scalar::all(0));
108
    patterns.push_back(allOff);
109
 
110
 
111
    // horizontally encoding patterns
112
    for(unsigned int p=0; p<NbitsHorz; p++){
113
        cv::Mat pattern(1, screenCols, CV_8UC3);
114
        cv::Mat patternInv(1, screenCols, CV_8UC3);
115
 
116
        for(unsigned int j=0; j<screenCols; j++){
117
 
118
            unsigned int jGray = binaryToGray(j);
119
            // Amplitude of channels
120
            int bit = (int)getBit(jGray, Nbits-p);
121
            pattern.at<cv::Vec3b>(0,j) = cv::Vec3b(255.0*bit,255.0*bit,255.0*bit);
122
            int invBit = bit^1;
123
            patternInv.at<cv::Vec3b>(0,j) = cv::Vec3b(255.0*invBit,255.0*invBit,255.0*invBit);
124
        }
125
        patterns.push_back(pattern);
126
        patterns.push_back(patternInv);
127
    }
128
 
129
    // vertical encoding patterns
130
    for(unsigned int p=0; p<NbitsVert; p++){
131
        cv::Mat pattern(screenRows, 1, CV_8UC3);
132
        cv::Mat patternInv(screenRows, 1, CV_8UC3);
133
 
134
        for(unsigned int j=0; j<screenRows; j++){
135
 
136
            unsigned int jGray = binaryToGray(j);
137
            // Amplitude of channels
138
            int bit = (int)getBit(jGray, Nbits-p);
139
            pattern.at<cv::Vec3b>(j,0) = cv::Vec3b(255.0*bit,255.0*bit,255.0*bit);
140
            int invBit = bit^1;
141
            patternInv.at<cv::Vec3b>(j,0) = cv::Vec3b(255.0*invBit,255.0*invBit,255.0*invBit);
142
        }
143
        patterns.push_back(pattern);
144
        patterns.push_back(patternInv);
145
    }
146
 
147
}
148
 
149
cv::Mat AlgorithmGrayCodeHQ::getEncodingPattern(unsigned int depth){
150
    return patterns[depth];
151
}
152
 
153
 
154
bool sortingLarger(cv::Vec4i i,cv::Vec4i j){ return (i[3]<j[3]);}
155
bool sortingEqual(cv::Vec4i i,cv::Vec4i j){ return (i[3]==j[3]);}
156
void getEdgeLabels(const cv::Mat& scanLine, int Nbits, std::vector<cv::Vec4i>& edges){
157
 
158
    int nCols = scanLine.cols;
159
    const int *data = scanLine.ptr<const int>(0);
160
 
161
    int labelLeft;
162
    int labelRight = data[0];
163
 
164
    // collect edges
165
    for(int col=1; col<nCols; col++){
166
 
167
        labelLeft = labelRight;
168
        labelRight = data[col];
169
 
170
        // labels need to be non-background, and differ in exactly one bit
171
        if(labelLeft != -1 && labelRight != -1 && countBits(labelLeft^labelRight) == 1){
172
            int orderingRelation = (labelLeft << Nbits) + labelRight;
173
            // store left label column
174
            edges.push_back(cv::Vec4i(col-1, labelLeft, labelRight, orderingRelation));
175
        }
176
    }
177
 
178
    // sort
179
    std::sort(edges.begin(), edges.end(), sortingLarger);
180
 
181
    // remove duplicates
182
    std::vector<cv::Vec4i>::iterator it;
183
    it = std::unique(edges.begin(), edges.end(), sortingEqual);
184
    edges.resize(std::distance(edges.begin(),it));
185
}
186
 
187
cv::Vec3b getColorSubpix(const cv::Mat& img, cv::Point2f pt){
188
    assert(!img.empty());
189
    assert(img.channels() == 3);
190
 
191
    int x = (int)pt.x;
192
    int y = (int)pt.y;
193
 
194
    int x0 = cv::borderInterpolate(x,   img.cols, cv::BORDER_REFLECT_101);
195
    int x1 = cv::borderInterpolate(x+1, img.cols, cv::BORDER_REFLECT_101);
196
    int y0 = cv::borderInterpolate(y,   img.rows, cv::BORDER_REFLECT_101);
197
    int y1 = cv::borderInterpolate(y+1, img.rows, cv::BORDER_REFLECT_101);
198
 
199
    float a = pt.x - (float)x;
200
    float c = pt.y - (float)y;
201
 
202
    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)
203
                           + (img.at<cv::Vec3b>(y1, x0)[0] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[0] * a) * c);
204
    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)
205
                           + (img.at<cv::Vec3b>(y1, x0)[1] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[1] * a) * c);
206
    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)
207
                           + (img.at<cv::Vec3b>(y1, x0)[2] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[2] * a) * c);
208
 
209
    return cv::Vec3b(b, g, r);
210
}
211
 
212
void AlgorithmGrayCodeHQ::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){
213
 
214
    assert(frames0.size() == N);
215
    assert(frames1.size() == N);
216
 
217
    int frameRows = frames0[0].rows;
218
    int frameCols = frames0[0].cols;
219
 
220
    // gray-scale
221
    std::vector<cv::Mat> frames0Gray(N);
222
    std::vector<cv::Mat> frames1Gray(N);
223
    for(int i=0; i<N; i++){
224
        cv::cvtColor(frames0[i], frames0Gray, CV_RGB2GRAY);
225
        cv::cvtColor(frames1[i], frames1Gray, CV_RGB2GRAY);
226
    }
227
 
228
    // colors
229
    cv::Mat color0 = frames0[0];
230
    cv::Mat color1 = frames1[0];
231
 
232
    // occlusion masks
233
    cv::Mat occlusion0, occlusion1;
234
    cv::subtract(frames0Gray[0], frames0Gray[1], occlusion0);
235
    occlusion0 = occlusion0 > 25;
236
    cv::subtract(frames1Gray[0], frames1Gray[1], occlusion1);
237
    occlusion1 = occlusion1 > 25;
238
 
239
    // erode occlusion masks
240
    cv::Mat strel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3,3));
241
    cv::erode(occlusion0, occlusion0, strel);
242
    cv::erode(occlusion1, occlusion1, strel);
243
 
244
//cvtools::writeMat(occlusion0, "occlusion0.mat", "occlusion0");
245
//cvtools::writeMat(occlusion1, "occlusion1.mat", "occlusion1");
246
 
247
    // decode patterns
248
    cv::Mat code0Horz(frameRows, frameCols, CV_32S, cv::Scalar(0));
249
    cv::Mat code1Horz(frameRows, frameCols, CV_32S, cv::Scalar(0));
250
    cv::Mat code0Vert(frameRows, frameCols, CV_32S, cv::Scalar(0));
251
    cv::Mat code1Vert(frameRows, frameCols, CV_32S, cv::Scalar(0));
252
 
253
    // horizontal codes into gray code
254
    for(int i=0; i<NbitsHorz; i++){
255
        cv::Mat bit0;
256
        cv::subtract(frames0Gray[i*2+2], frames0Gray[i*2+3], bit0);
257
        bit0 = bit0 > 0;
258
        bit0.convertTo(bit0, CV_32S, 1.0/255.0);
259
        cv::add(code0Horz, bit0*twopowi(Nbits-i-1), code0Horz, cv::Mat(), CV_32S);
260
 
261
        cv::Mat bit1;
262
        cv::subtract(frames1Gray[i*2+2], frames1Gray[i*2+3], bit1);
263
        bit1 = bit1 > 0;
264
        bit1.convertTo(bit1, CV_32S, 1.0/255.0);
265
        cv::add(code1Horz, bit1*twopowi(Nbits-i-1), code1Horz, cv::Mat(), CV_32S);
266
    }
267
 
268
    // vertical codes into gray code
269
    for(int i=0; i<NbitsVert; i++){
270
        cv::Mat bit0;
271
        cv::subtract(frames0Gray[i*2+NbitsHorz+2], frames0Gray[i*2+NbitsHorz+3], bit0);
272
        bit0 = bit0 > 0;
273
        bit0.convertTo(bit0, CV_32S, 1.0/255.0);
274
        cv::add(code0Vert, bit0*twopowi(Nbits-i-1), code0Vert, cv::Mat(), CV_32S);
275
 
276
        cv::Mat bit1;
277
        cv::subtract(frames1Gray[i*2+NbitsHorz+2], frames1Gray[i*2+NbitsHorz+3], bit1);
278
        bit1 = bit1 > 0;
279
        bit1.convertTo(bit1, CV_32S, 1.0/255.0);
280
        cv::add(code1Vert, bit1*twopowi(Nbits-i-1), code1Vert, cv::Mat(), CV_32S);
281
    }
282
 
283
//cvtools::writeMat(code0Horz, "code0Horz.mat", "code0Horz");
284
//cvtools::writeMat(code1Horz, "code1Horz.mat", "code1Horz");
285
//cvtools::writeMat(code0Vert, "code0Vert.mat", "code0Vert");
286
//cvtools::writeMat(code1Vert, "code1Vert.mat", "code1Vert");
287
 
288
    // set occluded pixels to -1
289
    for(int r=0; r<frameRows; r++){
290
        for(int c=0; c<frameCols; c++){
291
            if(occlusion0.at<char>(r,c) == 0){
292
                code0Horz.at<float>(r,c) = -1;
293
                code0Vert.at<float>(r,c) = -1;
294
            }
295
            if(occlusion1.at<char>(r,c) == 0){
296
                code1Horz.at<float>(r,c) = -1;
297
                code1Vert.at<float>(r,c) = -1;
298
            }
299
        }
300
    }
301
 
302
 
303
 
304
    // TODO: REWRITE TO PERFORM HORIZONTAL + VERTICAL MATCHING
305
 
306
//    // matching
307
//    std::vector<cv::Vec2f> q0Rect, q1Rect;
308
//    for(int row=0; row<frameRectRows; row++){
309
 
310
//        // edge data structure containing [floor(column), labelLeft, labelRight, orderingRelation]
311
//        std::vector<cv::Vec4i> edges0, edges1;
312
 
313
//        // sorted, unique edges
314
//        getEdgeLabels(code0Rect.row(row), Nbits, edges0);
315
//        getEdgeLabels(code1Rect.row(row), Nbits, edges1);
316
 
317
//        // match edges
318
//        std::vector<cv::Vec4i> matchedEdges0, matchedEdges1;
319
//        int i=0, j=0;
320
//        while(i<edges0.size() && j<edges1.size()){
321
 
322
//            if(edges0[i][3] == edges1[j][3]){
323
//                matchedEdges0.push_back(edges0[i]);
324
//                matchedEdges1.push_back(edges1[j]);
325
//                i += 1;
326
//                j += 1;
327
//            } else if(edges0[i][3] < edges1[j][3]){
328
//                i += 1;
329
//            } else if(edges0[i][3] > edges1[j][3]){
330
//                j += 1;
331
//            }
332
//        }
333
 
334
//        // crude subpixel refinement
335
//        // finds the intersection of linear interpolants in the positive/negative pattern
336
//        for(int i=0; i<matchedEdges0.size(); i++){
337
 
338
//            int level = Nbits - leastSignificantBitSet(matchedEdges0[i][1]^matchedEdges0[i][2]);
339
 
340
//            // refine for camera 0
341
//            float c0 = matchedEdges0[i][0];
342
//            float c1 = c0+1;
343
 
344
//            float pos0 = frames0Rect[2*level+2].at<char>(row, c0);
345
//            float pos1 = frames0Rect[2*level+2].at<char>(row, c1);
346
//            float neg0 = frames0Rect[2*level+3].at<char>(row, c0);
347
//            float neg1 = frames0Rect[2*level+3].at<char>(row, c1);
348
 
349
//            float col = c0 + (pos0 - neg0)/(neg1 - neg0 - pos1 + pos0);
350
//            q0Rect.push_back(cv::Point2f(col, row));
351
 
352
//            // refine for camera 1
353
//            c0 = matchedEdges1[i][0];
354
//            c1 = c0+1;
355
 
356
//            pos0 = frames1Rect[2*level+2].at<char>(row, c0);
357
//            pos1 = frames1Rect[2*level+2].at<char>(row, c1);
358
//            neg0 = frames1Rect[2*level+3].at<char>(row, c0);
359
//            neg1 = frames1Rect[2*level+3].at<char>(row, c1);
360
 
361
//            col = c0 + (pos0 - neg0)/(neg1 - neg0 - pos1 + pos0);
362
//            q1Rect.push_back(cv::Point2f(col, row));
363
 
364
//        }
365
 
366
//    }
367
 
368
//    int nMatches = q0Rect.size();
369
 
370
//    if(nMatches < 1){
371
//        Q.resize(0);
372
//        color.resize(0);
373
 
374
//        return;
375
//    }
376
 
377
//    // retrieve color information (at integer coordinates)
378
//    color.resize(nMatches);
379
//    for(int i=0; i<nMatches; i++){
380
 
381
//        cv::Vec3b c0 = color0Rect.at<cv::Vec3b>(q0Rect[i][1], q0Rect[i][0]);
382
//        cv::Vec3b c1 = color1Rect.at<cv::Vec3b>(q1Rect[i][1], q1Rect[i][0]);
383
////        cv::Vec3b c0 = getColorSubpix(color0Rect, q0Rect[i]);
384
////        cv::Vec3b c1 = getColorSubpix(color1Rect, q0Rect[i]);
385
 
386
//        color[i] = 0.5*c0 + 0.5*c1;
387
//    }
388
 
389
//    // triangulate points
390
//    cv::Mat QMatHomogenous, QMat;
391
////    cv::Mat C0 = P0.clone();
392
////    cv::Mat C1 = P1.clone();
393
////    C0.colRange(0, 3) = C0.colRange(0, 3)*R0;
394
////    C1.colRange(0, 3) = C1.colRange(0, 3)*R1.t();
395
//    cv::triangulatePoints(P0, P1, q0Rect, q1Rect, QMatHomogenous);
396
//    cvtools::convertMatFromHomogeneous(QMatHomogenous, QMat);
397
 
398
//    // undo rectifying rotation
399
//    cv::Mat R0Inv;
400
//    cv::Mat(R0.t()).convertTo(R0Inv, CV_32F);
401
//    QMat = R0Inv*QMat;
402
 
403
//    cvtools::matToPoints3f(QMat, Q);
404
 
405
}