Voronoi diagram: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
Superbatfish (talk | contribs) (→{{header|Python}}: Added alternative Python implementation, using numpy/scipy.) |
||
Line 2,090: | Line 2,090: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
This implementation takes in a list of points, each point being a tuple and returns a dictionary consisting of all the points at a given site. |
|||
<syntaxhighlight lang="python">from PIL import Image |
<syntaxhighlight lang="python">from PIL import Image |
||
import random |
import random |
||
Line 2,126: | Line 2,126: | ||
{{out}} |
{{out}} |
||
[[File:Voronoi_python.png|500px|thumb|center|Voronoi Diagram in Python]] |
[[File:Voronoi_python.png|500px|thumb|center|Voronoi Diagram in Python]] |
||
Alternatively, vectorized code leveraging numpy and scipy is 2x shorter and 10x faster: |
|||
<syntaxhighlight lang="python"> |
|||
import numpy as np |
|||
from PIL import Image |
|||
from scipy.spatial import KDTree |
|||
def generate_voronoi_diagram(X, Y, num_cells): |
|||
# Random colors and points |
|||
colors = np.random.randint((256, 256, 256), size=(num_cells, 3), dtype=np.uint8) |
|||
points = np.random.randint((Y, X), size=(num_cells, 2)) |
|||
# Construct a list of all possible (y,x) coordinates |
|||
idx = np.indices((Y, X)) |
|||
coords = np.moveaxis(idx, 0, -1).reshape((-1, 2)) |
|||
# Find the closest point to each coordinate |
|||
_d, labels = KDTree(points).query(coords) |
|||
labels = labels.reshape((Y, X)) |
|||
# Export an RGB image |
|||
rgb = colors[labels] |
|||
Image.fromarray(rgb, mode='RGB').save('VoronoiDiagram.png', 'PNG') |
|||
return rgb |
|||
</syntaxhighlight> |
|||
=={{header|QB64}}== |
=={{header|QB64}}== |