Subversion Repositories seema-scanner

Rev

Rev 42 | Rev 44 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

#include "AlgorithmGrayCode.h"
#include <cmath>
#include "cvtools.h"

#ifndef log2f
#define log2f(x) (log(x)/log(2.0))
#endif

//using namespace std;

/*
 * The purpose of this function is to convert an unsigned
 * binary number to reflected binary Gray code.
 *
 * The operator >> is shift right. The operator ^ is exclusive or.
 * Source: http://en.wikipedia.org/wiki/Gray_code
 */
static unsigned int binaryToGray(unsigned int num) {
    return (num >> 1) ^ num;
}

/*
 * From Wikipedia: http://en.wikipedia.org/wiki/Gray_code
 * The purpose of this function is to convert a reflected binary
 * Gray code number to a binary number.
 */
static unsigned grayToBinary(unsigned num, unsigned numBits)
{
    for (unsigned shift = 1; shift < numBits; shift <<= 1){
        num ^= num >> shift;
    }
    return num;
}

/*
 * Function takes the decimal number
 * Function takes the Nth bit (1 to 31)
 * Return the value of Nth bit from decimal
 * Source: http://icfun.blogspot.com/2009/04/get-n-th-bit-value-of-any-integer.html
 */
static int get_bit(int decimal, int N){

    // Shifting the 1 for N-1 bits
    int constant = 1 << (N-1);

    // If the bit is set, return 1
    if( decimal & constant ){
        return 1;
    }

    // If the bit is not set, return 0
    return 0;
}

static inline int powi(int num, unsigned int exponent){
    // NOT EQUIVALENT TO pow()
    if(exponent == 0)
        return 1;

    float res = num;
    for(unsigned int i=0; i<exponent-1; i++)
        res *= num;

    return res;
}

// Algorithm
AlgorithmGrayCode::AlgorithmGrayCode(unsigned int _screenCols, unsigned int _screenRows, CodingDir _dir) : Algorithm(_screenCols, _screenRows, _dir){

    // on/off patterns
    Nbits = ceilf(log2f((float)screenCols));
    N = 2 + Nbits*2;

    // all on pattern
    cv::Mat allOn(1, screenCols, CV_8UC3, cv::Scalar::all(255));
    patterns.push_back(allOn);

    // all off pattern
    cv::Mat allOff(1, screenCols, CV_8UC3, cv::Scalar::all(0));
    patterns.push_back(allOff);


    // horizontally encoding patterns
    for(unsigned int p=0; p<Nbits; p++){
        cv::Mat pattern(1, screenCols, CV_8UC3);
        cv::Mat patternInv(1, screenCols, CV_8UC3);

        for(unsigned int j=0; j<screenCols; j++){

            unsigned int jGray = binaryToGray(j);
            // Amplitude of channels
            int bit = get_bit(jGray, Nbits-p);
            pattern.at<cv::Vec3b>(0,j) = cv::Vec3b(255.0*bit,255.0*bit,255.0*bit);
            int invBit = bit^1;
            patternInv.at<cv::Vec3b>(0,j) = cv::Vec3b(255.0*invBit,255.0*invBit,255.0*invBit);
        }
        patterns.push_back(pattern);
        patterns.push_back(patternInv);
    }


}

cv::Mat AlgorithmGrayCode::getEncodingPattern(unsigned int depth){
    return patterns[depth];
}


bool sortingLarger(cv::Vec4f i,cv::Vec4f j){ return (i[3]<j[3]);}
bool sortingEqual(cv::Vec4f i,cv::Vec4f j){ return (i[3]==j[3]);}
void getEdgeLabels(const cv::Mat& scanLine, int Nbits, std::vector<cv::Vec4f>& edges){

    int nCols = scanLine.cols;
    const short *data = scanLine.ptr<const short>(0);

    short labelLeft;
    short labelRight = data[0];

    // collect edges
    for(int col=1; col<nCols; col++){

        labelLeft = labelRight;
        labelRight = data[col];

        if(labelLeft != -1 && labelRight != -1 && labelLeft != labelRight){
            int orderingRelation = (labelLeft << Nbits) + labelRight;
            edges.push_back(cv::Vec4f(col-0.5, labelLeft, labelRight, orderingRelation));
        }
    }

    // sort
    std::sort(edges.begin(), edges.end(), sortingLarger);

    // remove duplicates
    std::vector<cv::Vec4f>::iterator it;
    it = std::unique(edges.begin(), edges.end(), sortingEqual);
    edges.resize(std::distance(edges.begin(),it));
}

void AlgorithmGrayCode::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){

    assert(frames0.size() == N);
    assert(frames1.size() == N);

    int frameRows = frames0[0].rows;
    int frameCols = frames0[0].cols;

    // rectifying homographies (rotation+projections)
    cv::Size frameSize(frameCols, frameRows);
    cv::Mat R, T;
    // stereoRectify segfaults unless R is double precision
    cv::Mat(calibration.R1).convertTo(R, CV_64F);
    cv::Mat(calibration.T1).convertTo(T, CV_64F);
    cv::Mat R0, R1, P0, P1, QRect;
    cv::stereoRectify(calibration.K0, calibration.k0, calibration.K1, calibration.k1, frameSize, R, T, R0, R1, P0, P1, QRect, 0);

    std::cout << "R0" << std::endl << R0 << std::endl;
    std::cout << "P0" << std::endl << P0 << std::endl;
    std::cout << "R1" << std::endl << R1 << std::endl;
    std::cout << "P1" << std::endl << P1 << std::endl;

    // interpolation maps
    cv::Mat map0X, map0Y, map1X, map1Y;
    cv::initUndistortRectifyMap(calibration.K0, calibration.k0, R0, P0, frameSize, CV_32F, map0X, map0Y);
    cv::initUndistortRectifyMap(calibration.K1, calibration.k1, R1, P1, frameSize, CV_32F, map1X, map1Y);

    // gray-scale and remap
    std::vector<cv::Mat> frames0Rect(N);
    std::vector<cv::Mat> frames1Rect(N);
    for(int i=0; i<N; i++){
        cv::Mat temp;
        cv::cvtColor(frames0[i], temp, CV_RGB2GRAY);
        cv::remap(temp, frames0Rect[i], map0X, map0Y, CV_INTER_LINEAR);
        cv::cvtColor(frames1[i], temp, CV_RGB2GRAY);
        cv::remap(temp, frames1Rect[i], map1X, map1Y, CV_INTER_LINEAR);
    }

    // color remaps
    cv::Mat color0Rect, color1Rect;
    cv::remap(frames0[0], color0Rect, map0X, map0Y, CV_INTER_CUBIC);
    cv::remap(frames1[0], color1Rect, map0X, map0Y, CV_INTER_CUBIC);

    int frameRectRows = frames0Rect[0].rows;
    int frameRectCols = frames0Rect[0].cols;

    // occlusion maps
    cv::Mat occlusion0Rect, occlusion1Rect;
    cv::subtract(frames0Rect[0], frames0Rect[1], occlusion0Rect);
    occlusion0Rect = occlusion0Rect > 50;
    cv::subtract(frames1Rect[0], frames1Rect[1], occlusion1Rect);
    occlusion1Rect = occlusion1Rect > 50;
//cvtools::writeMat(occlusion0Rect, "occlusion0Rect.mat", "occlusion0Rect");
//cvtools::writeMat(occlusion1Rect, "occlusion1Rect.mat", "occlusion1Rect");

    // decode patterns
    cv::Mat code0Rect(frameRectRows, frameRectCols, CV_16S, cv::Scalar(-1));
    cv::Mat code1Rect(frameRectRows, frameRectCols, CV_16S, cv::Scalar(-1));
    cv::add(code0Rect, 1, code0Rect, occlusion0Rect, CV_16S);
    cv::add(code1Rect, 1, code1Rect, occlusion1Rect, CV_16S);

    for(int i=0; i<Nbits; i++){
        cv::Mat bit0;
        cv::subtract(frames0Rect[i*2+2], frames0Rect[i*2+3], bit0, cv::noArray(), CV_16S);
        bit0 = bit0 > 0;
//    cvtools::writeMat(bit0, "bit0.mat", "bit0");
        cv::add(code0Rect, bit0/255*powi(2,i), code0Rect, occlusion0Rect, CV_16S);
//    cvtools::writeMat(code0Rect, "code0Rect.mat", "code0Rect");
        cv::Mat bit1;
        cv::subtract(frames1Rect[i*2+2], frames1Rect[i*2+3], bit1, cv::noArray(), CV_16S);
        bit1 = bit1 > 0;
        cv::add(code1Rect, bit1/255*powi(2,i), code1Rect, occlusion1Rect, CV_16S);
    }

//cvtools::writeMat(code0Rect, "code0Rect.mat", "code0Rect");
//cvtools::writeMat(code1Rect, "code1Rect.mat", "code1Rect");

    // matching
    std::vector<cv::Vec2f> q0Rect, q1Rect;
    for(int row=0; row<frameRectRows; row++){

        std::vector<cv::Vec4f> edges0, edges1;

        // sorted, unique edges
        getEdgeLabels(code0Rect.row(row), Nbits, edges0);
        getEdgeLabels(code1Rect.row(row), Nbits, edges1);

        // subpixel refinement
        // ...

        int i=0, j=0;
        while(i<edges0.size() && j<edges1.size()){

            if(edges0[i][3] == edges1[j][3]){
                q0Rect.push_back(cv::Vec2f(edges0[i][0], row));
                q1Rect.push_back(cv::Vec2f(edges1[j][0], row));
                i += 1;
                j += 1;
            } else if(edges0[i][3] < edges1[j][3]){
                i += 1;
            } else if(edges0[i][3] > edges1[j][3]){
                j += 1;
            }
        }


    }

    // retrieve color information
    int nMatches = q0Rect.size();
    color.resize(nMatches);
    for(int i=0; i<nMatches; i++){

        cv::Vec3b c0 = color0Rect.at<cv::Vec3b>(q0Rect[i][1], q0Rect[i][0]);
        cv::Vec3b c1 = color1Rect.at<cv::Vec3b>(q1Rect[i][1], q1Rect[i][0]);

        color[i] = 0.5*(c0 + c1);
    }

    // triangulate points
    cv::Mat QMatHomogenous, QMat;
    cv::triangulatePoints(P0, P1, q0Rect, q1Rect, QMatHomogenous);
    cvtools::convertMatFromHomogeneous(QMatHomogenous, QMat);
    cvtools::matToPoints3f(QMat, Q);
}