Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift (like Matlab function) rows or columns of a matrix in OpenCV

Tags:

opencv

In Matlab there is a shift function in order to perform a circular shift of the columns or rows of a matrix. There is a similar function in OpenCV?

like image 587
user1370912 Avatar asked May 02 '12 19:05

user1370912


2 Answers

I was searching for same question but since there is none, I wrote by myself. Here is another option. In my code you can shift right or left n times: for left numRight is -n, right +n.

void shiftCol(Mat& out, Mat in, int numRight){
    if(numRight == 0){ 
        in.copyTo(out);
        return;
    }

    int ncols = in.cols;
    int nrows = in.rows;

    out = Mat::zeros(in.size(), in.type());

    numRight = numRight%ncols;
    if(numRight < 0)
        numRight = ncols+numRight;

    in(cv::Rect(ncols-numRight,0, numRight,nrows)).copyTo(out(cv::Rect(0,0,numRight,nrows)));
    in(cv::Rect(0,0, ncols-numRight,nrows)).copyTo(out(cv::Rect(numRight,0,ncols-numRight,nrows)));
}

Hope this will help to some people. Similarly, shiftRows can be written

like image 116
smttsp Avatar answered Sep 23 '22 08:09

smttsp


Here is my implementation of the circular matrix shift. Any suggestion is welcome.

//circular shift one row from up to down
void shiftRows(Mat& mat) {

    Mat temp;
    Mat m;
    int k = (mat.rows-1);
    mat.row(k).copyTo(temp);
    for(; k > 0 ; k-- ) {
        m = mat.row(k);
        mat.row(k-1).copyTo(m);
    }
    m = mat.row(0);
    temp.copyTo(m);

}

//circular shift n rows from up to down if n > 0, -n rows from down to up if n < 0
void shiftRows(Mat& mat,int n) {

    if( n < 0 ) {

        n = -n;
        flip(mat,mat,0);
        for(int k=0; k < n;k++) {
            shiftRows(mat);
        }
        flip(mat,mat,0);

    } else {

        for(int k=0; k < n;k++) {
            shiftRows(mat);
        }
    }

}

//circular shift n columns from left to right if n > 0, -n columns from right to left if n < 0
void shiftCols(Mat& mat, int n) {

    if(n < 0){

        n = -n;
        flip(mat,mat,1);
        transpose(mat,mat);
        shiftRows(mat,n);
        transpose(mat,mat);
        flip(mat,mat,1);

    } else {

        transpose(mat,mat);
        shiftRows(mat,n);
        transpose(mat,mat);
    }
}
like image 43
user1370912 Avatar answered Sep 23 '22 08:09

user1370912