将Voronoi图渲染为NumPy数组

4
我希望能够基于一组中心点和图像大小生成泰森多边形区域。
我尝试了下面的代码,基于https://rosettacode.org/wiki/Voronoi_diagram
def generate_voronoi_diagram(width, height, centers_x, centers_y):
    image = Image.new("RGB", (width, height))
    putpixel = image.putpixel
    imgx, imgy = image.size
    num_cells=len(centers_x)
    nx = centers_x
    ny = centers_y
    nr,ng,nb=[],[],[]
    for i in range (num_cells):
        nr.append(randint(0, 255));ng.append(randint(0, 255));nb.append(randint(0, 255));

    for y in range(imgy):
        for x in range(imgx):
            dmin = math.hypot(imgx-1, imgy-1)
            j = -1
            for i in range(num_cells):
                d = math.hypot(nx[i]-x, ny[i]-y)
                if d < dmin:
                    dmin = d
                    j = i
            putpixel((x, y), (nr[j], ng[j], nb[j]))
    image.save("VoronoiDiagram.png", "PNG")
    image.show()

我有所需的输出:

enter image description here

但生成输出需要太多时间。
我也尝试过https://dev59.com/HWIj5IYBdhLWcg3wMinW#20678647,它很快,但我没有找到将其转换为img_width X img_height的numpy数组的方法。主要是因为我不知道如何给scipy Voronoi class传递图像大小参数。
是否有更快的方法来获得此输出? 不需要中心或多边形边缘。
提前感谢。
编辑2018-12-11: 使用@tel“快速解决方案”。

enter image description here

代码执行更快了,似乎中心已经被转换了。可能这种方法在图像上添加了一个边距。

1
也许编译它? - Walter Tross
这是一个非常慢的算法,使用非常慢的语言。请参见 https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.spatial.Voronoi.html 以计算 Voronoi,以及 https://matplotlib.org/api/_as_gen/matplotlib.pyplot.fill.html 以生成图像。 - B. M.
2个回答

6

快速解决方案

这是您可以将您链接的基于 scipy.spatial.Voronoi快速解决方案的输出转换为任意宽度和高度的 Numpy 数组的方法。给定从链接代码中 voronoi_finite_polygons_2d 函数得到的 regions, vertices 集合,以下是一个辅助函数,将该输出转换为数组:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas

def vorarr(regions, vertices, width, height, dpi=100):
    fig = plt.Figure(figsize=(width/dpi, height/dpi), dpi=dpi)
    canvas = FigureCanvas(fig)
    ax = fig.add_axes([0,0,1,1])

    # colorize
    for region in regions:
        polygon = vertices[region]
        ax.fill(*zip(*polygon), alpha=0.4)

    ax.plot(points[:,0], points[:,1], 'ko')
    ax.set_xlim(vor.min_bound[0] - 0.1, vor.max_bound[0] + 0.1)
    ax.set_ylim(vor.min_bound[1] - 0.1, vor.max_bound[1] + 0.1)

    canvas.draw()
    return np.frombuffer(canvas.tostring_rgb(), dtype='uint8').reshape(height, width, 3)

测试一下

这是一个完整的vorarr示例:

from scipy.spatial import Voronoi

# get random points
np.random.seed(1234)
points = np.random.rand(15, 2)

# compute Voronoi tesselation
vor = Voronoi(points)

# voronoi_finite_polygons_2d function from https://dev59.com/HWIj5IYBdhLWcg3wMinW#20678647
regions, vertices = voronoi_finite_polygons_2d(vor)

# convert plotting data to numpy array
arr = vorarr(regions, vertices, width=1000, height=1000)

# plot the numpy array
plt.imshow(arr)

输出:

enter image description here

正如您所见,生成的Numpy数组确实具有(1000, 1000)的形状,与对vorarr的调用中指定的一样。

如果你想改进你现有的代码

以下是如何修改您当前的代码以使用/返回Numpy数组:

import math
import matplotlib.pyplot as plt
import numpy as np

def generate_voronoi_diagram(width, height, centers_x, centers_y):
    arr = np.zeros((width, height, 3), dtype=int)
    imgx,imgy = width, height
    num_cells=len(centers_x)

    nx = centers_x
    ny = centers_y

    randcolors = np.random.randint(0, 255, size=(num_cells, 3))

    for y in range(imgy):
        for x in range(imgx):
            dmin = math.hypot(imgx-1, imgy-1)
            j = -1
            for i in range(num_cells):
                d = math.hypot(nx[i]-x, ny[i]-y)
                if d < dmin:
                    dmin = d
                    j = i
            arr[x, y, :] = randcolors[j]

    plt.imshow(arr.transpose(1, 0, 2))
    plt.scatter(cx, cy, c='w', edgecolors='k')
    plt.show()
    return arr

示例用法:

np.random.seed(1234)

width = 500
cx = np.random.rand(15)*width

height = 300
cy = np.random.rand(15)*height

arr = generate_voronoi_diagram(width, height, cx, cy)

示例输出:

在此输入图片描述


非常感谢 @tel!我喜欢你的解决方案,但是看起来中心位置已经被缩小了。我附上了你的解决方案输出及其中心位置以及原始的中心位置。也许是 matplotlib 添加了边距? - virilo

2

不使用matplotlib也可以快速解决问题。你的解决方案很慢,因为你在迭代所有像素,这会在Python中产生很多开销。解决这个问题的简单方法是通过单个numpy操作计算所有距离,并通过另一个单个操作分配所有颜色。

def generate_voronoi_diagram_fast(width, height, centers_x, centers_y):
    # Create grid containing all pixel locations in image
    x, y = np.meshgrid(np.arange(width), np.arange(height))

    # Find squared distance of each pixel location from each center: the (i, j, k)th
    # entry in this array is the squared distance from pixel (i, j) to the kth center.
    squared_dist = (x[:, :, np.newaxis] - centers_x[np.newaxis, np.newaxis, :]) ** 2 + \
                   (y[:, :, np.newaxis] - centers_y[np.newaxis, np.newaxis, :]) ** 2
    
    # Find closest center to each pixel location
    indices = np.argmin(squared_dist, axis=2)  # Array containing index of closest center

    # Convert the previous 2D array to a 3D array where the extra dimension is a one-hot
    # encoding of the index
    one_hot_indices = indices[:, :, np.newaxis, np.newaxis] == np.arange(centers_x.size)[np.newaxis, np.newaxis, :, np.newaxis]

    # Create a random color for each center
    colors = np.random.randint(0, 255, (centers_x.size, 3))

    # Return an image where each pixel has a color chosen from `colors` by its
    # closest center
    return (one_hot_indices * colors[np.newaxis, np.newaxis, :, :]).sum(axis=2)

在我的机器上运行此函数,相对于原始的迭代解决方案(不考虑绘图和将结果保存到磁盘中),可以获得约10倍的加速。我相信还有许多其他调整可以进一步加快我的解决方案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接