我想使用Python解析SVG文件,提取坐标/路径(我相信这是在“path” ID下列出的,具体是d="..."/>)。最终将使用这些数据来驱动二轴CNC。
我已经在Stack Overflow和Google上搜索过可以返回此类路径字符串以便进一步解析的库,但没有找到。是否存在这样的库?
我已经在Stack Overflow和Google上搜索过可以返回此类路径字符串以便进一步解析的库,但没有找到。是否存在这样的库?
忽略转换,您可以像这样从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()
使用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
这个问题是关于提取路径字符串的,但最终需要的是线条绘制命令。根据使用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))
svg.path
比svgpathtools
更易读,但svgpathtools
打包得很好。
如果你想要理解如何通过SVG文件绘制曲线,那么可以阅读svg.path
,但需要与svgpathtools
一起使用。 - Carson