Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a sub-matrix of a multi-dimensional matrix in OpenCV function?

Tags:

c++

opencv

matrix

I have a multi-dimensional matrix A of size 100x100x100 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 multi-dimensional matrix, is there any efficient way to do this access? I am asking this because I need to copy the sub-matrix into another place.

like image 424
user2970089 Avatar asked Aug 19 '14 23:08

user2970089


1 Answers

Answer 1

If mat A is 3D 100 rows x 100 cols x 100 planes x n channels, you can use Mat Mat::operator()(const Range* ranges) 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 x n channels


Answer 2

If however mat A is 100 rows x 100 cols x 100 channels, that is just a 100 channel 2D mat. You can do this:

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

Now you need to select channels 30:40 from B, you would 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 required. This is a bit messy but I don't know a better way.

like image 172
Bull Avatar answered Sep 26 '22 19:09

Bull