我如何在 pycairo 中读取 svg 数据笔划?

pos*_*res 6 svg image-processing pycairo

我有 JPG 图像和 inputvgdraw,这是一个用于图像注释的 flash 工具(http://www.mainada.net/inputdraw),我可以在其上跟踪生成 svg 数据的线条。

svg 数据示例:

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 488 325"><g fill="none"   stroke-miterlimit="6" stroke-linecap="round" stroke-linejoin="round"><path d="M 307 97 l 0 -1 l -2 -1 l -10 -2 l -20 -1 l -25 5 l -22 9 l -10 9 l 0 9 l 2 12 l 16 18 l 25 11 l 25 5 l 17 -1 l 6 -4 l 3 -7 l -1 -12 l -6 -16 l -7 -13 l -11 -12 l -11 -14 l -9 -5" opacity="1" stroke="rgb(170,37,34)" stroke-width="5"/></g></svg>.
Run Code Online (Sandbox Code Playgroud)

什么功能可以管理这些数据?

mmg*_*mgp 4

您可以使用读取 SVG 输入librsvg,然后使用 渲染它cairo。如果您想在初始图像上绘制 SVG 中的注释,您可能需要使用PILwith numpy,因为cairo它本身不会加载许多不同的图像格式。

ctypes以下是实现这一目标的示例(唯一的区别是实际上我使用for的临时包装器对其进行了测试rsvg):

import sys
import rsvg
import cairo
import numpy
from PIL import Image

# Load an image that supposedly has the same width and height as the svg one.
img_rgba = numpy.array(Image.open(sys.argv[1]).convert('RGBA'))
data = numpy.array(img_rgba.tostring('raw', 'BGRA'))
width, height = img_rgba.size

surface = cairo.ImageSurface.create_for_data(data,
        cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(surface)

# "Paste" the svg into the image.
svg = rsvg.Handle(file=sys.argv[2])
svg.render_cairo(ctx)

surface.write_to_png(sys.argv[3])
Run Code Online (Sandbox Code Playgroud)