c++ - 如何将 vector <cv::Point2d> 转换为 vector <cv::Point>?

标签 c++ templates opencv vector point

是否有任何简单的解决方案如何转换 vector<cv::Point2d>vector<cv::Point> ?像这里的东西 C++ convert vector<int> to vector<double>

这种类型是模板化的:

typedef Point_<double> Point2d;

typedef Point_<int> Point2i;
typedef Point2i Point;


/*!
  template 2D point class.

  The class defines a point in 2D space. Data type of the point coordinates is specified
  as a template parameter. There are a few shorter aliases available for user convenience.
  See cv::Point, cv::Point2i, cv::Point2f and cv::Point2d.
*/
template<typename _Tp> class Point_
{
public:
    typedef _Tp value_type;

    // various constructors
    Point_();
    Point_(_Tp _x, _Tp _y);
    Point_(const Point_& pt);
    Point_(const CvPoint& pt);
    Point_(const CvPoint2D32f& pt);
    Point_(const Size_<_Tp>& sz);
    Point_(const Vec<_Tp, 2>& v);

    Point_& operator = (const Point_& pt);
    //! conversion to another data type
    template<typename _Tp2> operator Point_<_Tp2>() const;

    //! conversion to the old-style C structures
    operator CvPoint() const;
    operator CvPoint2D32f() const;
    operator Vec<_Tp, 2>() const;

    //! dot product
    _Tp dot(const Point_& pt) const;
    //! dot product computed in double-precision arithmetics
    double ddot(const Point_& pt) const;
    //! cross-product
    double cross(const Point_& pt) const;
    //! checks whether the point is inside the specified rectangle
    bool inside(const Rect_<_Tp>& r) const;

    _Tp x, y; //< the point coordinates
};

最佳答案

您可以使用 vector 范围构造函数完全按照那里的描述进行操作:

#include <opencv2\opencv.hpp>
#include <vector>
using namespace cv;
using namespace std;

int main()
{
    vector<Point2d> vd{ { 1.1, 2.2 }, { 3.3, 4.4 }, {5.5, 6.6} };
    vector<Point> v(vd.begin(), vd.end());

    // Print for debug
    copy(vd.begin(), vd.end(), ostream_iterator<Point2d>(cout, " "));
    cout << endl;
    copy(v.begin(), v.end(), ostream_iterator<Point>(cout, " "));

    return 0;
}

这会起作用,因为您可以通过以下方式从 Point2d 构建一个 Point:

template<typename _Tp> template<typename _Tp2> inline Point_<_Tp>::operator Point_<_Tp2>() const
{ return Point_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y)); }

关于c++ - 如何将 vector <cv::Point2d> 转换为 vector <cv::Point>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34395705/

相关文章:

c++ - 为什么我的模板特化需要匹配原始约束?

opencv - 线性判别分析和主成分分析的主要区别是什么

python - opencv - 如何在没有比例的情况下进行模板匹配?

C++ 从 Char 数组返回 T 类型的指针

arrays - std::arrays 的 std::vector 的比较函数

qt - 体系结构 x86_64 的 undefined symbol 将 QT 与 Opencv 结合使用

C++0x lambdas 编码风格

c++ - 构建一个 char* vector

c++ - 通过 decltype 声明一个 vector

python - 使用 python 和调用函数自省(introspection) C++ dll