Demonstrate how to generate and display a Voronoi diagram in Python.

Hint 1
Generate a list of points, with each point being a tuple and then return a dictionary consisting of all the points at a given site.

Solution
  • from PIL import Image
    import random
    import math
    
    def generate_voronoi_diagram(width, height, num_cells):
      image = Image.new("RGB", (width, height))
      putpixel = image.putpixel
      imgx, imgy = image.size
      nx = []
      ny = []
      nr = []
      ng = []
      nb = []
      for i in range(num_cells):
        nx.append(random.randrange(imgx))
        ny.append(random.randrange(imgy))
        nr.append(random.randrange(256))
        ng.append(random.randrange(256))
        nb.append(random.randrange(256))
      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()
    
    generate_voronoi_diagram(500, 500, 25)
  • URL:
  • Language: English
  • Subjects: Computer Science Computer Graphics
  • Type: Name
  • Duration: 30min
  • Credits: 5
  • Difficulty: 0.4
  • Tags: voronoi diagram geometry
  • Note:
    Check out https://rosettagit.org/tasks/voronoi-diagram for solutions in other programming languages.
  • Created By: adius
  • Created At:
    2020-03-24 21:12:23 UTC
  • Last Modified:
    2020-03-24 21:12:23 UTC