Building contours from points Hello !

One of my algorithms constructs points which should represent a contour. My problem with these points is the order. There is no reason these points have the correct connection order in order to be able to build a contour (for example, passing these to cv::drawContours will result in a mess...).

How should I order these points to satisfy the contour definition of OpenCV ? Is it even possible ?

Thanks !

edit retag close merge delete

I can't post any code (I am not allowed to...), but I'll try to give you an example. Let's say you have found a contour (with cv::findContours for example). If you shuffle the points in the contour, there is no more reason for it to be a valid contour as the connection order (ie the line segment) is important to draw this contour.

My goal would be to restore the order of the connections.

Hoping this is clearer :)

have you tried sort functions on the vector of points?

Hey, you should set a rule for points to make up a contour, like: it is a possibly convex, since a set of points can get many valid contours without crossed line.

Sort by » oldest newest most voted

OpenCV expects a contour to be a list of points of connected pixels, in which the starting point is the top-most one (with lowest Y coordinate). Then, each point on the list has to be connected with the previous one in a counter-clockwise fashion.

Imagine a circle defined as list of points: the top-most point (lowest Y coordinate) is number one in the list, then follows each point in a counter-clockwise fashion.

Priority goes like this:

Number 1 in list -> top-most point (lowest Y coordinate pixel)

Number n in the list -> connected to the n-1 pixel with the following priority:

1. Lower X coordinate compared to previous point
2. Higher Y coordinate compared to previous point
3. Higher X coordinate compared to previous point
4. Lower Y coordinate compared to previous point
more