Python SVG解析器

37
我想使用Python解析SVG文件,提取坐标/路径(我相信这是在“path” ID下列出的,具体是d="..."/>)。最终将使用这些数据来驱动二轴CNC。
我已经在Stack Overflow和Google上搜索过可以返回此类路径字符串以便进一步解析的库,但没有找到。是否存在这样的库?

你也可以看一下VPYPE。无论是作为独立的命令行界面,还是可能用于代码(Python)。 - Ideogram
3个回答

42

忽略转换,您可以像这样从SVG中提取路径字符串:

from xml.dom import minidom

doc = minidom.parse(svg_file)  # parseString also exists
path_strings = [path.getAttribute('d') for path
                in doc.getElementsByTagName('path')]
doc.unlink()

2
当转换很重要时,您有什么建议吗? - Veech
1
@Veech:如果有一个变换,那么它很可能是重要的。不幸的是,处理它们需要更多的代码。 - icktoofay
2
是的,我已经意识到了。我发现cjlano的svg仓库足够好(需要进行一些修改)。 - Veech
并非每个有效的XML都是有效的SVG。 - Danon

15

使用svgpathtools可以在一两行代码中获取d字符串。

from svgpathtools import svg2paths
paths, attributes = svg2paths('some_svg_file.svg')

paths 是一个包含 SVG 路径对象的列表,其中只包含曲线信息,不包括颜色、样式等。 attributes 是一个对应列表,存储每个路径的属性字典对象。

要打印出 d-strings,则可以这样做...

for k, v in enumerate(attributes):
    print(v['d'])  # print d-string of k-th path in SVG

13

这个问题是关于提取路径字符串的,但最终需要的是线条绘制命令。根据使用minidom的答案,我添加了路径解析并使用svg.path生成线条绘制坐标:

#!/usr/bin/python3
# requires svg.path, install it like this: pip3 install svg.path

# converts a list of path elements of a SVG file to simple line drawing commands
from svg.path import parse_path
from svg.path.path import Line
from xml.dom import minidom

# read the SVG file
doc = minidom.parse('test.svg')
path_strings = [path.getAttribute('d') for path
                in doc.getElementsByTagName('path')]
doc.unlink()

# print the line draw commands
for path_string in path_strings:
    path = parse_path(path_string)
    for e in path:
        if isinstance(e, Line):
            x0 = e.start.real
            y0 = e.start.imag
            x1 = e.end.real
            y1 = e.end.imag
            print("(%.2f, %.2f) - (%.2f, %.2f)" % (x0, y0, x1, y1))

2
那就是我想要的!svg.pathsvgpathtools更易读,但svgpathtools打包得很好。 如果你想要理解如何通过SVG文件绘制曲线,那么可以阅读svg.path,但需要与svgpathtools一起使用。 - Carson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接