# How to get centerline of the mask images

I am working on the centerline extraction, I have tried skeletonize, RivGraph and several other methods but could not get a good centerline. First the line on the ends are not following the center and it is also shorter than the mask itself.

Here is the code that I have tried:

``````# Thresholding the mask values to binary

# Convert the grayscale image to binary image

# Perform thinning
thinned = skeletonize(img, method= 'lee')

# Get the x, y coordinates of non-zero (white) pixels
y, x = np.nonzero(thinned)
``````

``````I = imageio.v2.imread("mask.jpg")

plt.plot(coords[:,0], coords[:,1])
``````

Could anybody give me some hint?

Since your first tag is grass-gis, I suggest you try the GRASS module `v.centerline`. You'll have to perform the following steps:

1. convert the raster to a polygon vector (`r.to.vect`)
2. extract the boundary of the polygon "mask" as a line (`v.to.lines`)
3. Then try `v.centerline` on that line feature

If you encounter any problems with the above, post again with your GRASS specific code, and we'll try to help.

• Hi Micha, very much appreciated it. I will try the way you described. Right now I am trying all the methods possible in python to work this out. Commented Aug 30, 2023 at 15:03

The library pygeoops also has an implementation to calculate a centerline of a polygon: pygeoops.centerline. It also removes short branches, simplifies the result,... to get a "clean" result.

You will first need to vectorize the image, and then this sample script shows how to do it:

``````import pygeoops
import shapely

polygon = shapely.from_wkt("POLYGON ((0 0, 0 8, -2 10, 4 10, 2 8, 2 2, 10 2, 10 0, 0 0))")
centerline = pygeoops.centerline(polygon)
``````

Result:

Disclaimer: I'm the developer of pygeoops