【问题标题】:Rotate vector of points by point coordinate按点坐标旋转点向量
【发布时间】:2015-08-13 11:43:10
【问题描述】:

有没有一种简单的方法可以将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 循环手动完成。

【问题讨论】:

  • std::rotate 不采用自定义交换器,因此您需要设计迭代器适配器以提供点的 y 坐标视图。你最好写循环。

标签: c++ opencv vector


【解决方案1】:

你可以:

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

注意Mat没有反向迭代器(实现旋转),所以当shift为负数时,你应该将vector<Point>的大小加到shift中并使用左旋转。

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

代码如下:

#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;
}

【讨论】:

    猜你喜欢
    • 2015-12-23
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 2012-08-10
    • 1970-01-01
    相关资源
    最近更新 更多