Pillow ImageChops モジュール

ImageChops は Python PIL(Python Imaging Library)のサブモジュールであり、画像のチャンネル操作("Channel Operations"の略)に特化しています。

ImageChops モジュールは、画像に対して数学的演算や論理演算を行うための一連のメソッドを提供しており、画像合成や特殊効果処理などの場面でよく使用されます。

モジュールの特徴

  • すべてのメソッドは2つの画像を引数として受け取り、それらの対応するピクセルに対して操作を行います。
  • 新しい画像オブジェクトを返します。
  • ほとんどのメソッドは、入力画像が同じサイズとモードを持つことを要求します。
  • 画像合成、ブレンド、特殊効果処理に特に適しています。

ImageChops のよく使われるメソッド

以下は、ImageChops モジュールで最もよく使用されるメソッドとその機能の説明です:

メソッド名 機能の説明 数式
add(image1, image2, scale=1.0, offset=0) 2つの画像を加算します。 out = ((image1 + image2) / scale + offset)
subtract(image1, image2, scale=1.0, offset=0) 2つの画像を減算します。 out = ((image1 - image2) / scale + offset)
lighter(image1, image2) 2つの画像を比較し、各ピクセルの明るい方の値を取得します。 out = max(image1, image2)
darker(image1, image2) 2つの画像を比較し、各ピクセルの暗い方の値を取得します。 out = min(image1, image2)
multiply(image1, image2) 2つの画像を乗算します。 out = image1 * image2 / 255
screen(image1, image2) 2つの画像をスクリーン合成します。 out = 255 - (255 - image1) * (255 - image2) / 255
overlay(image1, image2) 2つの画像をオーバーレイ合成します。 ピクセル値に基づいて multiply または screen 操作を選択します。
difference(image1, image2) 2つの画像の絶対差分を返します。 out = abs(image1 - image2)
invert(image) 画像を反転します(ネガ効果)。 out = 255 - image
logical_and(image1, image2) 2つの画像に対して論理 AND 操作を行います。 out = image1 & image2
logical_or(image1, image2) 2つの画像に対して論理 OR 操作を行います。 out = image1 | image2
logical_xor(image1, image2) 2つの画像に対して論理 XOR 操作を行います。 out = image1 ^ image2
blend(image1, image2, alpha) 固定の不透明度を使用して2つの画像をブレンドします。 out = image1 * (1.0 - alpha) + image2 * alpha
composite(image1, image2, mask) マスク画像を使用して2つの画像を合成します。 mask に基づいて image1 または image2 のピクセルを選択します。
offset(image, xoffset, yoffset=None) 画像をオフセットします。 画像を x 方向と y 方向に指定したピクセル数だけ移動します。

使用例

基本的な使用

実例

from PIL import Image, ImageChops

# 2つの画像を開く
image1 = Image.open("image1.jpg")
image2 = Image.open("image2.jpg")

# 2つの画像のサイズが同じであることを確認
if image1.size == image2.size:
    # 2つの画像を加算
    added_image = ImageChops.add(image1, image2)
    added_image.save("added.jpg")
   
    # 2つの画像の差分を取得
    diff_image = ImageChops.difference(image1, image2)
    diff_image.save("difference.jpg")

画像のネガを作成

実例

from PIL import Image, ImageChops

# 画像を開く
original = Image.open("photo.jpg")

# ネガを作成
inverted = ImageChops.invert(original)
inverted.save("negative.jpg")

画像のブレンド

実例

from PIL import Image, ImageChops

# 2つの画像を開く
foreground = Image.open("foreground.png")
background = Image.open("background.jpg")

# サイズが同じであることを確認
if foreground.size == background.size:
    # 画像をブレンド(alpha=0.5 はそれぞれ50%ずつを意味)
    blended = ImageChops.blend(foreground, background, 0.5)
    blended.save("blended.jpg")

注意事項

  1. 画像モード:ほとんどの ImageChops メソッドは、入力画像が同じモード(RGB、L など)であることを要求します。
  2. 画像サイズ:操作する2つの画像は同じサイズである必要があります。
  3. 戻り値:すべてのメソッドは新しい Image オブジェクトを返し、元の画像は変更しません。
  4. パフォーマンスに関する考慮事項:大きな画像の場合、これらの操作は多くのメモリを消費する可能性があります。
  5. 特殊なモード:一部のメソッド(論理演算など)は通常、1ビット画像(モード "1")に使用されます。

ImageChops モジュールを適切に使用することで、単純な画像合成から複雑な特殊効果処理まで、さまざまな画像処理効果を簡単に実現できます。

その他の拡張