简体   繁体   中英

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

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));
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM