如何使用命令行从gimpfu运行Python脚本?

11
我将使用gimp 2.8.22的功能将pdf转换为jpeg,并希望使用来自我的Windows cmd的gimpfu库中的python脚本完成此操作(我已安装python 3.6.1)。
目前,我正在尝试使用示例脚本完成此操作:
#!/usr/bin/env python

# Hello World in GIMP Python

from gimpfu import *

def hello_world(initstr, font, size, color) :
    # First do a quick sanity check on the font
    if font == 'Comic Sans MS' :
        initstr = "Comic Sans? Are you sure?"

    # Make a new image. Size 10x10 for now -- we'll resize later.
    img = gimp.Image(1, 1, RGB)

    # Save the current foreground color:
    pdb.gimp_context_push()

    # Set the text color
    gimp.set_foreground(color)

    # Create a new text layer (-1 for the layer means create a new layer)
    layer = pdb.gimp_text_fontname(img, None, 0, 0, initstr, 10,
                                   True, size, PIXELS, font)

    # Resize the image to the size of the layer
    img.resize(layer.width, layer.height, 0, 0)

    # Background layer.
    # Can't add this first because we don't know the size of the text layer.
    background = gimp.Layer(img, "Background", layer.width, layer.height,
                            RGB_IMAGE, 100, NORMAL_MODE)
    background.fill(BACKGROUND_FILL)
    img.add_layer(background, 1)

    # Create a new image window
    gimp.Display(img)
    # Show the new image window
    gimp.displays_flush()

    # Restore the old foreground color:
    pdb.gimp_context_pop()

register(
    "python_fu_hello_world",
    "Hello world image",
    "Create a new image with your text string",
    "Akkana Peck",
    "Akkana Peck",
    "2010",
    "Hello world (Py)...",
    "",      # Create a new image, don't work on an existing one
    [
        (PF_STRING, "string", "Text string", 'Hello, world!'),
        (PF_FONT, "font", "Font face", "Sans"),
        (PF_SPINNER, "size", "Font size", 50, (1, 3000, 1)),
        (PF_COLOR, "color", "Text color", (1.0, 0.0, 0.0))
    ],
    [],
    hello_world, menu="<Image>/File/Create")

main()

我尝试通过cmd运行以下脚本:

gimp-2.8 --no-interface --batch '(python_fu_hello_world RUN-NONINTERACTIVE "Hello" Arial 50 red)' -b '(gimp-quit 1)'

然而,无论我做什么,我总是收到相同的错误信息:

(gimp-2.8:1020): LibGimpBase-WARNING **: gimp-2.8: gimp_wire_read(): error

编辑:好的,谢谢。 我忽略了接口语句,并尝试了最简单的示例来找出问题所在:
#!/usr/bin/env python

# Hello World in GIMP Python

from gimpfu import *

def hello_world():
 gimp.message("Hello, GIMP world!\n")

register(
 "hello_world",
 'A simple Python-Fu "Hello, World" plug-in',
 'When run this plug-in prints "Hello, GIMP world!" in a dialog box.',
 "Tony Podlaski",
 "Tony Podlaski 2017. MIT License",
 "2017",
 "Hello World",
 "",
 [],
 [],
 hello_world,
 menu="<Image>/Filters/HelloWorld",
)

main()

脚本实际上在我从Gimp自身运行它时可以工作,但当我尝试从我的cmd中运行它时,Gimp会打开另一个cmd并显示以下内容:Error: ( : 1) eval: unbound variable: hello_world

有人知道我漏掉了什么吗?


未绑定的变量:hello_world:python_fuhello_world之间缺少下划线? - xenoid
我猜你是在谈论第一个代码示例,对吗?错误信息“未绑定变量”与第二个代码示例有关... - flixe
我说的是你使用的命令行。这条消息来自Scheme,在你的整个过程中没有太多的Scheme,也没有在很多地方使用“python-fu”字符串。另一方面,请参见我的第二个答案。 - xenoid
2个回答

30

运行Python脚本无需将其注册为插件。我认为您甚至应该避免这样做,因为这会不必要地污染Gimp的菜单和过程名称空间。以下是一个示例:

批处理脚本(保存为batch.py):

#!/usr/bin/python
# -*- coding: iso-8859-15 -*-

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


def process(infile):
        print "Processing file %s " % infile
        image = pdb.gimp_file_load(infile, infile, run_mode=RUN_NONINTERACTIVE)
        drawable = image.active_layer

        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

要调用它:

gimp -idf --batch-interpreter python-fu-eval -b "import sys;sys.path=['.']+sys.path;import batch;batch.run('./images')" -b "pdb.gimp_quit(1)"

慢动作模式中的参数:

  • -idf:无需用户界面工作,也不加载数据或字体(也许需要保留字体以加载pdf)
  • --batch-interpreter python-fu-eval:跟随-b后面的是Python代码而不是脚本fu
  • "import sys;sys.path=['.']+sys.path;import batch;batch.run('./images')":这是我们要求Gimp执行的代码,即:
    • import sys;sys.path=['.']+sys.path;:扩展导入路径以包括当前目录
    • import batch;:导入包含我们脚本的文件,该文件现在位于路径的一部分的目录中。
    • batch.run('./images'):调用我们导入的batch模块的run()函数,并给出要处理的图片所在的目录的名称。
  • -b "pdb.gimp_quit(1)":另一段Python代码:完成后退出。

请注意,命令行巧妙地使用双引号和单引号将所有参数传递给Gimp,然后传递给Python(*). 是的,您可以在Windows中使用正斜杠作为文件分隔符。

在Windows中进行调试有点复杂,因为没有始终存在的stdout流。以下是一些有用的方法:

  • 暂时删除-i参数,以便获得UI界面和可能看到消息的机会。
  • 添加--verbose,使Gimp启动一个辅助控制台窗口。
  • 这里列出了其他查看消息的技巧 here
  • 您还可以正常启动Gimp,并从Python-fu控制台(Filters>Python-fu>Console)运行脚本。您将不得不扩展路径并手动导入文件。

(*) 在Linux / OSX shell中,相反地:shell使用单引号,Python使用双引号。


谢谢您的回答,但我对Python完全不熟悉。我尝试按照您的示例运行代码:gimp -idf --batch-interpreter python-fu-eval -b "import sys;sys.path=['.']+sys.path;import batch;batch.run('C:\Path\to\image\')" -b "pdb.gimp_quit(1)" 但是,我遇到了一个错误:批处理命令执行错误。这个脚本具体是做什么的?我该如何处理这个错误? - flixe
如果您在路径中使用正斜杠(C:/Path/to/image/),会怎样呢?话虽如此,使用ImageMagick,“convert foobar.pdf foobar.jpg”就可以了,您不必学习Python和Gimp。 - xenoid
我成功让你的脚本工作了,是的,问题在于斜杠,非常感谢。还有一个问题:打印消息去哪里了?它们既没有显示在控制台中,也没有显示在我的stdout.txt中?是的,我读到更多的人使用ImageMagick,但我有使用GIMP的说明。 - flixe
@xenoid,非常感谢。这是我在GIMP上制作的第一个脚本。它可以直接在“Windows 10”上运行而无需更改。唯一不喜欢的是持久的消息“(gimp-console-2.8.exe:10020): LibGimpBase-WARNING **: gimp-console-2.8.exe: gimp_wire_read(): error”。 - alvaro562003
除Gimp开发人员之外,没有人控制它。你必须接受它... - xenoid
显示剩余9条评论

1
因为您使用的脚本会创建图像,然后在窗口中显示它...但是您正在使用--no-interface标志调用Gimp,因此窗口不会显示。
在我看来,要将PDF转换为JPEG,ImageMagick的convert命令会更简单。
另外,在Windows中,Gimp带有自己内置的Python 2.7解释器,因此您必须为该版本编写Python代码,并且无需安装其他解释器。

谢谢。我已经编辑了我的原始帖子,因为我仍然无法通过GIMP命令运行我的Python脚本。 - flixe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接