【问题标题】:clipping a voronoi diagram python剪裁voronoi图python
【发布时间】:2016-07-03 23:27:06
【问题描述】:

我正在从一组点计算 voronoi 图,如下所示:

from scipy.spatial import Voronoi
import numpy as np


np.random.seed(0)
points = np.random.uniform(-0.5, 0.5, (100, 2))
# Compute Voronoi
v = Voronoi(points)
voronoi_plot_2d(v)
plt.show()

这将创建如下图像:

正如人们所看到的,这是创建无穷大的顶点(虚线),并且超出了点的原始边界框:

 bbox = np.array([[-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]])

我想做的是将 voronoi 图剪辑到这个边界框,即将边界和无限顶点投影到这个边界框上的适当位置。因此,顶点需要重新排列并从无穷大或有限顶点投影回正确的交点,但这些顶点超出了我的剪辑区域的范围。

【问题讨论】:

  • @unutbu 虽然可以从“Colorize Voronoi Diagram”的链接中获得答案似乎是真的,但从我的角度来看,这种关系并不直接或明显。卢卡早些时候提出了一个类似的问题,当时我解释说他只想要边界框内的顶点(我当时的回答是这样)。这次他似乎想要边界框和 Voronoi 的无限区域之间的截取点。不一定出于情节目的。我不认为这是重复的。
  • 是的,它是以某种方式在具有边界和无限顶点的 voronoi 平面与[[-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]] 给出的边界框之间产生交集。我不确定其他代码是否正在这样做......我现在正在查看它。
  • 我不确定是否有更直接的方法,但请查看两行交叉的代码(例如:stackoverflow.com/questions/20677795/…)。显然,您必须对进入无限区域的每个顶点执行此操作。
  • 只是提到我写了一个你想要的 C++ 版本,它是可用的here。这还包含一个cgal-swig-bindings 的用户包,因此 python 版本可能并不难拥有(尽管我只是努力使其适用于 java)。
  • Here's 一个类似(重复?)的问题和答案

标签: python scipy computational-geometry spatial voronoi


【解决方案1】:

使用Shapely 可以轻松完成。您可以从 Conda Forge 安装它:conda install shapely -c conda-forge

github.gist 需要的代码,基于@Gabriel and @pv. 的回答:

# coding=utf-8
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi
from shapely.geometry import Polygon

def voronoi_finite_polygons_2d(vor, radius=None):
    """
    Reconstruct infinite voronoi regions in a 2D diagram to finite
    regions.
    Parameters
    ----------
    vor : Voronoi
        Input diagram
    radius : float, optional
        Distance to 'points at infinity'.
    Returns
    -------
    regions : list of tuples
        Indices of vertices in each revised Voronoi regions.
    vertices : list of tuples
        Coordinates for revised Voronoi vertices. Same as coordinates
        of input vertices, with 'points at infinity' appended to the
        end.
    """

    if vor.points.shape[1] != 2:
        raise ValueError("Requires 2D input")

    new_regions = []
    new_vertices = vor.vertices.tolist()

    center = vor.points.mean(axis=0)
    if radius is None:
        radius = vor.points.ptp().max()*2

    # Construct a map containing all ridges for a given point
    all_ridges = {}
    for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices):
        all_ridges.setdefault(p1, []).append((p2, v1, v2))
        all_ridges.setdefault(p2, []).append((p1, v1, v2))

    # Reconstruct infinite regions
    for p1, region in enumerate(vor.point_region):
        vertices = vor.regions[region]

        if all(v >= 0 for v in vertices):
            # finite region
            new_regions.append(vertices)
            continue

        # reconstruct a non-finite region
        ridges = all_ridges[p1]
        new_region = [v for v in vertices if v >= 0]

        for p2, v1, v2 in ridges:
            if v2 < 0:
                v1, v2 = v2, v1
            if v1 >= 0:
                # finite ridge: already in the region
                continue

            # Compute the missing endpoint of an infinite ridge

            t = vor.points[p2] - vor.points[p1] # tangent
            t /= np.linalg.norm(t)
            n = np.array([-t[1], t[0]])  # normal

            midpoint = vor.points[[p1, p2]].mean(axis=0)
            direction = np.sign(np.dot(midpoint - center, n)) * n
            far_point = vor.vertices[v2] + direction * radius

            new_region.append(len(new_vertices))
            new_vertices.append(far_point.tolist())

        # sort region counterclockwise
        vs = np.asarray([new_vertices[v] for v in new_region])
        c = vs.mean(axis=0)
        angles = np.arctan2(vs[:,1] - c[1], vs[:,0] - c[0])
        new_region = np.array(new_region)[np.argsort(angles)]

        # finish
        new_regions.append(new_region.tolist())

    return new_regions, np.asarray(new_vertices)

# make up data points
np.random.seed(1234)
points = np.random.rand(15, 2)

# compute Voronoi tesselation
vor = Voronoi(points)

# plot
regions, vertices = voronoi_finite_polygons_2d(vor)

min_x = vor.min_bound[0] - 0.1
max_x = vor.max_bound[0] + 0.1
min_y = vor.min_bound[1] - 0.1
max_y = vor.max_bound[1] + 0.1

mins = np.tile((min_x, min_y), (vertices.shape[0], 1))
bounded_vertices = np.max((vertices, mins), axis=0)
maxs = np.tile((max_x, max_y), (vertices.shape[0], 1))
bounded_vertices = np.min((bounded_vertices, maxs), axis=0)



box = Polygon([[min_x, min_y], [min_x, max_y], [max_x, max_y], [max_x, min_y]])

# colorize
for region in regions:
    polygon = vertices[region]
    # Clipping polygon
    poly = Polygon(polygon)
    poly = poly.intersection(box)
    polygon = [p for p in poly.exterior.coords]

    plt.fill(*zip(*polygon), alpha=0.4)

plt.plot(points[:, 0], points[:, 1], 'ko')
plt.axis('equal')
plt.xlim(vor.min_bound[0] - 0.1, vor.max_bound[0] + 0.1)
plt.ylim(vor.min_bound[1] - 0.1, vor.max_bound[1] + 0.1)

plt.savefig('voro.png')
plt.show()

【讨论】:

    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 2010-10-24
    • 2022-01-23
    • 2015-02-02
    相关资源
    最近更新 更多