将Voronoi图渲染为numpy数组

时间:2018-12-09 21:34:23

标签: python numpy scipy voronoi

我想根据中心列表和图像尺寸生成Voronoi区域。

我尝试了基于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://stackoverflow.com/a/20678647 它很快,但是我没有找到将其转换为img_width X img_height的numpy数组的方法。通常是因为我不知道如何将图像大小参数赋予scipy Voronoi class

有没有更快的方法来获得此输出?不需要中心或多边形边缘

预先感谢

编辑2018-12-11: 使用@tel“快速解决方案”

enter image description here

代码执行速度更快,似乎中心已经转换。可能是这种方法会在图片上添加边距

2 个答案:

答案 0 :(得分:4)

快速解决方案

这是将链接到的fast solution based on scipy.spatial.Voronoi的输出转换为任意宽度和高度的Numpy数组的方法。给定您从链接代码中的regions, vertices函数的输出中获得的voronoi_finite_polygons_2d的集合,以下是一个辅助函数,该函数会将输出转换为数组:

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://stackoverflow.com/a/20678647/425458
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

如您所见,根据对(1000, 1000)的调用所指定的,所得的Numpy数组确实具有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))
    imgx,imgy = width, height
    num_cells=len(centers_x)

    nx = centers_x
    ny = centers_y
    nr = list(range(num_cells))
    ng = nr
    nb = nr

    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, :] = (nr[j], ng[j], nb[j])

    plt.imshow(arr.astype(int))
    plt.show()
    return arr

答案 1 :(得分:1)

也可以使用不使用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倍的加速(不考虑绘图并将结果保存到磁盘)。我确信还有很多其他调整可以进一步加快我的解决方案的速度。