2D matrix reshape into 3D matrix

asked 2015-04-06 09:04:45 -0600

Gilad Darmon gravatar image

updated 2015-04-06 09:34:03 -0600

I Can see that opencv Reshape has been overloaded with

Mat reshape(int cn, int rows=0) const;
Mat reshape(int cn, int newndims, const int* newsz) const;

I wan to create this matlab code

original matrix gili = 2x24

1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19  20  21  22  23  24
25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48

reshapeGili = 4x6x2

reshape([gili(1,:) gili(2,:)], 4, 6, 2);


val(:,:,1) =

     1     5     9    13    17    21
     2     6    10    14    18    22
     3     7    11    15    19    23
     4     8    12    16    20    24


val(:,:,2) =

    25    29    33    37    41    45
    26    30    34    38    42    46
    27    31    35    39    43    47
    28    32    36    40    44    48

Can this be done using reshape?

I can create int newdims[] = { 4, 6, 2 };

but what does const int*newsz mean?

if I can't use reshape I will just create a new matrix and copy the values to it.

   int sizes[] = { 4, 6, 2 };
    cv::Mat xyFinal(3, sizes, CV_64F, cv::Scalar(0));
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 6; j++)
        {
            xyFinal.at<double>(i,j,0) = xyFinalMat.at<double>(0,i*6+j);
            xyFinal.at<double>(i,j,1) = xyFinalMat.at<double>(1,i*6+j);
        }
    }

the code works however when I try to print the output matrix

ofstream myfile;
    myfile.open("C:\\Users\\gdarmon\\Desktop\\OpenCV_CR.txt");
    myfile << xyFinal;
    myfile.close();


OpenCV Error: Assertion failed (m.dims <= 2) in cv::writeMat, file C:\buildslave
64\win64_amdocl\2_4_PackSlave-win64-vc11-shared\opencv\modules\core\src\out.cpp,
 line 117
edit retag flag offensive close merge delete

Comments

You have to declare xyFinal as CV_64FC2 (means 64-bit float and two channels).

Pedro Batista gravatar imagePedro Batista ( 2015-04-06 09:47:05 -0600 )edit