Search code examples
pythonimage-processinggraph-theorypath-findingmathematical-morphology

How do I implement a Python function to find distances of all pixels from a given point along a binary mask image


Assume I have a binary image (simply represented as a 2D numpy array), with some of the pixels '1' where the mask is on and the other pixels are '0'. For example:

5x5 binary mask image

I want to find the distances from the left-bottom pixel (index [4, 0]) to all the other '1' pixels in the mask image, but the path may only travel along the mask pixels (i.e. can't cross a '0' pixel). See the origin pixel below, marked in red:

The task: find distances from the pixel marked in red

In short, I want to get the following image:

Desired output image

In which all the mask pixels are marked with their L1 minimal distance from the seed pixel. I'm planning to apply the proposed solution on images around 100x200 pixels in size.

Is there a python function (or series of functions) that implement this?

I could of course convert the image to (sparse) graph and apply shortest path algorithm. Not sure how efficient that will be.


Solution

  • I ended up using https://github.com/Forget-It-Not/Geodesic_Distance_Transform. It supports both L1 and L2 distances. The only caveat was that I had to pad the original image with one row (and column) of zeros from each side for the output to make sense.