In [1]:
import cv2
import numpy as np
import pprint
In [2]:
w = h = 360
In [3]:
n = 6
np.random.seed(0)
pts = np.random.randint(0, w, (n, 2))
In [4]:
print(pts)
In [5]:
print(type(pts))
In [6]:
print(pts.shape)
In [7]:
img = np.zeros((w, h, 3), np.uint8)
In [8]:
for p in pts:
cv2.drawMarker(img, tuple(p), (255, 255, 255), thickness=2)
In [9]:
cv2.imwrite('data/dst/opencv_random_pts.png', img)
Out[9]:
In [10]:
rect = (0, 0, w, h)
In [11]:
subdiv = cv2.Subdiv2D(rect)
In [12]:
for p in pts:
subdiv.insert((p[0], p[1]))
In [13]:
triangles = subdiv.getTriangleList()
In [14]:
print(triangles)
In [15]:
pols = triangles.reshape(-1, 3, 2)
In [16]:
print(pols)
In [17]:
img_draw = img.copy()
cv2.polylines(img_draw, pols.astype(int), True, (0, 0, 255), thickness=2)
cv2.imwrite('data/dst/opencv_delaunay.png', img_draw)
Out[17]:
In [18]:
print(np.all(pols[:, :, 0] < w, axis=1))
In [19]:
pols_inner = pols[np.all(pols[:, :, 0] < w, axis=1) &
np.all(pols[:, :, 0] > 0, axis=1) &
np.all(pols[:, :, 1] < h, axis=1) &
np.all(pols[:, :, 1] > 0, axis=1)]
In [20]:
print(pols_inner)
In [21]:
img_draw = img.copy()
cv2.polylines(img_draw, pols_inner.astype(int), True, (0, 0, 255), thickness=2)
cv2.imwrite('data/dst/opencv_delaunay_inner.png', img_draw)
Out[21]:
In [22]:
facets, centers = subdiv.getVoronoiFacetList([])
In [23]:
pprint.pprint(facets)
In [24]:
print(centers)
In [25]:
img_draw = img.copy()
cv2.polylines(img_draw, [f.astype(int) for f in facets], True, (255, 255, 255), thickness=2)
cv2.imwrite('data/dst/opencv_voronoi.png', img_draw)
Out[25]:
In [26]:
img_draw = img.copy()
step = int(255 / len(facets))
for i, p in enumerate(f.astype(int) for f in facets):
cv2.fillPoly(img_draw, [p], (step * i, step * i, step * i))
cv2.imwrite('data/dst/opencv_voronoi_fill.png', img_draw)
Out[26]:
In [27]:
img_draw = img.copy()
step = int(255 / len(facets))
for i, p in enumerate(f.astype(int) for f in facets):
cv2.fillPoly(img_draw, [p], (step * i, step * i, step * i))
cv2.polylines(img_draw, pols_inner.astype(int), True, (0, 0, 255), thickness=2)
for c in centers:
cv2.drawMarker(img_draw, tuple(c), (255, 255, 255), thickness=2)
cv2.imwrite('data/dst/opencv_delaunay_voronoi.png', img_draw)
Out[27]: