从SVG路径采样几何点的快速方法 [英] Fast way to sample geometric points from SVG paths
问题描述
我正在使用Python 3中出色的svgpathtools
库来处理在矢量绘图应用程序中创建的SVG文件中的某些路径.
I'm using the excellent svgpathtools
library in Python 3 to work with some paths in an SVG file, created in a vector drawing application.
我想为SVG中包含的每个路径创建详细的点阵列,其中点沿路径等距.只是这样做,但是如果要获取数千个样本,速度将变得令人难以忍受.
I'd like to create detailed point arrays for each of the paths contained within the SVG, where the points are equidistant along the path. The following does just that but becomes unbearably slow if more than a few thousand samples are taken.
SAMPLES_PER_PX = 1
fname = "/path/to/file.svg"
paths, attributes = svg2paths(fname)
myPaths = {}
for path,attr in zip(paths, attributes):
myPathList = []
pathLength = path.length()
pathColour = attr['stroke']
numSamples = int(pathLength * SAMPLES_PER_PX)
for i in range(numSamples):
#parametric length = ilength(geometric length)
myPathList.append(path.point(path.ilength(pathLength * i / (numSamples-1))))
myPaths[pathColour] = np.array(myPathList)
我一直觉得我的Python不太像Python.有什么方法可以利用某些Python风格来加快速度吗?
I've always felt that my Python ain't very Pythonic. Is there a way I can take advantage of some Python-ness to speed this up?
推荐答案
我遇到了同样的问题.我的解决方案是使用path.point
采样N个点,然后使用scipy样条对这些点进行插值,然后从样条中重新采样.像这样:
I had the same problem. My solution was to sample N points using path.point
and then interpolate those points using scipy spline and resample from the spline. Something like:
tck, _ = interpolate.splprep(pts, s=0)
result = interpolate.splev(np.linspace(0, 1, 1000), tck)
其中pts
是采样点的列表.数字N取决于输入曲线的不均匀程度.通常N = 20足以应付不太疯狂的情况:-)
Where pts
is a list of sampled points. The number N depends on how non-uniform the input curve is. Usually N=20 is sufficient for not too crazy cases:-)
这篇关于从SVG路径采样几何点的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!