# 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 255, 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 in opencv?

edit retag close merge delete

Sort by ยป oldest newest most voted

You want to use the distanceTransform function. It gives you the distance to the closest 0 pixel, so you'll have to pre- and post-process the image.

Pre process by copying the image as a mask, and make everything not white equal to 1 or something. Then put a single black pixel around the edges.

Post-process by getting rid of the edge and taking everything not in the mask,setting it to whatever your no good value is. -1 you say.

more

I can foresee the distanceTransform just get those straight-line distance from itself to the image edge, but actually I hope to get the travel distance something along the white pixel to image edge..But anyway, you have provided a excited idea

( 2018-01-11 21:00:17 -0500 )edit
1

From the documentation: "This means that for a pixel the function finds the shortest path to the nearest zero pixel consisting of basic shifts: horizontal, vertical, diagonal, or knight's move (the latest is available for a (5\times 5) mask). The overall distance is calculated as a sum of these basic distances."

So it does provide the path length.

( 2018-01-11 22:51:52 -0500 )edit

You need 2 point coordinates from your line or segment and your single point coordinates --> then use dot product formula to calculate the distance.

( 2018-01-12 03:42:38 -0500 )edit

I don't know how to implement it still, though I have read and understand your answer many many time. Because after I replace those non-zero pixel(a), the path will through those pixels(a). Could you help give a try?

( 2018-01-23 11:29:10 -0500 )edit

I'm not sure what you mean. Try editing the question with your code so we can see. Be sure to put a comment where you're having trouble.

( 2018-01-23 17:52:59 -0500 )edit