foronoi
foronoi copied to clipboard
incorrect voronoi tiling
I noticed that sometimes my tilings are wrong and managed to get it down to a 4-point case that seems incorrect. One of the polygons it generates only has one edge.
points = [
(np.float64(20.0), np.float64(20.0)),
(np.float64(480.0), np.float64(20.0)),
(np.float64(480.0), np.float64(180.0)),
(np.float64(20.0), np.float64(180.0))
]
width = 500
height = 200
from foronoi import Polygon, Voronoi
# Create bounding polygon for the window
polygon = Polygon(
[
(0, 0),
(width, 0),
(width, height),
(0, height),
]
)
# Create Voronoi diagram
voronoi: Voronoi = Voronoi(polygon)
voronoi.create_diagram(points=points)
img = np.zeros((height, width, 3), dtype=np.uint8)
for p in points:
cv2.circle(img, (int(p[0]), int(p[1])), 1, (255, 255, 255), 3)
for i, site in enumerate(voronoi.sites):
print(i)
print(points[i])
print(site)
# Get cell vertices from the site's borders
vertices = []
for edge in site.borders():
vertex = edge.origin
vertices.append((int(vertex.x), int(vertex.y)))
print(vertices)
# I get the same results if I build vertices like this
# vertices = site.vertices()
# vertices = [(int(vertex.x), int(vertex.y)) for vertex in vertices]
# print(vertices)
if len(vertices) > 2: # Need at least 3 vertices for a polygon
next_vertices = [*vertices[1:], vertices[0]]
for v1, v2 in zip(vertices, next_vertices):
cv2.line(img, v1, v2, (255, 255, 255), 1)
imshow(img)
outputs:
0
(np.float64(20.0), np.float64(20.0))
P2
[(0, 100)]
1
(np.float64(480.0), np.float64(20.0))
P3
[(250, 100), (500, 100), (500, 0), (0, 0), (0, 100)]
2
(np.float64(480.0), np.float64(180.0))
P1
[(250, 100), (250, 200), (500, 200), (500, 100)]
3
(np.float64(20.0), np.float64(180.0))
P0
[(250, 200), (250, 100), (0, 100), (0, 200)]