逐点旋转点矢量

时间:2015-08-13 11:43:10

标签: c++ opencv vector

是否有一种简单的方法可以将cv::vector<cv::Point>中存储的一组点移动cv::Point定义的数量?像std :: rotate之类的东西,但只有一个点的坐标。它应该考虑矢量的大小。

例如,

[1,0],[0,1],[1,2],[2,3][0,2]移至[1,2],[0,3],[1,0],[2,1]

我能想到的唯一方法是使用for循环手动完成。

1 个答案:

答案 0 :(得分:1)

你可以:

  1. Mat创建vector<Point>。它将是一个2通道矩阵,Nx1
  2. 重塑,使其成为1通道矩阵,Nx2
  3. 获取包含x和y坐标的列
  4. 使用MatIterator
  5. 在该列上使用旋转

    请注意Mat没有反向迭代器(实现旋转),因此,当shift为负时,您应该将vector<Point>的大小添加到班次并使用轮换。

    您主要使用矩阵标头,因此不会复制数据。

    以下是代码:

    #include <opencv2\opencv.hpp>
    #include <vector>
    #include <iostream>
    
    using namespace std;
    using namespace cv;
    
    int main()
    {
        vector<Point> pts = { Point(1, 0), Point(0, 1), Point(1, 2), Point(2, 3) };
        Point shift(0,2);
    
        for (const Point& p : pts) { cout << "[" << p.x << ", " << p.y << "] "; } cout << endl;
    
        // [1, 0] [0, 1] [1, 2] [2, 3]
    
        // ----------------------------  
    
        Mat mpts(pts);
        Mat xy = mpts.reshape(1);
        Mat x = xy.col(0);
        Mat y = xy.col(1);
    
        if (shift.x < 0)
            shift.x += pts.size();
    
        std::rotate(x.begin<Point::value_type>(), x.begin<Point::value_type>() + shift.x, x.end<Point::value_type>());
    
        if (shift.y < 0)
            shift.y += pts.size();
    
        std::rotate(y.begin<Point::value_type>(), y.begin<Point::value_type>() + shift.y, y.end<Point::value_type>());
    
        // ----------------------------        
    
        for (const Point& p : pts) { cout << "[" << p.x << ", " << p.y << "] "; } cout << endl;
    
        // [1, 2] [0, 3] [1, 0] [2, 1]
    
        return 0;
    }
    
相关问题