Ask Your Question
0

Pointer to cv::Mat and sizeof underlying structure

asked 2016-02-24 09:27:07 -0600

Vaniax gravatar image

Hi,

I have to use an interface which 'transmits' data between different execution units in a pipeline. The interface of the correspoding transmit function looks similar to this:

transmit(TimeStamp time, const void* data, int sizeOfData)

Now I want to transmit OpenCV matrices over this interface. In the first place I used an intermediate data structure like this:

typedef struct {
    int rows;
    int cols;
    int channels;
    unsigned int depth;
    unsigned char* data;
} CVMat;

Function call:

CVMat mat;
transmit(time, &mat, sizeof(CVMat));

On the other side I can reconstruct a new matrix with the transmitted data.

Now I wonder whether its possible to transmit OpenCV matrices directly. But I'm not sure how to deal with the concept of the seperation between data and header. Is it possible to get a void pointer to an OpenCV matrix and what is the correct way to determine the size of the underlying data structure? Is a reconstruction of the matrix possible (cast to cv::Mat)?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2016-02-24 12:54:53 -0600

Guyygarty gravatar image

updated 2016-02-24 13:04:24 -0600

You don't really need the size. You can define a void pointer :

Mat Image;
...
void *P=(void *) &Image;

and then at the destination recreate the Mat using:

Mat Image1=((Mat) *(Mat *)P);
Mat Image2=((Mat) *(Mat *)P).clone();

Note that Image1 is the same Mat as you had originally. If you change anything in Image, Image1 will also change and vice versa.

Image2 is a new Mat, that has a copy of the original image

As a note, you should think seriously on how you want to do this.

Using Image1 is faster and more memory efficient, but will likely mess up the reference counting in OpenCV and (if you are not careful) can lead to either a memory leak or to your image going out of scope while you are still using it.

guy

edit flag offensive delete link more

Comments

Thank you very much, that's exactly the solution I was looking for. But isn't the second cast (Mat) unnecessary? When dereferencing a Mat* I get the corresponding Mat object, right?

Vaniax gravatar imageVaniax ( 2016-02-26 01:06:10 -0600 )edit

It's probably not required for compilation and running but it doesn't hurt to have it. I vaguely recall that without it, VS2013's auto-completion didn't recognize (Mat)P as a Mat. guy

Guyygarty gravatar imageGuyygarty ( 2016-02-26 08:04:16 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2016-02-24 09:27:07 -0600

Seen: 3,066 times

Last updated: Feb 24 '16