neuviemeporte
neuviemeporte

Reputation: 6478

Is it safe to manipulate the internal buffer of a cv::Mat like this?

I need to create a cv::Mat from a buffer, but I don't want the data to be shared, so I can't use the Mat(height, width, type, data) constructor:

int data[100];
cv::Mat m;
m.create(10, 10, CV_32SC1); // allocate own buffer for m
for (size_t i = 0; i < 100; ++i)
{
    reinterpret_cast<int*>(m.data)[i] = data[i];
}

I need to cast the internal buffer (which is always uchar*) to be able to copy data of my desired type (int in this case) directly, and it seems to work. However, I recall that the docs preferred the method of doing all operations using uchar*, that is casting the source buffer into uchar* and using a parameter called stepWidth to obtain the correct offset in uchar*-units. Will I get in trouble doing this the other way around, or is the buffer of a CV_32SC1-type Mat simply a buffer of int, and it doesn't make a difference?

Upvotes: 0

Views: 765

Answers (1)

Martin Beckett
Martin Beckett

Reputation: 96147

Yes, the cv::Mat internal buffers are just a block of data - do with them as you will (just don't free them!)

The only complexity, for multidimensional arrays (such as images) is that each new row doesn't necessarily follow directly from the end of the last row. The rows are padded so they always start on a 32bit (64bit for 64bit builds??) boundary - so you need to use data(row).

There is a topic on 'foreign data' in the cv::Mat docs

Upvotes: 1

Related Questions