Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert OpenCV 2 vector<Point2i> to vector<Point2f>

Tags:

c++

opencv

stl

The OpenCV 2 contour finder returns a vector<Point2i>, but sometimes you want to use these with a function that requires a vector<Point2f>. What is the fastest, most elegant way to convert?

Here are some ideas. A very general conversion function for anything that can be converted to a Mat:

template <class SrcType, class DstType>
void convert1(std::vector<SrcType>& src, std::vector<DstType>& dst) {
  cv::Mat srcMat = cv::Mat(src);
  cv::Mat dstMat = cv::Mat(dst);
  cv::Mat tmpMat;
  srcMat.convertTo(tmpMat, dstMat.type());
  dst = (vector<DstType>) tmpMat;
}

But this uses an extra buffer, so it's not ideal. Here's an approach that pre-allocates the vector then calls copy():

template <class SrcType, class DstType>
void convert2(std::vector<SrcType>& src, std::vector<DstType>& dst) {
  dst.resize(src.size());
  std::copy(src.begin(), src.end(), dst.begin());
}

Finally, using a back_inserter:

template <class SrcType, class DstType>
void convert3(std::vector<SrcType>& src, std::vector<DstType>& dst) {
  std::copy(src.begin(), src.end(), std::back_inserter(dst));
}
like image 904
Kyle McDonald Avatar asked Sep 12 '11 10:09

Kyle McDonald


1 Answers

Assuming src and dst are vectors, in OpenCV 2.x you can say:

cv::Mat(src).copyTo(dst);

And in OpenCV 2.3.x you can say:

cv::Mat(src).convertTo(dst, cv::Mat(dst).type());  

Note: type() is a function of the Mat and not of the std::vector class. Therefore, you cannot call dst.type(). If you create a Mat instance using dst as input then you can call the function type() for the newly created object.

like image 57
Kyle McDonald Avatar answered Nov 15 '22 19:11

Kyle McDonald