我想使用 python 解析 SVG 文件以提取坐标/路径(我相信这列在“路径”ID 下,特别是 d="..."/>)。该数据最终将用于驱动 2 轴 CNC。
我在 SO 和 Google 上搜索了可以返回此类路径字符串的库,以便我可以进一步解析它,但无济于事。有这样的图书馆吗?
我想使用 python 解析 SVG 文件以提取坐标/路径(我相信这列在“路径”ID 下,特别是 d="..."/>)。该数据最终将用于驱动 2 轴 CNC。
我在 SO 和 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()
获取 d-string 可以使用svgpathtools在一两行中完成。
from svgpathtools import svg2paths
paths, attributes = svg2paths('some_svg_file.svg')
路径是 svgpathtools 路径对象的列表(仅包含曲线信息,没有颜色、样式等)。 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))