Your algorithm allows the whole image, with the exception of one pixel, to be a "path". I'm not sure exactly what you want; usually the outline is the boundary between two different regions. The problem with your method is that you can get huge pixels of pixels that do not have a particularly obvious traversal order. If you have a path that is one pixel thick, then the traversal order is much more obvious: clockwise or counterclockwise.
Consider the following image.
........ ..%%%%.. .%%%%... ...%%%%. ....%... ........
Here I marked all the "dark" (<50, maybe) as % and all bright as . . Now you can select any pixel that is on the border between the two regions (I will choose the dark side, you can also draw an outline on the light side or with a little more work, right between the light and dark sides.)
........ ..%%%%.. .*%%%... ...%%%%. ....%... ........
Now you are trying to move around the outer edge of the dark area, one pixel at a time. Firstly, you are looking towards something bright (right on the left, for example). Then you spin around - counterclockwise, let them say - until you click on the dark pixel.
........ ..%%%%.. 1*5%%... 234%%%%. ....%... ........
As soon as you press position 5 , you will see that it is dark. So you mark it as part of the path, and then try to find the next fragment on the path by expanding it starting from the pixel that you just came from
........ ..%%%%.. .0*%%... .123%%%. ....%... ........
Here is 0 , where you came from, and you won’t return there, and then you try pixels 1 and 2 (both lights, which is not entirely normal) until you click on pixel 3 , which is dark.
That way, you can move around the pixels of the path by the pixels — both identify the path and get the order of the pixels — until you come across the same pixel that you started at and walk away from it so that you hit the same pixel that you did the first time you left it. Then the circuit is closed. In our example, where we create an 8-connected contour (i.e., we look at 8 neighbors, not 4), we get the following (where @ denotes a contour point).
........ ..@ @@@.. .@ @%@... ...@ %@@. ....@... ........
(You must have this “two in a row” criterion, or if you have a dark area one pixel wide, you will go up and then you cannot go down it).
At this point, you have covered one whole border. But there may be others. Keep looking for dark pixels next to bright ones until you draw an outline on top of all of them. Now you have converted a two-level image (dark and bright pixels) into a set of outlines.
If the contours are too noisy, try blurring the image first. This will smooth out the contours. (Alternatively, you can first find the contours, and then average the coordinates using a moving window.)