-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdouglasPeucker.py
116 lines (77 loc) · 2.32 KB
/
douglasPeucker.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import math
import numpy as np
def distance(p1,p2):
a = p1[0]-p2[0]
b = p1[1]-p2[1]
return math.sqrt(a*a+b*b)
def point2lineDistance(p, n1, n2):
l = distance(n1,n2)
if l == 0:
return 0.0
v1 = [n1[0]-p[0], n1[1]-p[1]]
v2 = [n2[0]-p[0], n2[1]-p[1]]
area = abs(v1[0]*v2[1]-v1[1]*v2[0])
return area/l
def douglasPeucker(node_list, e = 5):
new_list = []
if len(node_list) <= 2:
return node_list
best_i = 1
best_d = 0
for i in range(1, len(node_list)-1):
d = point2lineDistance(node_list[i], node_list[0], node_list[-1])
if d > best_d:
best_d = d
best_i = i
if best_d <= e:
return [node_list[0], node_list[-1]]
new_list = douglasPeucker(node_list[0:best_i+1], e=e)
new_list = new_list[:-1] + douglasPeucker(node_list[best_i:len(node_list)], e=e)
return new_list
def graphInsert(node_neighbor, n1key, n2key):
if n1key != n2key:
if n1key in node_neighbor:
if n2key in node_neighbor[n1key]:
pass
else:
node_neighbor[n1key].append(n2key)
else:
node_neighbor[n1key] = [n2key]
if n2key in node_neighbor:
if n1key in node_neighbor[n2key]:
pass
else:
node_neighbor[n2key].append(n1key)
else:
node_neighbor[n2key] = [n1key]
return node_neighbor
def simplifyGraph(node_neighbor, e=2.5):
new_graph = {}
visited = []
new_node_neighbor = {}
for node, node_nei in node_neighbor.items():
if len(node_nei) == 1 or len(node_nei) > 2:
if node in visited:
continue
# search node_nei
for next_node in node_nei:
if next_node in visited:
continue
node_list = [node, next_node]
current_node = next_node
while True:
if len(node_neighbor[node_list[-1]]) == 2:
if node_neighbor[node_list[-1]][0] == node_list[-2]:
node_list.append(node_neighbor[node_list[-1]][1])
else:
node_list.append(node_neighbor[node_list[-1]][0])
else:
break
for i in range(len(node_list)-1):
if node_list[i] not in visited:
visited.append(node_list[i])
# simplify node_list
new_node_list = douglasPeucker(node_list, e=e)
for i in range(len(new_node_list)-1):
new_node_neighbor = graphInsert(new_node_neighbor, new_node_list[i],new_node_list[i+1])
return new_node_neighbor