2011-09-12 262 views
5

OpenCV 2等高線查找程序返回vector<Point2i>,但有時候您希望將這些用於需要vector<Point2f>的功能。什麼是最快,最優雅的轉換方式?將OpenCV 2矢量<Point2i>轉換爲矢量<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)); 
} 

回答

9

假設SRC和DST是矢量,在OpenCV的2.x的,你可以說:

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

而且在OpenCV的2.3.x版本,你可以說:

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

UPDATE:類型()的函數,而不是的std ::矢量類的。因此,您不能致電dst.type()

,如果您使用DST作爲輸入,那麼你可以調用函數類型()爲新創建對象的實例墊:

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

thx!澄清:cv :: Mat(src).convertTo(dst,cv :: Mat(dst).type()); – Flayn

1

要知道,從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#point

相關問題