Search code examples
pythongimppython-fu

GIMP Python, selection based on path not the same as menu item "From Path"


I've created an image in GIMP 2.8 with several paths using Select -> To Path. Now I want to create a Python script that will loop through all these paths, make a selection based on each path, cut out the selection to a new image, do some additional stuff, and save each cut-out to a separate PNG image.

So far I've got this Python script, which I can start from Filters -> Paths as a menu item:

#!/usr/bin/env python
# coding: utf-8

from gimpfu import *
import os

def export_paths_to_pngs(img, layer, path, vis):

    # get all paths (internally called "vectors")
    cnt, vectors = pdb.gimp_image_get_vectors(img)
    if (cnt > 0):
        # iterate all paths
        for n in vectors:
            v = gimp.Vectors.from_id(n)
            # only visible paths
            if (v.visible):
                st = v.strokes
                sufix = 0
                # iterate all strokes in vector
                for ss in st:
                    type, num_pnts, cntrlpnts, closed = pdb.gimp_vectors_stroke_get_points(v, ss.ID)
                    pdb.gimp_image_select_polygon(img, CHANNEL_OP_REPLACE, len(cntrlpnts), cntrlpnts)

# tell gimp about our plugin
register(
    "python_fu_export_paths_to_png",
    "Export paths as png files",
    "Export paths as png files",
    "BdR",
    "BdR",
    "2017",
    "<Image>/Filters/Paths/Export paths to png", # menu path
    "",   # Create a new image, don't work on an existing one
    [
        (PF_DIRNAME, "export_directory", "Export destination directory", "/tmp"),
        (PF_TOGGLE, "p2",   "TOGGLE:", 1)       
    ],
    [],
    export_paths_to_pngs
)

main()

However, the problem is that the python function gimp_image_select_polygon doesn't make a selection as intended. The selection seems to have some differences in the bezier curves (or something like that) which is not exactly the same as the path it's based on. On the other hand, the menu item From Path does work correctly, it makes a perfect selection based on the path. See image below:

enter image description here

So my questions are:

  1. What is the difference between the menu item Select -> From Path and the GimpPython function gimp_image_select_polygon
  2. Am I using the function gimp_image_select_polygon incorrectly, or is there another function I should use?
  3. Failing all that, is there a way to somehow call the menu item From Path directly from Python?

Solution

  • Don't use

    pdb.gimp_image_select_polygon(...) 
    

    which is meant to create a polygonal selection (like the Freehand selection in "polygon" mode). You should be using

    pdb.gimp_image_select_item(image,CHANNEL_OP_REPLACE,path) 
    

    (on the whole path, no need to do it stroke by stroke).

    PS: your code to iterate on paths is very contrived. It is normally as simple as:

    for v in img.vectors:
       if v.visible: