Convert SVG to numpy array

Viewed 4124

I am writing a function for a python library, and in one of the functions I need to take SVG strings as input, i.e.

<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>

and I want get an rasterized image, like so:

svg image

However, i need to have access to this image in python, preferably in the form of a numpy array.

I am aware that this can be done using externally available software, i.e. inkscape or imagemagic, but I explicitly need to be able to do this in pure python. Further, in order to be able to distribute this to a wide range of users on different platforms, I cannot support compiled backends (as with cairo).

Is there any python package that takes SVG images in string format and somehow returns a numpy array representing the rasterized image?

1 Answers

Late answer !

Here is the documentation reference :

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

I am writing a function for a python library - OK, here's something to get you going.

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))

A better answer to your solution might depend on the performance and import requirements given the context of your "python library", feel free to continue this discussion.

Related