Ask Your Question
0

Convert cv::Mat to std::vector without copying

asked 2017-05-01 16:36:03 -0600

lovaj gravatar image

I've this function:

void foo(cv::Mat &mat){
  float *p = mat.ptr<float>(0);
  //modify mat values through p
}

And I have this code that calls the function:

void bar(std::vector<unsigned char> &vec){
  //...
  cv::Mat res(m, n, CV_32FC1, (void *)&workspace.front());
}

However, the code above has a performance problem: vec isn't probably aligned. In fact, the Intel compiler says that reference *out has unaligned access. I hope that this is the reason.

Btw, as I found out, cv::Mat is going to be aligned. So a simple workaround would be to:

  1. Create cv::Mat res(m,n)
  2. Call foo(m);
  3. Assign the vec pointer to m.ptr<float>(0)

As you can imagine, performance here are crucial, so deep-copies are out of questions.

I tried the code in this question:

vec = res.data;

But I get a compiler error. Besides, I don't know if this code above is going to do an (inefficient) copy, or just change the pointed data by vec.

How can I do this smoothly? Otherwise, another workaround would be appreciated.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2017-05-01 16:49:33 -0600

matman gravatar image

updated 2017-05-01 16:54:45 -0600

Fastest way I know is this:

cv::Mat res(m, n, CV_32FC1);
std::vector<float>vec(res.begin<float>(), res.end<float>());

or if you declare your vec before:

std::vector<float> vec;
cv::Mat res(m, n, CV_32FC1);
vec.assign(res.begin<float>(), res.end<float>());
edit flag offensive delete link more

Comments

But this is going to copy element by element, right? It's not just copying the references, right? In other words: the cost is linear, right?

lovaj gravatar imagelovaj ( 2017-05-02 04:06:20 -0600 )edit
1

Thats right. I didn't think about it yesterday. So I don't think it is possible to pass a pointer to a std::vector. You have to deal with plain pointer array if you won't copy the data.

matman gravatar imagematman ( 2017-05-02 10:36:35 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2017-05-01 16:36:03 -0600

Seen: 20,682 times

Last updated: May 01 '17