I’m following a one pixel line which sometimes intersects with other lines, and I’m trying to find an elegant way to stay on the same line.

The current pixel is 0 (blue). the previous pixel is -1 (black).
In the first image there are two possible next pixels (green and red) but the green pixel (1) should be chosen because it continues the line.
In the second image there are two green pixels (1) which I’d be equally happy with – I don’t mind leaving the choice between them undefined as long as it’s not the red one.
In pseudo-cpp:
vector<Point> points;
for (i = x - 1; i < x + 2; i++) {
for (j = y - 1; j < y + 2; j++) {
if (i == x && j == y) {
continue;
}
if (IS_ON(i, j) && NOT_VISITED(i, j)) {
points.push_back(Point(i, j));
}
}
}
// sort points to find closest to opposite lastX,lastY
lastX = x;
lastY = y;
x = points[0].x;
y = points[0].y;
The sorting step is the bit I’m struggling with.
I was thinking of using std::sort but I’m having a hard time formulating the comparison function.
What would the appropriate comparison function look like, or is there a more elegant approach?
If currentP=(x,y) is your current point, lastP is the previous point, then test all possible points p by taking the dot product
and choose the p with the biggest dot product. See wikipedia for dot product.