0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CLIからPythonでGIMPを操作する:上級者向けガイド

Last updated at Posted at 2024-07-20

はじめに

前回の記事「GIMPのPythonスクリプトで画像生成:初心者向け完全ガイド」では、GIMPのPythonスクリプトを使って、カスタムメッセージを含む画像を自動生成する方法を解説しました。今回は、その続編として、コマンドラインインターフェース(CLI)からPythonを介してGIMPを操作する、より高度な方法を紹介します。

この方法を使うことで、GIMPのグラフィカルユーザーインターフェース(GUI)を起動することなく、画像処理を自動化できます。これは、大量の画像を処理する場合や、サーバー上で画像処理を行う場合に特に有用です。

デモ動画

環境設定

まず、必要な環境を整えましょう:

  1. GIMP(バージョン2.10以上)をインストール
  2. Pythonをインストール(GIMPに付属のPythonを使用)
  3. 必要なPythonライブラリをインストール:
    pip install art loguru
    

基本的なGIMP操作スクリプト

まずは、簡単なスクリプトから始めましょう。このスクリプトは、GIMPのバージョンとPythonのバージョンを表示します。

# hello.py
import subprocess

# GIMPで実行するPythonスクリプトを定義
gimp_script = r"""
# -*- coding: utf-8 -*-

from __future__ import print_function, unicode_literals
import sys
from gimpfu import *

# GIMPとPythonのバージョンを表示
print("Hello GIMP!!!")
print("Gimpのバージョンは " + str(pdb.gimp_version()))
print("Pythonのバージョンは " + str(sys.version))

# GIMPを終了
pdb.gimp_quit(1)
"""

# GIMPをCLIモードで実行するコマンド
commands = [
    "gimp-console-2.10.exe",
    "--batch-interpreter",
    "python-fu-eval",
    "--batch",
    gimp_script,
]

# サブプロセスとしてGIMPを実行
process = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()

# 結果を表示
output = stdout.decode().strip()
print(output)

このスクリプトは、subprocessモジュールを使用してGIMPをCLIモードで起動し、指定したPythonスクリプトを実行します。

高度なGIMP操作スクリプト

次に、より高度なスクリプトを見てみましょう。このスクリプトは、テキストを含む画像を生成し、保存します。

# gimp_text_image.py
import subprocess
import os
from art import text2art
from loguru import logger

# ログの設定
logger.add("gimp_script.log", rotation="500 KB")

# GIMPで実行するPythonスクリプトを定義
gimp_script = r"""
# -*- coding: utf-8 -*-

from __future__ import print_function, unicode_literals
import sys
from gimpfu import *

# ログ出力関数
def log_info(message):
    print("INFO: " + message)

def log_success(message):
    print("SUCCESS: " + message)

# ASCIIアートを生成する関数
def create_ascii_art(text):
    art = ""
    for line in text.split("\n"):
        art += "*" * (len(line) + 4) + "\n"
        art += "* " + line + " *\n"
        art += "*" * (len(line) + 4) + "\n"
    return art

# テキスト画像を作成する関数
def create_text_image(text, font_size, output_path):
    print(create_ascii_art("GIMP Text Image Creator"))
    
    # 新しい画像を作成
    log_info("新しい画像を作成中...")
    width, height = 400, 200
    image = pdb.gimp_image_new(width, height, RGB)
    
    # 背景レイヤーを追加
    log_info("背景レイヤーを追加中...")
    background = pdb.gimp_layer_new(image, width, height, RGB, "Background", 100, NORMAL_MODE)
    pdb.gimp_image_insert_layer(image, background, None, 0)
    
    # 背景を白で塗りつぶし
    log_info("背景を白で塗りつぶし中...")
    pdb.gimp_context_set_foreground((255, 255, 255))
    pdb.gimp_drawable_fill(background, FOREGROUND_FILL)
    
    # テキストレイヤーを追加
    log_info("テキストレイヤーを追加中...")
    text_layer = pdb.gimp_text_layer_new(image, text, "Sans", font_size, 0)
    pdb.gimp_image_insert_layer(image, text_layer, None, -1)
    
    # テキストの色を設定
    log_info("テキストの色を設定中...")
    pdb.gimp_text_layer_set_color(text_layer, (0, 0, 0))
    
    # テキストレイヤーを中央に配置
    log_info("テキストレイヤーを中央に配置中...")
    pdb.gimp_layer_set_offsets(text_layer, (width - text_layer.width) // 2, (height - text_layer.height) // 2)
    
    # 画像を保存
    log_info("画像を保存中...")
    pdb.gimp_file_save(image, pdb.gimp_image_merge_visible_layers(image, CLIP_TO_IMAGE), output_path, output_path)
    
    # 画像を閉じる
    log_info("画像を閉じています...")
    pdb.gimp_image_delete(image)
    
    log_success("画像の作成が完了しました!")

# メイン処理
print(create_ascii_art("GIMP Script Start"))

output_path = r'D:\hello_gimp.png'  # 出力先のパスを適切に設定してください
create_text_image("Hello GIMP!", 36, output_path)

log_success("画像が保存されました: " + output_path)
log_info("Gimpのバージョンは " + str(pdb.gimp_version()))
log_info("Pythonのバージョンは " + str(sys.version))

print(create_ascii_art("GIMP Script End"))

# GIMPを終了
pdb.gimp_quit(1)
"""

# GIMPスクリプトを実行する関数
def run_gimp_script():
    logger.info("GIMPスクリプトの実行を開始します")
    
    # GIMPをCLIモードで実行するコマンド
    commands = [
        "gimp-console-2.10.exe",
        "--batch-interpreter",
        "python-fu-eval",
        "--batch",
        gimp_script,
    ]

    # サブプロセスとしてGIMPを実行
    process = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()

    # 結果をログに記録
    output = stdout.decode().strip()
    logger.info(f"GIMPの出力:\n{output}")
        
    logger.success("GIMPスクリプトの実行が完了しました")

# メイン処理
if __name__ == "__main__":
    print(text2art("GIMP Text Image"))
    logger.info("プログラムを開始します")
    run_gimp_script()
    logger.info("プログラムを終了します")
    print(text2art("Completed!", font="small"))

このスクリプトは、前回の記事で紹介したGIMP内部で実行するスクリプトを、外部のPythonスクリプトから制御しています。主な違いは以下の点です:

  1. subprocessモジュールを使用してGIMPをCLIモードで起動
  2. loguruを使用して詳細なログを記録
  3. artモジュールを使用してASCIIアートを生成

スクリプトの実行と結果の確認

  1. コマンドプロンプトを開きます。
  2. スクリプトのあるディレクトリに移動します。
  3. 以下のコマンドを実行します:
    python gimp_text_image.py
    
  4. 実行結果を確認し、生成された画像を確認します。

まとめ

CLIからPythonを介してGIMPを操作することで、画像処理を自動化し、効率化することができます。この方法は以下のような場面で特に有効です:

  1. 大量の画像を一括処理する場合
  2. 定期的に同じ画像処理を行う場合
  3. GUIを使用せずにサーバー上で画像処理を行う場合

今回紹介したスクリプトをベースに、さらに複雑な画像処理タスクを自動化することも可能です。GIMPのドキュメントを参照しながら、自分のニーズに合わせてスクリプトをカスタマイズしてみてください。

CLIからのGIMP操作は、画像処理の可能性を大きく広げてくれます。ぜひ挑戦して、あなたの画像処理ワークフローを次のレベルに引き上げてください!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?