Find the center of an object in a script

Discussion about writing code for Inkscape.
raphael0202
Posts: 1
Joined: Sun Feb 15, 2015 2:10 am

Find the center of an object in a script

Postby raphael0202 » Sun Feb 15, 2015 2:17 am

Hello,
I've written a script in Python in order to automatically scrape data from graphs saved in svg.
I need to get the center positions of the objects selected in Inkscape. I looked for a convenient way to do it, and the only solution I found was to call externally the Inkscape command this way:
inkscape --query-id=node_id -X temporary_svg_path
It has the major drawback of being extremely slow when many points are selected. Is there an easy way to do so ?
Thanks
Raphaël

User avatar
samueldellicour
Posts: 26
Joined: Mon Jul 01, 2013 11:03 pm
Location: Belgium
Contact:

Re: Find the center of an object in a script

Postby samueldellicour » Sat Feb 21, 2015 5:19 am

In my extension to add guides through the center of a SINGLE selected object, I use the following code. Maybe you can use that as a start?

Code: Select all

         # getting the main SVG document element (canvas)
         svg = self.document.getroot()

         # getting the width and height attributes of the canvas
         canvas_width  = self.unittouu(svg.get('width'))
         canvas_height = self.unittouu(svg.attrib['height'])

         # check if a selection exists
         if not self.options.ids:
            inkex.errormsg(_("No objects selected. Please select an object first."))
            exit()

         # query bounding box, UPPER LEFT corner (?)
         q = {'x':0, 'y':0, 'width':0, 'height':0}
         for query in q.keys():
            p = Popen(
               'inkscape --query-%s --query-id=%s "%s"' % (query, self.options.ids[0], self.args[-1], ),
               shell=True,
               stdout=PIPE,
               stderr=PIPE,
               )
            p.wait()
            q[query] = p.stdout.read()

         # get width, height, center of bounding box
         obj_width = float(q['width'])
         obj_height = float(q['height'])
         center_x = float(q['x']) + obj_width/2
         center_y = ( canvas_height - float(q['y']) - obj_height ) + obj_height/2


With some imports at the beginning of the file:

Code: Select all

import inkex
import gettext
_ = gettext.gettext
from subprocess import Popen, PIPE


I'm not a programmer, and have used various sources to build the code, so I cannot explain every single line of the code I used, but it works for me ;-)
Samuel


Return to “Programming”