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

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

本文关键字:vector lt to Point2f gt Point2i convert OpenCV      更新时间:2023-10-16

OpenCV 2轮廓查找器返回vector<Point2i>,但有时您希望将这些与需要vector<Point2f>的函数一起使用。最快、最优雅的转换方式是什么?

这里有一些想法。一个非常通用的转换函数,可以转换为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;
}

但是这会使用一个额外的缓冲区,所以它不是理想的。这是一种预先分配矢量然后调用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());
}
最后,使用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));
}

假设src和dst是矢量,在OpenCV 2中。X你可以说:

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

在OpenCV 2.3中。X你可以说:

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

注意:type()Mat的函数,而不是std::vector类的函数。因此,不能调用dst.type()。如果您使用dst作为输入创建Mat实例,那么您可以为新创建的对象调用函数type()

请注意,从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到Point2i将进行舍入,而类型转换将截断。

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