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

Matlab has a shift function for circularly shifting columns or rows of a matrix. Does OpenCV have a similar feature?

+3
source share
4 answers

The short answer is no.

Long answer, you can easily implement it if you really need it, for example, using temporary objects using cv::Mat::row(i) , cv::Mat::(cv::Range(rowRange), cv::Range(cv::colRange)) .

0
source

I was looking for the same question, but since it is not there, I wrote it 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 helps some people. Similarly, shiftRows can be written

+3
source

Here is my implementation of a 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); } } 
+1
source

Or, if you use Python, just the roll () method .

0
source

All Articles