Following a trail of pixels
in
Programming Questions
•
1 year ago
I load an image that is a simple 3 colour one:
color 0 (black) represents an empty space, 255 (white) represents a starting point for a trail and 149 (grey) represents a trail.
I scan the image at the start to find any white pixels and make an array of this amount called crayonPoints. This is a PVector that holds the position of 'crayons' and they begin on these starting points. White pixels are isolated one offs.
The image is drawn in such a way that there is always a grey pixel line leading off from these initial white pixels that makes a path. It can change direction in any of the 8 directions around the current position but never junctions. My code searches the 8 pixels around the current location (crayonPoints) and finds the next touching grey pixel. Ruling out that it is one we were already came from, or the current location, it changes the coordinates of crayonPoints to this new location. Repeating this should follow a trail.
However, what I'm experiencing is the pixels moving diagonally around the black space and then bouncing off any grey pixels they encounter:
- void searchPixelNeighbours(int i) {
- // The trail in the image is pixels of grey of value 149.
- // Search in a circle (neighbourhood) around the currentLocation
- PVector nextPoint = new PVector(0,0);
- for (int x = 0; x < 3; x++) {
- for (int y = 0; y < 3; y++) {
- int xCoord = int(crayonPoints[i].x - 1 + x);
- int yCoord = int(crayonPoints[i].y - 1 + y);
- if (previousPoints[i].x != xCoord && previousPoints[i].y != yCoord) {
- // Confirms this was not our last point. We don't want to backtrack
- if (crayonPoints[i].x != xCoord && crayonPoints[i].y != yCoord) {
- // Confirms this is not our current point.
- if (red(lightMap.pixels[(yCoord * lightMapWidth) + xCoord]) == red(149)) {
- // Next trail pixel found!
- nextPoint = new PVector(xCoord, yCoord);
- }
- }
- }
- }
- }
- previousPoints[i] = crayonPoints[i].get();
- crayonPoints[i].set(nextPoint);
- }
I'm completely stumped. I've rearranged this several times with different results but nothing close to success.
1