Sar*_*any 17 python xml svg xml-parsing cnc
我想使用python解析一个SVG文件来提取坐标/路径(我相信它列在"路径"ID下,特别是d ="..."/>).该数据最终将用于驱动2轴CNC.
我在SO和Google上搜索了可以返回这些路径字符串的库,以便我可以进一步解析它,但无济于事.这样的图书馆存在吗?
ick*_*fay 26
忽略转换,您可以从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()
Run Code Online (Sandbox Code Playgroud)
问题是关于提取路径字符串,但最终需要画线命令。根据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))
Run Code Online (Sandbox Code Playgroud)
获取d-string可以使用svgpathtools在一行或两行中完成.
from svgpathtools import svg2paths
paths, attributes = svg2paths('some_svg_file.svg')
Run Code Online (Sandbox Code Playgroud)
paths是svgpathtools Path对象的列表(仅包含曲线信息,没有颜色,样式等). attributes是存储每个路径的属性的相应字典对象的列表.
比方说,打印出d弦然后......
for k, v in enumerate(attributes):
print v['d'] # print d-string of k-th path in SVG
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21395 次 |
最近记录: |