简体   繁体   English

使用 Python 解析 SVG 文件路径

[英]Parsing SVG file paths with Python

I am working on a robotic project that from an Android running device take a picture then send to cloudconvert.org to convert it into an SVG, then all SVG paths will be translated into xy coordinates and serially send to the robotic arm which will plot them with the pen on or off.我正在开发一个机器人项目,该项目从 Android 运行设备拍照,然后发送到 cloudconvert.org 以将其转换为 SVG,然后所有 SVG 路径将被转换为 xy 坐标并串行发送到将绘制它们的机械臂打开或关闭笔。

So I've gone so far in this project and the only problem that I am having now is to parse the SVG file into a list of path as a list of string.所以我在这个项目中已经走了这么远,我现在遇到的唯一问题是将 SVG 文件解析为路径列表作为字符串列表。

I tried minidom but it doesn't seems that it's working.我试过 minidom 但它似乎没有工作。 I can actually access the SVG file and but I can't access the path data example 'M 100,200 L 200.300' instead of that I get我实际上可以访问 SVG 文件,但我无法访问路径数据示例 'M 100,200 L 200.300' 而不是我得到的

>>> from xml.dom import minidom
>>> xmldoc= minidom.parse("C:\Users\DELL\Desktop\drawing-1.svg")
>>> a=xmldoc.getElementsByTagName("svg")[0]
>>> b=a.getElementsByTagName("g")[0]
>>> pth=b.getElementsByTagName("path")[0]
>>> pth
<DOM Element: path at 0x1bb6238>

I just want to access the data inside that dom object as a string and when I tried我只想访问该 dom 对象中的数据作为字符串,当我尝试

>>> print (str(pth))

nothing appears just two blank line then >>> appears again.什么都没有出现,只有两个空行然后>>>再次出现。

That's an old thread but since the link from the accepted answer no longer works here is my approach to processing svg paths.这是一个旧线程,但由于来自已接受答案的链接在这里不再有效,这是我处理 svg 路径的方法。

There is an svg.path module which extracts paths and other shapes plus provides methods to process them.有一个 svg.path 模块可以提取路径和其他形状,并提供处理它们的方法。

from xml.dom import minidom
from svg.path import parse_path

svg_dom = minidom.parseString(svg_string)

path_strings = [path.getAttribute('d') for path in svg_dom.getElementsByTagName('path')]

for path_string in path_strings:
    path_data = parse_path(path_string)

    #  now use methods provided by the path_data object
    #  e.g. points can be extracted using 
    #  point = path_data.pos(pos_val) 
    #  where pos_val is anything between 0 and 1

I have been working on the same problem my solution was this: 1.convert svg paths to polygons using http://guilhermemussi.com/conversor.html 2. use a relatively simple python script to extract a list of the points.我一直在解决同样的问题,我的解决方案是: 1. 使用http://guilhermemussi.com/conversor.html 将svg 路径转换为多边形 2. 使用相对简单的 python 脚本来提取点列表。 Here is my code it might be sort of messy/inneficient but it gets the job done这是我的代码,它可能有点混乱/低效,但它完成了工作

scribble=open("scrib1.txt")
for line in scribble:
    if line.startswith("<polygon"):
        rightline=line.split('"')
commas=rightline[13].split(' ') 
newlist=[]
for i in commas:
    tup=i.split(',')
    newlist.append((tup[0],tup[1]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM