问题
in OpenCV, I have a matrix like this: [3 4 2; 5 2 1; 6 7 9], that is with 3x3 size. Now I want to change it into 3x1 size, and be like this: [3 4 2 5 2 1 6 7 9]. But this is not exactly what I want, my actual goal is to put zero before and after each value, at the same time repeat each value three times. So my goal matrix should be like this: [ 0 3 3 3 0 0 4 4 4 0 0 2 2 2 0 0 5 5 5 0 0 2 2 2 0 0 1 1 1 0 0 6 6 6 0 0 7 7 7 0 0 9 9 9 0 ]. I wrote the following code for this:
for ( int i = 0; i < 3; i ++ )
{
for ( int j = 0; j < 3; j ++ )
{
for ( int m = k + 1; m < m + 3; m ++ )
{
dstMat.col (m) = srcMat.at <int> ( i, j );
}
k = k + 5 ;
}
}
Is there any better way for doing is? Especially without "for" loop, it is really time confusing. Many thanks in advance.
回答1:
You can use Mat::reshape to convert your 3x3 matrix to 3x1. This way you'll need one for loop instead of two, and it's an O(1)
operation.
you can omit the next for loop by using ROI:
srcMat.reshape(0,1);
for (int i =0; i < 9; i++)
dstMat(cv::Range::all(), cv::Range(i*5+1, i*5+4)).setTo(srcMat.at<int>(i));
and that would be all.
回答2:
You could start by calling reshape on your matrix to flatten it to one row/column. That would save you one of the for loops and make it slightly clearer.
来源:https://stackoverflow.com/questions/11883461/opencv-how-to-create-new-matrix-from-existing-matrix-with-some-changes