13

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));
}
Kyle McDonald
  • 1,171
  • 2
  • 11
  • 17

2 Answers2

16

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.

Stefan
  • 919
  • 2
  • 13
  • 24
Kyle McDonald
  • 1,171
  • 2
  • 11
  • 17
7

Be aware that converting from cv::Point2f to cv::Point2i may have unexpected results.

float j = 1.51;    
int i = (int) j;
printf("%d", i);

Will result in "1".

while

cv::Point2f j(1.51, 1.49);
cv::Point2i i = f;
std::cout << i << std::endl;

will result in "2, 1".

That means, Point2f to Point2i will round, while type casting will truncate.

http://docs.opencv.org/modules/core/doc/basic_structures.html#point

gitfredy
  • 399
  • 4
  • 3