使用PyGame显示Sci Py voronoi边缘会产生怪异的“星形”效果

时间:2019-03-19 01:27:29

标签: python python-2.7 numpy scipy pygame

我正在尝试使用SciPy和PyGame在我随机生成的世界地图上创建并显示Voronoi Diagram

我遇到的问题是,总有一个点具有奇怪的线条,这些线条会忽略其他任何东西,并像星星之类的东西散布在整个地图上。从左上角和左下角可以看出,它们并没有进入无限远。

我如何摆脱它?

显示内容:

enter image description here

我的代码:

import numpy
import random
import pygame
from scipy.spatial import Voronoi


def __generate_voronoi():
    """
    Randomly chooses various points within the x and y dimensions of the map.
    Then, uses SciPy to generate a voronoi diagram with them, and returns it.

    :return: SciPy voronoi diagram
    """

    point_arr = numpy.zeros([900, 2], numpy.uint16)

    for i in range(900):
        point_arr[i][0] = numpy.uint16(random.randint(0, 1600))
        point_arr[i][1] = numpy.uint16(random.randint(0, 900))

    return Voronoi(point_arr)


def draw_voronoi(pygame_surface):
    # generate voronoi diagram
    vor = __generate_voronoi()

    # draw all the edges
    for indx_pair in vor.ridge_vertices:
        start_pos = vor.vertices[indx_pair[0]]
        end_pos = vor.vertices[indx_pair[1]]

        pygame.draw.line(pygame_surface, (0, 0, 0), start_pos, end_pos)

1 个答案:

答案 0 :(得分:1)

由于这里有耐心的评论者,我了解到vor.vertices将为到达无穷大的点的第一个索引返回-1。这就产生了一个问题,因为python将-1视为列表或数组的最后一个元素的索引。

我的问题的解决方案是不从vor.vertices绘制任何索引为-1的线。

我通过用以下代码替换draw_voronoi()函数来实现了这一点:

def draw_voronoi(pygame_surface):

    # generate voronoi diagram
    vor = __generate_voronoi()

    # draw all the edges
    for indx_pair in vor.ridge_vertices:

        if -1 not in indx_pair:

            start_pos = vor.vertices[indx_pair[0]]
            end_pos = vor.vertices[indx_pair[1]]

            pygame.draw.line(pygame_surface, (0, 0, 0), start_pos, end_pos)

产生了这张图片:

enter image description here