How to access submatrix of multidimensional matrix in OpenCV function?

I have a 100x100x100 multidimensional matrix A and I want to get a sub-matrix of A for example A[10:20, 20:30, 30:40]

. When the original matrix has two dimensions, OpenCV has a Mat operator to access the sub-matrix, for example:A(Range(10,20), Range(20,30))

For a multidimensional matrix, is there an efficient way to do this access? I am asking this because I need to copy the submatrix somewhere else.

+3


source to share


1 answer


Answer 1

If mat A is 3D 100 rows x 100 cols x 100 planes xn channels, you can use Mat Mat :: operator () (const Range *) const like this:

std::vector<Range> ranges;
ranges.push_back(Range(10,20));
ranges.push_back(Range(20,30));
ranges.push_back(Range(30,40));

Mat B = A(&ranges[0]);

      

B will be 10x10x10 xn channels


Answer 2



If, however, Matrix A is 100 rows x 100 ears x 100 channels, this is just a 100 channel 2D math. You can do it:

Mat B = A(Range(10,20), Range(20,30));  // B will be 10x10x100

      

Now you need to select 30:40 channels from B, you will need to use void mixChannels (const Mat * src, size_t nsrcs, Mat * dst, size_t ndsts, const int * fromTo, size_t npairs) :

Mat C(10, 10, CV_MAKETYPE(A.depth(), 10));
int from_to[] = { 10,0, 11,1, 12,2, 13,3, 14,4,
                  15,5, 16,6, 17,7, 18,8, 19,9};
mixChannels(&B, 1, &C, 1, fromTo, 10);

      

C will then be 10 rows x 10 cols x 10 channels as needed. It's a little messy, but I don't know a better way.

+4


source







All Articles