对标记点进行三角化
《Python計算機視覺編程》(《Programming Computer Vision with Python》)一書的第三章第二節分段仿射扭曲一節中,使用狄洛克三角剖分方法時提示錯誤
ModuleNotFoundError: No module named ‘matplotlib.delaunay’
即,matplotlib庫中已經不再支持delaunay模塊了。所以我們需要尋找一個別的模塊來代替它。我在網上找到了from scipy.spatial import Delaunay 這個方法,scipy庫中依然保留有這個模塊,所以可以用scipy庫來代替matplotlib這個庫。
具體實現函數如下:(取自網絡)
輸出結果:
這個版本的代碼添加了將三角形內部填充上顏色的過程。這個過程可以省略。所以代碼可修剪為:
結果如圖:
如果你想要得到和書中例子類似的圖片,只需要將上面的代碼中隨機取值部分更改為正態分布隨機取值就可以了,修改后代碼如下:
from scipy.spatial import Delaunay import numpy as np import matplotlib.pyplot as plt# Triangle Settings pointNumber = 100 points = np.zeros((pointNumber, 2)) x, y = np.random.standard_normal((2, pointNumber)) points[:, 0] = x points[:, 1] = y# 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 plt.figure(figsize=(7, 3)) plt.triplot(points[:, 0], points[:, 1], tri.simplices.copy())# 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')plt.show()結果為:
本文基于python3+win10環境。
總結
- 上一篇: python numpy库中省略号...
- 下一篇: pygame.mixer.Sound()