Skip to content

voronoi_medial

cellseg_gsontools.lines.voronoi_medial(polygon, n=None, delta=None)

Compute the medial lines of a polygon using voronoi diagram.

Parameters:

Name Type Description Default
polygon Polygon

Polygon to compute the medial lines of.

required
n int

Number of resampled points in the input polygon, defaults to None

None
delta float

Distance between resampled polygon points, defaults to None. Ignored if n is not None.

None

Returns:

Name Type Description
vertices ndarray

Array of vertices of the voronoi diagram.

edges ndarray

Array of edges of the voronoi diagram.

Source code in cellseg_gsontools/lines.py
def voronoi_medial(
    polygon: shapely.Polygon, n: int = None, delta: float = None
) -> Tuple[np.ndarray, np.ndarray]:
    """Compute the medial lines of a polygon using voronoi diagram.

    Parameters:
        polygon (shapely.geometry.Polygon):
            Polygon to compute the medial lines of.
        n (int):
            Number of resampled points in the input polygon, defaults to None
        delta (float):
            Distance between resampled polygon points, defaults to None. Ignored
            if n is not None.

    Returns:
        vertices (numpy.ndarray):
            Array of vertices of the voronoi diagram.
        edges (numpy.ndarray):
            Array of edges of the voronoi diagram.
    """
    points = equal_interval_points(polygon.exterior, n=n, delta=delta)

    # # create the voronoi diagram on 2D points
    voronoi = Voronoi(points)

    # which voronoi vertices are contained inside the polygon
    contains = vectorized.contains(polygon, *voronoi.vertices.T)

    # ridge vertices of -1 are outside, make sure they are False
    contains = np.append(contains, False)

    # make sure ridge vertices is numpy array
    ridge = np.asanyarray(voronoi.ridge_vertices, dtype=np.int64)

    # only take ridges where every vertex is contained
    edges = ridge[contains[ridge].all(axis=1)]

    # now we need to remove uncontained vertices
    contained = np.unique(edges)
    mask = np.zeros(len(voronoi.vertices), dtype=np.int64)
    mask[contained] = np.arange(len(contained))

    # mask voronoi vertices
    vertices = voronoi.vertices[contained]

    # re-index edges
    return vertices, mask[edges]