Is it possible to get a 2D Mat object from a 3D data cube stored as MatND in opencv? Basically I'm passing a 3D matrix to a MexFile using "mexopencv". I convert the matrix to a MatND object by using MxArray(prhs[0]).toMatND(). Now I want to split up this datacube along the third dimension into a vector of cv::Mat matrices. I need to make operations on these 2D matrices an therefore iterate over the third dimension. Is there a function to split the data cube as needed? Or maybe a way to get a pointer to the 2D sub matrices of the 3D data cube?
Edit: This is my code which uses mexopencv to convert the Matlab input arguments to MatND arrays. I implemented @chappjc's method of splitting up the 3D data code into a vector of 2D matrices. Apart from the fact that x and y dimensions are switched everything is fine.
#include "mexopencv.hpp"
#include <iostream>
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
// Check arguments
if (nlhs!=1 || nrhs!=1)
mexErrMsgIdAndTxt("myfunc:invalidArgs", "Wrong number of arguments");
// 1) Convert MxArray to cv::Mat
cv::MatND matnd = MxArray(prhs[0]).toMatND();
// Extract planes from matrix
int dims[] = { matnd.size[0],matnd.size[1],matnd.size[2]};
std::vector<cv::Mat> matVec;
for (int p = 0; p < dims[2]; ++p) {
double *ind = (double*)matnd.data + p * dims[0] * dims[1]; // sub-matrix pointer
matVec.push_back(cv::Mat(2, dims, CV_64F, ind).clone()); // clone if mnd goes away
}
std::cout << "
matVec[0]:
" << matVec[0] << std::endl;
std::cout << "
matVec[1]:
" << matVec[1] << std::endl;
// Here I will do some stuff with the 2D submatrices from matVec
// ...
// 2) Here I want to pass the 3D matrix back to Matlab
// I only know how to convert cv::Mat back to mxArray* using mexopencv:
plhs[0] = MxArray(matnd);
}
2nd Edit. Actually the fact that the dimensions are switched in "matVec" is pretty annoying. Does anyone have a better solution?
This is the output of a small [5 x 4 x 2] example:
>> b
b(:,:,1) =
1 6 11 16
2 7 12 17
3 8 13 18
4 9 14 19
5 10 15 20
b(:,:,2) =
101 106 111 116
102 107 112 117
103 108 113 118
104 109 114 119
105 110 115 120
>> c = cv.myFunc(b)
matVec[0]:
[1, 2, 3, 4, 5;
6, 7, 8, 9, 10;
11, 12, 13, 14, 15;
16, 17, 18, 19, 20]
matVec[1]:
[101, 102, 103, 104, 105;
106, 107, 108, 109, 110;
111, 112, 113, 114, 115;
116, 117, 118, 119, 120]
c(:,:,1) =
1 6 11 16
2 7 12 17
3 8 13 18
4 9 14 19
5 10 15 20
c(:,:,2) =
101 106 111 116
102 107 112 117
103 108 113 118
104 109 114 119
105 110 115 120
See Question&Answers more detail:os