How can I read a bar of svg data in pycairo?

I have JPG images and with inputvgdraw, a tool for creating image annotations ( http://www.mainada.net/inputdraw ), I can trace the lines that generate svg datas on it.

Svg sample data:

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

What function can manage this data?

0
source share
1 answer

You can read the SVG input using librsvg and then pass it using cairo . If you want to draw annotations in SVG from the original image, you may need to use PIL with numpy , since cairo itself does not load many different image formats.

Below is an example that achieves this (the only difference is that I actually tested it with an ad-hoc ctypes wrapper 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]) 
+1
source

Source: https://habr.com/ru/post/892722/


All Articles