简体   繁体   中英

Sort vector of cv::Point2i clockwise

I'm new and I have a std::vector of cv::Point2i :

vector<Point2i> x_y;

And I want to sort them clockwise!
How can I do it?

You can use std::sort .
Overload (3) accepts a custom comparator , that should:

returns true if the first argument is less than (ie is ordered before) the second.

Your comparator should compare the angles of the lines connecting the points to the origin (or to any other rotation pivot).

Here is a complete example (replace Point with cv::Point2i ):

#include <vector>
#include <algorithm>
#include <iostream>
#include <cmath>

struct Point
{
    int x;
    int y;
};

int main()
{
    std::vector<Point> points = { {0,1}, {-1,0}, {-1,1}, {1,0} };

    Point pivot{ 0,0 }; // Select a point from the vector, or any other (will be used as rotation center).
    std::sort(points.begin(),
              points.end(),
              [pivot](Point const& p1, Point const& p2)
                     { return std::atan2(p1.y - pivot.y, p1.x - pivot.x) > std::atan2(p2.y - pivot.y, p2.x - pivot.x); });

    for (auto const& p : points)
    {
        std::cout << "{" << p.x << "," << p.y << "}" << std::endl;
    }
}

Note that I used > in the comparator to get a clockwise order (in which large angles should come before small ones). Use < for an anti-clockwise order).

Output:

{-1,0}
{-1,1}
{0,1}
{1,0}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM