Split 3D MatND into vector of 2D Mat opencv

夙愿已清 提交于 2019-11-29 02:26:32

A wise mage once said: Do not try to split the MatND. That's impossible. Instead... only try to realize the truth. There is no MatND.


MatND is obsolete and it's now typedef'd to Mat. In opencv2/core/core.hpp:

 typedef Mat MatND;

This means you can just treat it just like a Mat and cut it up manually. I believe the at and ptr methods don't work as expected for dims>2, so you can just grab the Mat::data pointer and compute the location of the sub-matrix. There is a ptr(int i0, int i1, int i2) method, but I have not had much luck with it because the step[] for multi-dimensional arrays is strange.

Example

// create 3D matrix with element index as content
int dims[] = { 5, 5, 3 };
cv::Mat mnd(3, dims, CV_64F);
for (int i = 0; i < mnd.total(); ++i)
    *((double*)mnd.data+i) = (double)i;

// extract planes from matrix
std::vector<cv::Mat> matVec;
for (int p = 0; p < dims[2]; ++p) {
    double *ind = (double*)mnd.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 << "Size of matVec: " << matVec.size() << std::endl;
std::cout << "Size of first Mat: " << matVec[0].size() << std::endl;

std::cout << "\nmatVec[0]:\n" << matVec[0] << std::endl;
std::cout << "\nmatVec[1]:\n" << matVec[1] << std::endl;
std::cout << "\nmatVec[2]:\n" << matVec[2] << std::endl;

Output

Size of matVec: 3
Size of first Mat: [5 x 5]

matVec[0]:
[0, 1, 2, 3, 4;
  5, 6, 7, 8, 9;
  10, 11, 12, 13, 14;
  15, 16, 17, 18, 19;
  20, 21, 22, 23, 24]

matVec[1]:
[25, 26, 27, 28, 29;
  30, 31, 32, 33, 34;
  35, 36, 37, 38, 39;
  40, 41, 42, 43, 44;
  45, 46, 47, 48, 49]

matVec[2]:
[50, 51, 52, 53, 54;
  55, 56, 57, 58, 59;
  60, 61, 62, 63, 64;
  65, 66, 67, 68, 69;
  70, 71, 72, 73, 74]

A solution for people who use numpy/MATLAB syntax extracting submatrices.

Mat mat3D;
// ... 3D matrix with shape (A, B, C)
// equivalent to numpy: mat3D[a, :, :]
Range ranges[3] = {Range(a, a+1), Range::all(), Range::all()};
Mat mat2D = mat3D(ranges).reshape(0, {mat3D.size[1], mat3D.size[2]});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!