You may use the Dynamic Programming approach as utilized in Seam Carving for Content Aware Image Resizing.
Just replace their weights with yours.
Julia Implementation
I implemented the idea of looking for the longest chain using dynamic programming.
This is the input image:
We have 3 values: Blue -> Edges of 0
, Green -> Background
and Yellow -> Edges of 255
.
We need to work on each on itself.
For instance, this is the image of the 0
edges:
Now, using the dynamic programming based algorithm we can build the path.
The idea is very simple, per pixel we look at row above it in its 8 connected neighborhood. We find the maximum and keep the value and the direction. We add the value to the values accumulated until this step.
mS[ii - 1, jj - 1] mS[ii - 1, jj] mS[ii - 1, jj + 1]
↖ ↑ ↗
mS[ii, jj]
For the case above the result is:
↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
↑↖↖↖↖↗↑↖↖↖↖↗↑↖↖↖↖↖↖↖↖↖↗↑↖↖↖↖↖↖
↑↖↖↖↗↑↖↖↖↖↗↗↑↖↖↖↖↖↖↖↖↗↑↗↑↖↖↖↖↖
↑↖↖↗↑↖↖↖↖↖↗↑↖↖↖↖↖↖↖↖↗↑↗↑↗↑↖↖↖↖
↑↖↖↖↖↖↖↖↖↗↗↑↖↖↖↖↖↖↖↗↑↖↑↗↑↗↑↖↖↖
↑↖↖↖↖↖↖↖↗↗↗↑↖↖↖↖↖↖↗↑↗↑↖↑↗↗↑↖↖↖
↑↖↖↖↖↖↖↗↗↗↗↑↖↖↖↖↖↖↑↗↗↑↖↗↗↗↑↖↖↖
↑↖↖↖↖↖↗↗↗↗↗↑↖↖↖↖↖↖↗↗↗↑↖↗↗↑↖↖↖↖
↑↖↖↖↖↖↗↗↗↗↑↗↑↖↖↖↖↑↖↗↗↑↖↗↗↑↖↖↖↖
↑↖↖↖↖↖↗↑↗↑↗↗↑↖↖↖↖↖↗↗↗↑↖↗↗↑↖↖↖↖
↑↖↖↖↖↖↑↗↑↖↗↗↑↖↖↖↖↖↗↗↑↖↗↗↗↑↖↖↖↖
↑↖↖↖↖↖↗↑↖↗↗↑↖↖↖↖↖↖↗↑↖↗↗↗↑↖↖↖↖↖
↑↖↖↖↖↗↑↖↗↗↑↖↖↖↖↖↖↖↖↖↗↗↗↑↖↖↖↖↖↖
↑↖↖↖↗↑↖↗↗↗↑↖↖↖↖↖↖↖↖↗↗↗↑↖↖↖↖↖↖↖
↑↖↖↗↑↖↗↗↗↑↗↑↖↖↖↖↖↖↖↗↗↑↖↖↖↖↖↖↖↖
↑↖↗↑↖↗↗↗↑↗↗↑↖↖↖↖↖↑↖↖↑↖↖↖↖↖↖↗↑↖
↑↗↑↖↗↗↗↑↗↗↗↑↖↖↖↖↗↑↖↖↖↖↖↖↖↖↗↗↑↖
↗↑↖↗↗↗↑↗↗↗↑↖↖↖↖↖↖↗↑↖↖↖↖↖↖↗↗↗↑↖
↑↖↗↗↗↑↗↗↗↑↖↖↖↖↖↖↖↗↑↖↖↖↖↖↗↗↗↗↑↖
↑↗↗↗↑↗↗↗↗↑↖↖↖↗↑↖↖↖↖↖↖↖↖↗↗↗↗↗↑↖
↗↗↗↑↗↗↗↗↑↗↑↖↖↑↗↑↖↖↖↗↑↖↖↗↗↗↗↑↖↖
↗↗↑↗↗↗↗↑↗↑↖↖↖↗↗↑↖↖↖↗↑↖↖↖↗↗↑↖↖↖
↗↑↗↗↗↗↑↗↑↗↑↖↖↖↗↑↖↖↖↗↑↖↖↖↗↑↖↖↖↖
↑↗↗↗↗↑↗↑↗↗↑↖↖↗↑↗↑↖↖↖↑↖↖↖↖↖↖↖↖↖
↗↗↗↗↑↗↑↗↗↗↑↖↖↖↗↗↑↖↖↖↗↑↖↖↖↖↖↖↖↖
↗↗↗↑↗↑↗↗↗↑↖↖↖↖↗↑↖↖↖↖↗↑↖↖↖↖↖↖↖↖
↗↗↑↗↑↗↗↗↑↖↖↖↗↑↖↖↗↑↖↖↖↑↖↖↖↖↖↖↖↖
↗↑↗↑↗↗↗↑↖↖↖↗↗↑↖↖↗↑↖↖↖↑↖↖↖↖↖↖↖↖
↑↗↑↗↗↗↑↖↗↑↖↗↗↑↖↖↗↑↖↖↖↑↖↖↖↖↖↖↖↖
↗↑↗↗↗↑↖↗↗↑↖↗↗↑↖↖↗↑↖↖↖↑↖↖↖↖↖↖↖↖
↑↗↗↗↑↖↗↗↑↗↑↗↑↖↖↖↗↑↖↖↖↑↖↖↖↖↖↖↖↖
↗↗↗↑↖↗↗↑↗↗↑↖↖↖↖↖↖↗↑↖↖↖↖↖↖↖↖↖↖↖
↗↗↑↖↗↗↑↗↗↗↑↖↖↗↑↖↗↗↑↖↖↖↖↖↖↖↖↖↖↖
↗↑↖↗↗↑↗↗↗↑↖↖↖↖↖↖↗↑↖↖↖↖↖↖↖↖↖↖↖↖
With the chosen path being:
The binary image for the edges of 255
:
The path of the edges of 255
:
It looks like the method is working for your case.
The code is available at my StackExchange Codes Signal Processing GitHub Repository (Look at the SignalProcessing\Q88303
folder).