Post Reply 

Run a simple python script

Jul 18, 2011, 21:19 (This post was last modified: Jul 18, 2011 21:21 by jedi200582.)
Post: #1
Run a simple python script
Hello all,
I am a newb. And I realize the pb I have is trivial, but not much people are posting on that on internet.
I have this simple script python-fu script that resizes image in batch mode:

#################################################
#!/usr/bin/python

from gimpfu import *

def plugin_main(timg, tdrawable, neww=620, newh=880):
pdb.gimp_image_scale(timg, neww, newh)
pdb.file_bmp_save(timg, tdrawable, timg.name+"_"+str(newh)+"_"+str(neww)+".bmp",
timg.name+"_"+str(newh)+"_"+str(neww)+".bmp")

register(
"gimp_resize",
"Resizes the image at a specific width and height, and store it to bmp",
"Resizes the image at a specific width and height, and store it to bmp",
"toto",
"toto",
"2011",
"<Image>/Image/Batch resize...",
"RGB*, GRAY*",
[
(PF_INT, "new_width", "New Width", 620),
(PF_INT, "new_height", "New Height", 880),
],
[],
plugin_main)

main()
#################################################

I moved it to my ~/.gimp-2.6/plug-ins.
Now, when in try to run it in command line, it fails:

*******************************************************************************
toto@titi:~/projects/python/img/master$ gimp --verbose -i -b '(python-fu-gimp-resize RUN-NONINTERACTIVE "some_file.xcf" 141 200)' -b '(gimp-quit 0)'

(gimp:16135): GLib-WARNING **: /build/buildd/glib2.0-2.28.6/./glib/goption.c:2132: ignoring no-arg, optional-arg or filename flags (8) on option of type 0
INIT: gimp_load_config
Parsing '/home/jedi/.gimp-2.6/unitrc'
Parsing '/etc/gimp/2.0/gimprc'
Parsing '/home/jedi/.gimp-2.6/gimprc'
gimp_composite: use=yes, verbose=no
Processor instruction sets: +mmx +sse +sse2 -3dnow -altivec -vis
INIT: gimp_initialize
INIT: gimp_real_initialize
INIT: gimp_restore
Parsing '/home/jedi/.gimp-2.6/parasiterc'
Loading 'brush factory' data
Loading 'pattern factory' data
Loading 'palette factory' data
Loading 'gradient factory' data
Loading fonts
Parsing '/home/jedi/.gimp-2.6/templaterc'
INIT: gimp_real_restore
Parsing '/home/jedi/.gimp-2.6/pluginrc'
Starting extension: 'extension-script-fu'
No batch interpreter specified, using the default 'plug-in-script-fu-eval'.
batch command experienced an execution error
EXIT: gimp_exit
EXIT: gimp_real_exit
Terminating plug-in: '/usr/lib/gimp/2.0/plug-ins/script-fu'
Terminating plug-in: '/usr/lib/gimp/2.0/plug-ins/script-fu'
Writing '/home/jedi/.gimp-2.6/templaterc'
Writing '/home/jedi/.gimp-2.6/parasiterc'
Writing '/home/jedi/.gimp-2.6/unitrc'
EXIT: batch_exit_after_callback
********************************************************************************​*

Obviously, I tried many names and options (with - or _, with or without the "python-fu" prefix in the procedure name, with or without the "RUN_NONINTERATIVE" flag....) The debug message is actually not very helpful.

Please help Sad
Find all posts by this user
Quote this message in a reply
Jul 18, 2011, 21:44 (This post was last modified: Jul 18, 2011 21:46 by ofnuts.)
Post: #2
RE: Run a simple python script
My (only) python batch is called thus:
Code:
gimp-2.6 -idf --batch-interpreter python-fu-eval -b 'import sys; sys.path=["."]+sys.path;import batch;batch.run("./images")' -b 'pdb.gimp_quit(1)'
and it goes:
Code:
# -*- coding: iso-8859-15 -*-

import os,glob,sys,time
from gimpfu import *


def process(infile):
        print "Processing file %s " % infile
        image = pdb.file_jpeg_load(infile,infile)
        drawable = pdb.gimp_image_get_active_layer(image)

        print "File %s loaded OK" % infile
        pdb.plug_in_photocopy(image, drawable,8.,0.8,0.2,0.2)
        pdb.plug_in_cartoon(image, drawable, 7.,0.2)
        outfile=os.path.join('processed',os.path.basename(infile))
        outfile=os.path.join(os.path.dirname(infile),outfile)
        print "Saving to %s" % outfile
        pdb.file_jpeg_save(image, drawable, outfile, outfile, "0.5",0,1,0,"",0,1,0,0)
        print "Saved to %s" % outfile
        pdb.gimp_image_delete(image)


def run(directory):
        start=time.time()
        print "Running on directory \"%s\"" % directory
#       os.mkdir(os.path.join(directory,'processed'))
        for infile in glob.glob(os.path.join(directory, '*.jpg')):
                process(infile)
        end=time.time()                                                                                                                                          
        print "Finished, total processing time: %.2f seconds" % (end-start)                                                                                      
                                                                                                                              
if __name__ == "__main__":                                                                                                                                        
        print "Running as __main__ with args: %s" % sys.argv
There is a bit of kludging the python path to make my python script loadable from the directory where it sits.

As you can see if you don't intend to use the script interactively there is no need to register the plugin (which isn't really one...)

IMHO if your only goal is to resize the picture you should look into ImageMagick.

Now answering your questions on
https://Gimp-Forum.net
Visit this user's website Find all posts by this user
Quote this message in a reply
Jul 19, 2011, 09:06 (This post was last modified: Jul 19, 2011 09:10 by paynekj.)
Post: #3
RE: Run a simple python script
While ofnuts is probably right about using ImageMagick for batch processing (I don't use it myself), in the interests of you learning Python scripting, here's some hints:

You seem to have a misunderstanding about parameters in your script and command line. The script is expecting to get a numeric image id, a numeric drawable id, a width value and a height value, but your command line is passing a file name string, a width value and a height value.

You can only get the image id and drawable id by opening the image within the script, generally using pdb.gimp_file_load and maybe pdb.gimp_image_get_active_layer.

Have a look at this for an example:
http://enoent.blogspot.com/2009/10/runni...batch.html
(found by Googling "gimp +batch +python": http://lmgtfy.com/?q=batch+%2Bgimp+%2Bpython )
Find all posts by this user
Quote this message in a reply
Jul 19, 2011, 10:25 (This post was last modified: Jul 19, 2011 10:28 by ofnuts.)
Post: #4
RE: Run a simple python script
(Jul 19, 2011 09:06)paynekj Wrote:  You seem to have a misunderstanding about parameters in your script and command line. The script is expecting to get a numeric image id, a numeric drawable id, a width value and a height value, but your command line is passing a file name string, a width value and a height value.

You can only get the image id and drawable id by opening the image within the script, generally using pdb.gimp_file_load and maybe pdb.gimp_image_get_active_layer.

Have a look at this for an example:
http://enoent.blogspot.com/2009/10/runni...batch.html
(found by Googling "gimp +batch +python": http://lmgtfy.com/?q=batch+%2Bgimp+%2Bpython )
In python you seldom handle ids... for instance

Code:
pdb.gimp_image_get_active_drawable(image)

returns a Drawable object (from an Image object....), and actually the line above is better expressed as:
Code:
image.active_layer
or
Code:
image.active_drawable

This yields very terse and efficient code, the current_layer of the first image is for instance obtained by
Code:
gimp.image_list()[0].active_drawable

When using python the python-fu console is your friend, not only for the Python procedure browser (which should be taken with a serious grain of salt since it often documents IDs when objects are needed/returned), but because you can use dir() on objects to see what they are and what method they have:
Code:
>>> image=gimp.image_list()[0]
>>> dir(image)
['ID', '__class__', '__cmp__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'active_channel', 'active_drawable', 'active_layer', 'add_channel', 'add_hguide', 'add_layer', 'add_vguide', 'attach_new_parasite', 'base_type', 'channels', 'clean_all', 'colormap', 'crop', 'delete_guide', 'dirty', 'disable_undo', 'duplicate', 'enable_undo', 'filename', 'find_next_guide', 'flatten', 'floating_sel_attached_to', 'floating_selection', 'free_shadow', 'get_channel_by_tattoo', 'get_component_active', 'get_component_visible', 'get_guide_orientation', 'get_guide_position', 'get_layer_by_tattoo', 'height', 'layers', 'lower_channel', 'lower_layer', 'lower_layer_to_bottom', 'merge_down', 'merge_visible_layers', 'name', 'new_layer', 'parasite_attach', 'parasite_detach', 'parasite_find', 'parasite_list', 'pick_correlate_layer', 'raise_channel', 'raise_layer', 'raise_layer_to_top', 'remove_channel', 'remove_layer', 'resize', 'resize_to_layers', 'resolution', 'scale', 'selection', 'set_component_active', 'set_component_visible', 'tattoo_state', 'undo_freeze', 'undo_group_end', 'undo_group_start', 'undo_is_enabled', 'undo_thaw', 'unit', 'unset_active_channel', 'vectors', 'width']

Now answering your questions on
https://Gimp-Forum.net
Visit this user's website Find all posts by this user
Quote this message in a reply
Jul 19, 2011, 20:52
Post: #5
RE: Run a simple python script
Thanks for your help both of you,
But without proper documentation and easy way to debug the script, gimp is not useful tool for what I want to do.

Thanks anyway,
cheers.
Find all posts by this user
Quote this message in a reply
Jul 19, 2011, 21:48
Post: #6
RE: Run a simple python script
I grant you that debugging batch scripts isn't easy because of the lack of error messages, so I always start by making an interactive version first.

The official Gimp Python page is a good place to start learning:
http://www.gimp.org/docs/python/index.html
Find all posts by this user
Quote this message in a reply
Jul 19, 2011, 21:59
Post: #7
RE: Run a simple python script
The only good reason to use Gimp in batch mode is because something you want to do on many images only exists as a Gimp filter. When you have read the doc for ImageMagick and seen what it can do, using Gimp batch becomes awfully rare.

For instance, creating a thumb-$n file for every JPG in the current directory, with a small side of 200 pixels:

Code:
convert *.jpg -geometry 200x200^ -set filename:out "thumb-%f" '%[filename:out]'

Now answering your questions on
https://Gimp-Forum.net
Visit this user's website Find all posts by this user
Quote this message in a reply
Jul 20, 2011, 11:08
Post: #8
RE: Run a simple python script
The thing is I have lot of xcf images. I want to create bitmap version of those, with various sizes (developing something on android and I need different version of the files for small phones, big phones, tablets, etc...).
The problem with ImageMagick is that it only reads one of the layer at a time and produce a bmp file for each layer, instead of combining those. I could solve this issue by removing the alpha channel from the layer (cause I basically have one text layer in my image) but if I do that, I can't modify the text layer anymore, because if I do, the layer is all screwed up.

Anyway, thanks for your help ofnuts.

(Jul 19, 2011 21:59)ofnuts Wrote:  The only good reason to use Gimp in batch mode is because something you want to do on many images only exists as a Gimp filter. When you have read the doc for ImageMagick and seen what it can do, using Gimp batch becomes awfully rare.

For instance, creating a thumb-$n file for every JPG in the current directory, with a small side of 200 pixels:

Code:
convert *.jpg -geometry 200x200^ -set filename:out "thumb-%f" '%[filename:out]'
Find all posts by this user
Quote this message in a reply
Jul 20, 2011, 11:10
Post: #9
RE: Run a simple python script
Yes I did that, and my script works in the console, not in command line. Don't ask me why, I just have this cryptic error message. For what I know, it could be anything...

The documendation is not really helpful either. It does not even mention the error message.

(Jul 19, 2011 21:48)paynekj Wrote:  I grant you that debugging batch scripts isn't easy because of the lack of error messages, so I always start by making an interactive version first.

The official Gimp Python page is a good place to start learning:
http://www.gimp.org/docs/python/index.html
Find all posts by this user
Quote this message in a reply
Jul 20, 2011, 12:39
Post: #10
RE: Run a simple python script
Just to reiterate, your script cannot work from the command line, and won't work interactively if you don't already have an image open, for the reasons I explained above.
Find all posts by this user
Quote this message in a reply
Post Reply 


Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Request for script chlebna 1 87 Sep 13, 2017 09:35
Last Post: ythgilb
  Request for script - Guillotine + Watermark sunslick 1 157 Sep 4, 2017 08:51
Last Post: ythgilb
  Script-fu: How to create new, addressable layer using gimp-floating-sel-to-layer Bertholom√§us 2 143 Aug 31, 2017 14:32
Last Post: Bertholomäus
  How to modify this script-fu? Zakary81 1 114 Aug 23, 2017 12:48
Last Post: paynekj
  Loading PythonFu Plugin: ImportError for .../python/gimp.so (GIMP 2.8.22/OSX/Py2.7.9) joroek 1 196 Jul 11, 2017 07:26
Last Post: ythgilb

Forum Jump:


GIMP ForumPortalArchiveContactTermsRSS