Delaunay Triangulation 是一種空間劃分的方法,它能使得分割形成的三角形最小的角盡可能的大尖殃,關(guān)于 Delaunay Triangulation 的詳細(xì)介紹丈莺,請(qǐng)參考這里,Delaunay Triangulation在很多領(lǐng)域都有應(yīng)用分衫,科學(xué)計(jì)算領(lǐng)域它是有限元和有限體積法劃分網(wǎng)格的重要方法场刑,除此之外在圖像識(shí)別、視覺藝術(shù)等領(lǐng)域也有它的身影蚪战。
貼一段有趣的油管視頻牵现,用 Delaunay Triangulation 進(jìn)行人臉識(shí)別的演示:Delaunay Triangulation and Voronoi Diagram in OpenCV
接下來(lái)寫一下怎么用 Python 實(shí)現(xiàn) Delaunay Triangulation,需要用到的模塊有Numpy
, Matplotlib
和 Scipy
邀桑,基本的思路是隨機(jī)制造幾個(gè)點(diǎn)瞎疼,然后利用scipy.spatial.Delaunay
對(duì)這些點(diǎn)進(jìn)行處理配對(duì)三角形,最后用matplotlib
的tripcolor
(填充三角形顏色壁畸,如果不需要填充顏色贼急,可以用triplot
).
下面貼上代碼:
from scipy.spatial import Delaunay
import numpy as np
import matplotlib.pyplot as plt
# Triangle Settings
width = 200
height = 40
pointNumber = 1000
points = np.zeros((pointNumber, 2))
points[:, 0] = np.random.randint(0, width, pointNumber)
points[:, 1] = np.random.randint(0, height, pointNumber)
# Use scipy.spatial.Delaunay for Triangulation
tri = Delaunay(points)
# Plot Delaunay triangle with color filled
center = np.sum(points[tri.simplices], axis=1)/3.0
color = np.array([(x - width/2)**2 + (y - height/2)**2 for x, y in center])
plt.figure(figsize=(7, 3))
plt.tripcolor(points[:, 0], points[:, 1], tri.simplices.copy(), facecolors=color, edgecolors='k')
# Delete ticks, axis and background
plt.tick_params(labelbottom='off', labelleft='off', left='off', right='off',
bottom='off', top='off')
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['top'].set_color('none')
# Save picture
plt.savefig('Delaunay.png', transparent=True, dpi=600)
貼上結(jié)果:
來(lái)自fangs.in