forked from dribnet/svg-sorter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsvg-sorter.py
executable file
·240 lines (169 loc) · 4.41 KB
/
svg-sorter.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#!/usr/bin/python
# -*- coding: utf-8 -*-
# this is rather quick and dirty and it only works on svgs with straight lines
def align_left(paths, mi):
res = []
for path in paths:
res.append(path-mi)
return res
def export_svg(fn, paths, w, h, line_width=0.1):
from cairo import SVGSurface, Context
s = SVGSurface(fn, w, h)
c = Context(s)
c.set_line_width(line_width)
for path in paths:
c.new_path()
c.move_to(*path[0,:])
for p in path[1:]:
c.line_to(*p)
c.stroke()
c.save()
def export_svg_svgwrite(fn, paths, w, h, line_width=0.1):
from svgwrite import Drawing
w_str = "{}pt".format(w)
h_str = "{}pt".format(h)
dwg = Drawing(filename = fn,
size = (w_str, h_str),
viewBox=("0 0 {} {}".format(w,h)))
for path in paths:
if(len(path) > 1):
str_list = []
str_list.append("M {},{}".format(path[0,0],path[0,1]))
for e in path[1:]:
str_list.append(" L {},{}".format(e[0],e[1]))
s = ''.join(str_list)
dwg.add(dwg.path(s).stroke(color="rgb(0%,0%,0%)",width=line_width).fill("none"))
dwg.save()
def get_mid(v):
from numpy import array
mi = v.min(axis=0).squeeze()
ma = v.max(axis=0).squeeze()
midx = mi[0]+ma[0]
midy = mi[1]+ma[1]
move = array([[midx,midy]])*0.5
return mi, ma, move
def spatial_concat(paths, eps=1.e-9):
from numpy.linalg import norm
from numpy import row_stack
res = []
curr = paths[0]
concats = 0
for p in paths[1:]:
if p.shape[0]<2:
print('WARNING: path with only one vertex.')
continue
if norm(p[0,:]-curr[-1,:])<eps:
curr = row_stack([curr, p[1:,:]])
concats += 1
else:
res.append(curr)
curr = p
res.append(curr)
print('concats: ', concats)
print('original paths: ', len(paths))
print('number after concatination: ', len(res))
print()
return res
def spatial_sort(paths, init_rad=0.01):
from numpy import array
from numpy import zeros
from numpy.linalg import norm
from scipy.spatial import cKDTree as kdt
num = len(paths)
res = []
unsorted = set(range(2*num))
xs = zeros((2*num,2), 'float')
x_path = zeros(2*num, 'int')
for i, path in enumerate(paths):
xs[i,:] = path[0,:]
xs[num+i,:] = path[-1,:]
x_path[i] = i
x_path[num+i] = i
tree = kdt(xs)
count = 0
pos = array([0,0],'float')
order = []
while count<num:
rad = init_rad
while True:
near = tree.query_ball_point(pos, rad)
cands = list(set(near).intersection(unsorted))
if not cands:
rad *= 2.0
continue
dst = norm(pos - xs[cands,:], axis=1)
cp = dst.argmin()
uns = cands[cp]
break
path_ind = x_path[uns]
path = paths[path_ind]
if uns>=num:
res.append(path[::-1])
pos = paths[path_ind][0,:]
unsorted.remove(uns)
unsorted.remove(uns-num)
else:
res.append(path)
pos = paths[path_ind][-1,:]
unsorted.remove(uns)
unsorted.remove(uns+num)
order.append(path_ind)
count += 1
return res, order
def get_lines_from_svg(fn, out):
from lxml import etree
from numpy import array
res = {}
with open(fn, 'rb') as f:
tree = etree.parse(f)
root = tree.getroot()
fields = root.findall('.//{http://www.w3.org/2000/svg}line')
paths = []
print('num fields', len(fields))
for f in fields:
x1 = f.xpath('@x1').pop()
y1 = f.xpath('@y1').pop()
x2 = f.xpath('@x2').pop()
y2 = f.xpath('@y2').pop()
p = array([[x1,y1], [x2,y2]], 'float')
paths.append(p)
return paths
def main(args, **argv):
from numpy import row_stack
fn = args.fn
out = args.out
# w = 1000
# h = 1000
paths = get_lines_from_svg(fn, out)
mi, ma, move = get_mid(row_stack(paths))
paths, _ = spatial_sort(paths)
paths = spatial_concat(paths)
paths = align_left(paths, mi)
w, h = ma - mi
if args.svgwrite:
export_svg_svgwrite(out, paths, w, h, line_width=1)
else:
export_svg(out, paths, w, h, line_width=1)
# return
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'--fn',
type=str,
required=True
)
parser.add_argument(
'--out',
type=str,
required=True
)
parser.add_argument(
'--svgwrite',
default=False,
action='store_true',
help="Disable cairo and use svgwrite instead.",
required=False
)
args = parser.parse_args()
main(args)