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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With