Using strided external array as cv::Mat

asked 2015-07-22 04:13:12 -0500

Alex Shtof gravatar image

updated 2015-07-28 04:53:57 -0500

I have an array in memory that represents a matrix. However, I have a stride value for both rows and individual elements. That is, the step from one element in a row to the next is NOT the size associated with its type (e.g. 8 for doubles).

Is there any way to construct a cv::Mat object that maps to this chunk of memory?

P.S. The constructor of cv::Mat with step-size does not seem to do the trick, since I cannot specify the step size between elements in a row.

Update - data layout

Let's say I have an 3D LxMxN array. It stored in a consecutive chunk of memory representing a 1D array of L*M*N entries. The data is organized in L-N-M storage order. The following example demonstrates the data layout of a 3x2x2 array in i:(n,m,l) format where i is the actual index in the memory chunk and (n,m,l) is the corresponding index in the 3D array:

0:(0,0,0)  1:(1,0,0)  2:(2,0,0), 
3:(0,1,0)  4:(1,1,0)  5:(2,1,0),
6:(0,0,1)  7:(1,0,1)  8:(2,0,1),
9:(0,1,1) 10:(1,1,1) 11:(2,1,1)

Given such a chunk in memory representing the 3D array A and a number i, I would like to construct a cv::Mat object representing a 2D array B such that B(m,n) maps to the same memory cell as A(i,m,n).

edit retag flag offensive close merge delete



can you describe, how your data is set up ? maybe we can find some magic Mat pattern, that fits.

berak gravatar imageberak ( 2015-07-22 04:36:23 -0500 )edit

@berak, I added an explanation about the data layout.

Alex Shtof gravatar imageAlex Shtof ( 2015-07-27 04:28:56 -0500 )edit

no matlab person here, having trouble understanding your notation. but there's 2 obstacles, where you can't pass the same memory object into a cv::Mat:

  • do you have consecutive memory ? or an array of arrays constructed with 'new' ?
  • do you have to reorder / shuffle your elements ?
berak gravatar imageberak ( 2015-07-27 04:38:20 -0500 )edit

@berak, I wrote the meaning of my notation explicitly. I hope it is clear now.

Alex Shtof gravatar imageAlex Shtof ( 2015-07-28 04:55:08 -0500 )edit

I do not have first hand experience doing this, but I believe you should be able to do this with a custom datatype where the depth matches your data layout.

pwm1234 gravatar imagepwm1234 ( 2015-07-28 11:35:13 -0500 )edit

@pwm1234, First of all thank you for your comment. It almost does the job. In my application L is not a compile-time constant. Hence, this technique does not seem useful.

Alex Shtof gravatar imageAlex Shtof ( 2015-07-30 03:05:05 -0500 )edit

Can you use CV_MAKETYPE macro as discussed here on StackOverflow?

pwm1234 gravatar imagepwm1234 ( 2015-08-03 08:48:05 -0500 )edit