jkl
jkl

Reputation: 103

How to copy the structure of a vector of vectors to another one in C++ using OpenCV

I have got a vector containing contours of an image. The code looks like this:

cv::Mat img = cv::imread ("whatever");

cv::Mat edges;
double lowThresh = 100, highThresh = 2*lowThresh;
Canny(img, edges, lowThresh, highThresh);

std::vector<std::vector<cv::Point>> contourVec;
std::vector<cv::Vec4i> hierarchy;
int mode = CV_RETR_LIST;
int method = CV_CHAIN_APPROX_TC89_KCOS;
findContours(edges, contourVec, hierarchy, mode, method);

What I now would like to do is to transform these points. I therefore created another vector, which shall have the same structure as the other one, just with Point3delements instead of Point. At the moment, I do it like this:

std::vector<std::vector<cv::Point3d>> contour3DVec(contourVec.size());
for (int i = 0; i < contourVec.size(); i++)
    contour3DVec[i].resize(contourVec[i].size());

But I'm not sure whether that is really the best way to do it, as I don't know how resize()is actually working (e.g. in the field of memory location).

Does anybody have an idea whether there is a faster and/or "smarter" way to solve this? Thanks in advance.

Upvotes: 1

Views: 910

Answers (2)

berak
berak

Reputation: 39816

if you want 3d points, you'll have to create them manually, one by one:

std::vector<std::vector<cv::Point3d>> contour3DVec(contourVec.size());
for (size_t i = 0; i < contourVec.size(); i++)
{
    for (size_t j = 0; j < contourVec[i].size(); j++)
    {
        Point p = contourVec[i][j];
        contour3DVec[i].push_back( Point3d(p.x, p.y, 1) );
    }
}

Upvotes: 1

xophos
xophos

Reputation: 386

Given that you surely want to do something with the contours afterwards, the resizing probably won't be a performance hotspot in your Program.

Vectors in c++ are usually created with a bit of slack to grow. They may take up to double their current size in memory.

If you resize a vector it will first check if the resizing will fit in the reserved memory. If that's the case the resizing is free.

Otherwise new memory (up to double the new size) will be reserved and the current vector content moved there.

As your vectors are empty in the beginning, they will have to reserve new memory anyway, so (given a sane compiler and standard library) it would be hard to beat your Implementation speed wise.

Upvotes: 2

Related Questions