Convert Vector OpenCV 2 <Point2i> to Vector <Point2f>

An OpenCV 2 loop search returns vector<Point2i>, but sometimes you want to use them with the function for which it is required vector<Point2f>. What is the fastest and most elegant way to convert?

Here are some ideas. A very general conversion function for everything that can be converted to 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 is not perfect. Here's an approach that pre-allocates a 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 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));
}
+5
source share
2 answers

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

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

OpenCV 2.3.x :

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

UPDATE: type() - Mat, std::vector. dst.type().

Mat dst , () :

cv::Mat(dst).type();
+9

, cv:: Point2f cv:: Point2i .

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

"1".

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

"2, 1".

, Point2f to Point2i , .

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

+1

All Articles