Pillow Image モジュール

Image は Pillow ライブラリの中核モジュールであり、画像処理の基本的な機能を提供します。

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

メソッド 説明 例
Image.open(fp, mode='r') 画像ファイルを開いて識別する img = Image.open('image.jpg')
Image.new(mode, size, color=0) 新しい画像を作成する new_img = Image.new('RGB', (500, 500), 'blue')
Image.save(fp, format=None, **params) 画像を保存する img.save('output.png')
Image.show(title=None, command=None) 画像を表示する img.show()
Image.resize(size, resample=None, box=None) 画像サイズを調整する img.resize((200, 200))
Image.rotate(angle, resample=0, expand=0) 画像を回転する img.rotate(45)
Image.crop(box=None) 画像を切り抜く img.crop((100, 100, 400, 400))
Image.paste(im, box=None, mask=None) 画像を貼り付ける img.paste(logo, (50, 50))
Image.convert(mode, matrix=None, dither=None) 画像モードを変換する img.convert('L')
Image.filter(filter) フィルタを適用する img.filter(ImageFilter.BLUR)
Image.copy() 画像をコピーする copy = img.copy()
Image.thumbnail(size) サムネイルを作成する img.thumbnail((100, 100))
Image.getpixel(xy) ピクセル値を取得する pixel = img.getpixel((50, 50))
Image.putpixel(xy, value) ピクセル値を設定する img.putpixel((50, 50), (255, 0, 0))
Image.split() チャンネルを分離する r, g, b = img.split()
Image.merge(mode, bands) チャンネルを結合する Image.merge('RGB', (r, g, b))

3. 共通属性

メソッド以外にも、Image オブジェクトにはいくつかの重要な属性があります:

属性 説明 例
format 画像フォーマット print(img.format)
size 画像サイズ (幅, 高さ) print(img.size)
width 画像の幅 print(img.width)
height 画像の高さ print(img.height)
mode 画像モード print(img.mode)
info 画像関連情報の辞書 print(img.info)

実際の応用例

基本的な画像操作

例

from PIL import Image

# 画像を開く
img = Image.open('example.jpg')

# 画像情報を表示する
print(f"形式: {img.format}, サイズ: {img.size}, モード: {img.mode}")

# サイズを調整して保存
resized_img = img.resize((300, 300))
resized_img.save('resized_example.jpg')

# グレースケールに変換
gray_img = img.convert('L')
gray_img.save('gray_example.jpg')

画像処理

例

from PIL import Image, ImageFilter

img = Image.open('example.jpg')

# ぼかしフィルタを適用
blurred = img.filter(ImageFilter.BLUR)
blurred.save('blurred.jpg')

# 輪郭フィルタを適用
contour = img.filter(ImageFilter.CONTOUR)
contour.save('contour.jpg')

# 画像を回転
rotated = img.rotate(45, expand=True)
rotated.save('rotated.jpg')

高度な機能

画像合成

例

from PIL import Image

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

# 2つの画像のサイズが同じであることを確認
img2 = img2.resize(img1.size)

# 画像を合成 (foreground.png に透明チャンネルがあると仮定)
composite = Image.alpha_composite(img1.convert('RGBA'), img2.convert('RGBA'))
composite.save('composite.png')

バッチ処理

例

import os
from PIL import Image

input_dir = 'input_images/'
output_dir = 'output_images/'

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

for filename in os.listdir(input_dir):
    if filename.endswith('.jpg'):
        img = Image.open(os.path.join(input_dir, filename))
        # グレースケールに変換して保存
        gray_img = img.convert('L')
        gray_img.save(os.path.join(output_dir, f"gray_{filename}"))
その他の拡張