Skip to main content
 首页 » 编程设计

python之将 SVG 转换为 numpy 数组

2025年02月15日8rubylouvre

我正在为 python 库编写一个函数,在其中一个函数中我需要将 SVG 字符串作为输入,即

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink"  > 
    <rect style="stroke-width:1; fill:rgb(255, 255, 255); stroke:black; " x="0" y="0" height="100px" width="200px"  /> 
    <text x="210" y="110"  > 
    Hello World 
    </text> 
</svg> 

我想要一个光栅化的图像,像这样:



但是,我需要在 python 中访问这个图像,最好是 numpy 数组的形式。

我知道这可以使用外部可用的软件来完成,即inkscape或imagemagic,但我明确需要能够在纯python中做到这一点。此外,为了能够将其分发给不同平台上的广泛用户,我不支持编译后端(如 cairo)。

是否有任何 python 包以字符串格式获取 SVG 图像并以某种方式返回表示光栅化图像的 numpy 数组?

请您参考如下方法:

迟到的答案!

这是文档引用:

https://www.crummy.com/software/BeautifulSoup/bs4/doc/

我正在为 python 库编写一个函数 - 好的,这里有一些东西可以帮助你。

from bs4 import BeautifulSoup 
 
data = BeautifulSoup(input, "lxml-xml") 
nsvg = data.find_all('svg') 
 
for svg in nsvg: 
    # parse specific to your needs, read docs 
    for element in svg.children: 
        np.append(do_something(element)) 

给定“python 库”的上下文,对您的解决方案的更好答案可能取决于性能和导入要求,请随时继续此讨论。