Delaunay三角Python实现初探

Delaunay三角Python实现初探

  好久没写代码了,真是恍如隔世啊。

起因

  放假前几天,老板让师弟研究一下Delaunay三角的画法,鉴于俺当时实在摸鱼摸出贤者时间了,就主动揽过了这个活。

过程

  首先去网上找轮子,果不其然有个轮子,但是老板有一些需求,接下来是探索过程。

上色标准

  首先是希望颜色分布按三角形面积大小来排列。将原轮子稍加改动,替换求面积公式:s = 0.5*abs(x1*y2+x2*y3+x3*y1-x1*y3-x2*y1-x3*y2)

配色方案

  plt.cm.get_cmap函数能使用配色方案,在可以选择预设的方案。

解决不了的问题

  右边刻度没法准确操控,即无法自定义分布区间,待俺有空再研究研究。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from scipy.spatial import Delaunay
import matplotlib as mpl
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

# parameters
width = 80
height = 40

def getDelaunay(data,pointNumber):
points = np.zeros((pointNumber, 2))
points[:, 0] = data["X"]
points[:, 1] = data["Y"]
tri = Delaunay(points)

color = []
for index, sim in enumerate(points[tri.simplices]):
x1, y1 = sim[0][0], sim[0][1]
x2, y2 = sim[1][0], sim[1][1]
x3, y3 = sim[2][0], sim[2][1]
s = 0.5*abs(x1*y2+x2*y3+x3*y1-x1*y3-x2*y1-x3*y2)
color.append(s)
color = np.array(color)
areas = pd.DataFrame(color)
areas.to_excel("areas.xlsx")

fig, ax = plt.subplots(figsize=(20,10))
cmap = plt.cm.get_cmap('Pastel1')
delu = plt.tripcolor(points[:, 0], points[:, 1], tri.simplices.copy(), cmap=cmap, facecolors=color, edgecolors='r')
cb = fig.colorbar(delu)
cb.update_normal(delu)
ax = plt.gca()
plt.scatter(points[:,0],points[:,1], color='w')
ax.set_title('Title test',fontsize=20)
ax.set_xlabel('Xlabel test',fontsize=20)
ax.set_ylabel('Ylabel test',fontsize=20)
plt.savefig('Delaunay.png', transparent=True, dpi=600)


if __name__ == '__main__':
data = pd.read_excel('Results.xlsx')
pointNumber = len(data)
getDelaunay(data,pointNumber)

参考

python 实现德洛内三角剖分

评论