# How to calculate the distance that from the pixel to image edges

I have such image: It is a binary image, I mean the pixel value is 0 or 1, but now, I hope to replace every pixel value with its distance from self to the image edges(edge can be one of the top edge, bottom edge, left edge or right edge), but I don't care the distance is shortest or not. Such as the following red pixel, which have two or more paths to image edges. We can use any distance to replace its pixel value. When the pixel have no any path to the image edge, I will replace the pixel value with -1. Is there any efficient method can implement this target? Sorry for no try but just a question. It seem it is hard to me. Can anyone give me some advice to do it?

You can use graph tools for this. Take a small part of your image for an example:

small = ImageTake[img, {500, 600}, {50, 100}] extract white pixels:

whitepix =
Position[Round[ImageData[ColorConvert[small, "Grayscale"]]], 1];


near = Nearest[whitepix -> Range@Length@whitepix]
edges = DeleteCases[
Union[Sort /@
Flatten[Function[{i}, {{i, #} & /@
near[whitepix[[i]], {9, 1}]}] /@  (*make {9,Sqrt} to take diagonals*)
Range[Length@whitepix] , 2]], {i_, i_}];


now make a graph:

g = Graph[Range[Length@whitepix], UndirectedEdge@@@ edges,
VertexCoordinates -> Reverse /@ whitepix, EdgeStyle -> Gray] now we can find shortest paths point to point: (here i just manually identified an edge point 237 , and pick another point at random)

HighlightGraph[g, PathGraph[FindShortestPath[g, 400, 237]],
EdgeStyle -> {Thick, Red}] the distance is simply: GraphDistance[g, 400, 237] (*64*)

works well on the whole image.. • I cannot imagine it will cost how much time to replace all white pixel vlaue.
– yode
Jan 12, 2018 at 19:16
• @yode FindShortestPath is actually surprisingly fast. This will take some hours I suppose but its not intractable. Jan 12, 2018 at 19:41

I am not exactly sure what it mean by distance to image edges but here's the first step you can try.

bimg = Binarize[img];

g = GridGraph[ImageDimensions[bimg]];

sa = SparseArray[ImageData[bimg]];

dim = Dimensions[sa];

vindex[i_, j_, h_] := (i - 1) h + j

vind = Flatten[
Table[vindex[i, #, dim[]] & /@ alist[[i]], {i, 1,
Length[alist]}]];

pixelgraph =
Subgraph[g, vind, VertexCoordinates -> GraphEmbedding[g][[vind]]];


This is a large graph so I just plot vertex coordinates to see it works:

Graphics[Point[GraphEmbedding[pixelgraph]]] Now you can compute the distance using a pixelgraph and then mapping back vertex index (with distance) to position of ImageData matrix.

• The four margins of image.
– yode
Jan 11, 2018 at 19:10
• Do you have any comments on this? Do you see any errors in the code? I tried to document it so people wouldn't have to rely on reading the code only. Do you see any simple ways to significantly improve performance? Currently, this function is suitable for interactive use, but it is not fast enough to put it in a loop. Jan 17, 2018 at 13:18