python生成、操作svg图片

生成svg图片

通过python生成svg图片的方法有许多,比如OpenCV的源码中有svgfig.py这个脚本可以用于生成svg图片(OpenCV的棋盘格图片可以通过这个方法生成),也可以使用svg.py的库,安装方法如下

pip install svg.py

下面是通过这个库生成一个简单的svg图片

width = 500
height = 500

import svg

canvas = svg.SVG(
    width=width, height=height,
    elements=[
        svg.Circle(
            cx=width/2, cy=height/2, r=width/2,
            stroke="green",
            fill="red",
            stroke_width=20,
        ),
    ],
)
f = open("test1.svg", "w")
f.write(str(canvas))
f.close()

主意svg与png、jpg等格式不同,svg是矢量图,里面的内容都是一些描述性的。
比如下面就是"test1.svg"的内容

<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500"><circle stroke="green" stroke-width="20" cx="250.0" cy="250.0" r="250.0" fill="red"/></svg>

通过浏览器可以直接打开这个svg文件

读入svg并转换成numpy格式

应该还有一些其他方法,不过我的方法就是将svg图片转换成png格式,然后将png格式转换为RGBA格式的numpy。
(下面的代码接上面)

from PIL import Image
from cairosvg import svg2png
from io import BytesIO
import numpy as np
import matplotlib.pyplot as plt

# If the write_to argument is provided (filename or file-like object), the output is written there.
png = svg2png(bytestring=str(canvas)) # png是一个bytestring
print(type(png))

png_img = Image.open(BytesIO(png))

cv_img = np.array(png_img.convert('RGBA'))

plt.figure()
plt.imshow(cv_img)
plt.show()

svg转换成png使用到的库为cairosvg

pip install CairoSVG

这样安装完后可能使用会出问题(尤其是windows系统下),比如报一些cairo动态库找不到的错误。因为CairoSVG依赖cairo动态库。在windows系统下可以安装msys2,然后在msys2中安装gtk3,因为gtk3会安装cairo相关的库。

pacman -S mingw-w64-ucrt-x86_64-gtk3

CairoSVG and its dependencies may require additional tools during the installation: a compiler, Python headers, Cairo, and FFI headers. These tools have different names depending on the OS you are using, but:
on Windows, you’ll have to install Cairo (with GTK for example) and Visual C++ compiler for Python;
on macOS, you’ll have to install cairo and libffi (with Homebrew for example);
on Linux, you’ll have to install the cairo, python3-dev and libffi-dev packages (names may vary for your distribution).

msys2可以支持不同平台,不同平台下都有相应的库。我是将gtk3的库都安装在ucrt64这个平台下面。
注意安装完后,需要将ucrt64/bin添加到查找的path中,这样python的cairoSVG库才能找到cairo的依赖。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值