Pillow 高度な画像処理

画像フィルタと強調

組み込みフィルタの適用 (filter())

Pillow は複数の組み込みフィルタを提供しています。ImageFilter モジュールを使用します:

例

from PIL import Image, ImageFilter

# 画像を開く
image = Image.open("input.jpg")

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

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

# エンボスフィルタを適用
emboss = image.filter(ImageFilter.EMBOSS)
emboss.save("emboss.jpg")

# エッジを検出
edges = image.filter(ImageFilter.FIND_EDGES)
edges.save("edges.jpg")

# シャープフィルタ
sharpen = image.filter(ImageFilter.SHARPEN)
sharpen.save("sharpen.jpg")

# スムーズフィルタ
smooth = image.filter(ImageFilter.SMOOTH)
smooth.save("smooth.jpg")

# ディテール強調
detail = image.filter(ImageFilter.DETAIL)
detail.save("detail.jpg")

画像強調 (ImageEnhance モジュール)

ImageEnhance モジュールは、輝度、コントラスト、彩度、シャープネスを制御するツールを提供します:

例

from PIL import Image, ImageEnhance

# 画像を開く
image = Image.open("input.jpg")

# 輝度を強調(factor > 1 で明るく、< 1 で暗く)
enhancer = ImageEnhance.Brightness(image)
brightened = enhancer.enhance(1.5)  # 輝度を50%増加
brightened.save("brightened.jpg")

# コントラストを強調
enhancer = ImageEnhance.Contrast(image)
contrast = enhancer.enhance(1.8)  # コントラストを80%増加
contrast.save("contrast.jpg")

# 彩度を強調
enhancer = ImageEnhance.Color(image)
saturated = enhancer.enhance(1.5)  # 彩度を50%増加
saturated.save("saturated.jpg")

# シャープネスを強調
enhancer = ImageEnhance.Sharpness(image)
sharpened = enhancer.enhance(2.0)  # シャープネスを100%増加
sharpened.save("sharpened.jpg")
カスタム畳み込みカーネル
Pillow では、カスタム畳み込みカーネルを使用して特殊効果を作成できます:
pythonimport numpy as np
from PIL import Image, ImageFilter

# 画像を開く
image = Image.open("input.jpg")

# カスタム畳み込みカーネルを作成
# これはシャープ化の畳み込みカーネルです
kernel = ImageFilter.Kernel(
    size=(3, 3),
    kernel=[-1, -1, -1, -1, 9, -1, -1, -1, -1],
    scale=1
)
sharpened = image.filter(kernel)
sharpened.save("custom_sharpen.jpg")

# エンボス効果の畳み込みカーネル
emboss_kernel = ImageFilter.Kernel(
    size=(3, 3),
    kernel=[-2, -1, 0, -1, 1, 1, 0, 1, 2],
    scale=1,
    offset=128
)
embossed = image.filter(emboss_kernel)
embossed.save("custom_emboss.jpg")

# ガウスぼかしの畳み込みカーネル
gaussian_kernel = ImageFilter.Kernel(
    size=(5, 5),
    kernel=[1, 4, 6, 4, 1, 4, 16, 24, 16, 4, 6, 24, 36, 24, 6, 4, 16, 24, 16, 4, 1, 4, 6, 4, 1],
    scale=256
)
gaussian_blur = image.filter(gaussian_kernel)
gaussian_blur.save("custom_gaussian.jpg")

エッジ検出とシャープ化

組み込みフィルタを使用するだけでなく、より高度なエッジ検出やシャープ化効果も実装できます:

例

from PIL import Image, ImageFilter, ImageChops, ImageOps

# 画像を開く
image = Image.open("input.jpg")

# Sobel エッジ検出
# 水平 Sobel フィルタ
h_sobel = ImageFilter.Kernel(
    size=(3, 3),
    kernel=[-1, 0, 1, -2, 0, 2, -1, 0, 1],
    scale=1
)
# 垂直 Sobel フィルタ
v_sobel = ImageFilter.Kernel(
    size=(3, 3),
    kernel=[-1, -2, -1, 0, 0, 0, 1, 2, 1],
    scale=1
)

h_edges = image.filter(h_sobel)
v_edges = image.filter(v_sobel)

# 水平と垂直のエッジを結合
edges = ImageChops.add(
    ImageChops.multiply(h_edges, h_edges),
    ImageChops.multiply(v_edges, v_edges)
)
edges.save("sobel_edges.jpg")

# 高周波強調によるシャープ化(USM - アンシャープマスク)
def unsharp_mask(image, radius=2, percent=150, threshold=3):
    """USM シャープフィルタを適用
   
パラメータ:
radius: ガウスぼかしの半径
percent: シャープ化の強さ(パーセント)
threshold: シャープ化を適用する最小の輝度変化しきい値
    """

    blurred = image.filter(ImageFilter.GaussianBlur(radius=radius))
    sharpened = Image.blend(image, ImageChops.subtract(image, blurred), percent/100)
    return sharpened

usm_image = unsharp_mask(image, radius=2, percent=200, threshold=5)
usm_image.save("usm_sharpened.jpg")

描画とテキスト追加

基本図形の描画 (ImageDraw モジュール)

例

from PIL import Image, ImageDraw

# 空白のキャンバスを作成
width, height = 800, 600
image = Image.new("RGB", (width, height), color="white")
draw = ImageDraw.Draw(image)

# 線を描画
draw.line([(100, 100), (700, 500)], fill="black", width=5)

# 長方形を描画
draw.rectangle([(200, 200), (600, 400)], outline="red", width=3, fill="yellow")

# 楕円を描画
draw.ellipse([(300, 150), (500, 350)], outline="blue", width=3, fill="lightblue")

# 円を描画
draw.ellipse([(550, 50), (650, 150)], outline="green", width=2, fill="lightgreen")

# 多角形を描画
draw.polygon([(100, 500), (300, 450), (500, 550), (250, 600)],
             outline="purple", fill="lavender")

# 円弧を描画
draw.arc([(400, 400), (600, 500)], start=0, end=180, fill="orange", width=3)

# 点を描画
for i in range(50):
    import random
    x = random.randint(0, width)
    y = random.randint(0, height)
    draw.point((x, y), fill="black")

image.save("drawings.png")

テキストの追加 (text())

例

from PIL import Image, ImageDraw, ImageFont

# 空白のキャンバスを作成
image = Image.new("RGB", (800, 600), color="white")
draw = ImageDraw.Draw(image)

# デフォルトフォントを使用
draw.text((100, 100), "Hello, Pillow!", fill="black")

# カスタム TrueType フォントをロード
try:
    # システムフォントをロードしてみる
    # Windows: "arial.ttf", "simhei.ttf"
    # Mac: "Arial.ttf", "STHeiti Light.ttc"
    # Linux: "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
    font = ImageFont.truetype("arial.ttf", size=36)
except IOError:
    # システムフォントが見つからない場合はデフォルトフォントを使用
    font = ImageFont.load_default()

# カスタムフォントでテキストを描画
draw.text((100, 200), "カスタムフォントテキスト", font=font, fill="blue")

# 縁取り付きテキストを描画
def draw_text_with_outline(draw, text, position, font, text_color, outline_color):
    """輪郭付きテキストを描画"""
    x, y = position
    # 輪郭を描画
    draw.text((x-1, y-1), text, font=font, fill=outline_color)
    draw.text((x+1, y-1), text, font=font, fill=outline_color)
    draw.text((x-1, y+1), text, font=font, fill=outline_color)
    draw.text((x+1, y+1), text, font=font, fill=outline_color)
    # メインテキストを描画
    draw.text((x, y), text, font=font, fill=text_color)

draw_text_with_outline(draw, "輪郭テキスト効果", (100, 300), font, "red", "black")

# テキストサイズを取得して中央に描画
text = "中央揃えテキスト"
text_width, text_height = draw.textsize(text, font=font)
position = ((800 - text_width) // 2, 400)
draw.text(position, text, font=font, fill="purple")

# 複数行テキストを描画
multiline_text = """これは
複数行テキストの例です
Pillow ライブラリを使用
描画しています"""

draw.multiline_text((100, 450), multiline_text, font=font, fill="green", spacing=10, align="center")

image.save("text_drawings.png")

複雑な形状の描画

例

from PIL import Image, ImageDraw
import math

# 空白のキャンバスを作成
width, height = 800, 800
image = Image.new("RGB", (width, height), color="white")
draw = ImageDraw.Draw(image)

# 星形を描画
def draw_star(draw, center, points=5, outer_radius=100, inner_radius=50, rotation=0, **kwargs):
    """星形を描画
   
パラメータ:
center: 中心点の座標タプル (x, y)
points: 星の角の数
outer_radius: 外側の円の半径
inner_radius: 内側の円の半径
rotation: 回転角度(度)
**kwargs: polygon() に渡すパラメータ
    """

    cx, cy = center
    angle = math.pi / points
    rotation_rad = math.radians(rotation)
   
    vertices = []
    for i in range(2 * points):
        radius = outer_radius if i % 2 == 0 else inner_radius
        theta = i * angle + rotation_rad
        x = cx + radius * math.sin(theta)
        y = cy - radius * math.cos(theta)
        vertices.append((x, y))
   
    draw.polygon(vertices, **kwargs)

# 星を描画
draw_star(draw, center=(200, 200), fill="gold", outline="orange", width=2)
draw_star(draw, center=(500, 200), points=8, rotation=22.5,
          outer_radius=120, inner_radius=40, fill="blue", outline="navy", width=2)

# ハート形を描画
def draw_heart(draw, center, size=100, **kwargs):
    """ハート形を描画
   
パラメータ:
center: 中心点の座標タプル (x, y)
size: ハート形のサイズ
**kwargs: polygon() に渡すパラメータ
    """

    cx, cy = center
    vertices = []
    for t in range(100):
        angle = t / 100 * 2 * math.pi
        x = 16 * math.sin(angle) ** 3
        y = 13 * math.cos(angle) - 5 * math.cos(2*angle) - 2 * math.cos(3*angle) - math.cos(4*angle)
        # スケーリングと移動
        vertices.append((cx + x * size / 16, cy - y * size / 16))
   
    draw.polygon(vertices, **kwargs)

draw_heart(draw, center=(200, 500), size=150, fill="red", outline="darkred", width=3)

# 螺旋を描画
def draw_spiral(draw, center, loops=3, radius_start=5, radius_end=100, points=500, **kwargs):
    """螺旋を描画
   
パラメータ:
center: 中心点の座標タプル (x, y)
loops: 螺旋の回転数
radius_start: 開始半径
radius_end: 終了半径
points: 点の数
**kwargs: line() に渡すパラメータ
    """

    cx, cy = center
    vertices = []
   
    for i in range(points + 1):
        # 現在の角度と半径を計算
        angle = i / points * loops * 2 * math.pi
        radius = radius_start + (radius_end - radius_start) * i / points
       
        x = cx + radius * math.cos(angle)
        y = cy + radius * math.sin(angle)
        vertices.append((x, y))
   
    # ポリラインを描画
    for i in range(len(vertices) - 1):
        draw.line([vertices[i], vertices[i+1]], **kwargs)

draw_spiral(draw, center=(500, 500), loops=5, fill="purple", width=2)

image.save("complex_shapes.png")

異なるフォントとスタイルの使用

例

from PIL import Image, ImageDraw, ImageFont
import os

# 空白のキャンバスを作成
image = Image.new("RGB", (800, 600), color="white")
draw = ImageDraw.Draw(image)

# 複数のフォントをロードしてみる
fonts = {
    "default": ImageFont.load_default(),
}

# システムフォントをロードしてみる
try:
    fonts["arial"] = ImageFont.truetype("arial.ttf", size=36)
except IOError:
    pass

try:
    fonts["times"] = ImageFont.truetype("times.ttf", size=36)
except IOError:
    pass

try:
    fonts["simhei"] = ImageFont.truetype("simhei.ttf", size=36)  # 中国語フォント
except IOError:
    pass

# 異なるフォントスタイルを描画
y_position = 50
for font_name, font in fonts.items():
    draw.text((50, y_position), f"Font: {font_name}", font=font, fill="black")
    y_position += 60

# アートテキスト効果を作成
def draw_gradient_text(draw, text, position, font, start_color, end_color, steps=10):
    """グラデーションカラーテキストを描画
   
パラメータ:
draw: ImageDraw オブジェクト
text: 描画するテキスト
position: テキストの位置 (x, y)
font: フォントオブジェクト
start_color: 開始色 (r, g, b)
end_color: 終了色 (r, g, b)
steps: グラデーションのステップ数
    """

    x, y = position
    width, height = draw.textsize(text, font=font)
   
    # 各文字の幅を計算
    char_width = width / len(text)
   
    for i, char in enumerate(text):
        # 現在の文字の色を計算
        progress = i / (len(text) - 1) if len(text) > 1 else 0
        r = int(start_color[0] + (end_color[0] - start_color[0]) * progress)
        g = int(start_color[1] + (end_color[1] - start_color[1]) * progress)
        b = int(start_color[2] + (end_color[2] - start_color[2]) * progress)
        color = (r, g, b)
       
        # 現在の文字を描画
        draw.text((x + i * char_width, y), char, font=font, fill=color)

# グラデーションテキストを適用
if "arial" in fonts:
    draw_gradient_text(
        draw,
        "グラデーションカラーテキスト効果",
        (50, 300),
        fonts["arial"],
        start_color=(255, 0, 0),  # 赤
        end_color=(0, 0, 255)     # 青
    )

# 影付きテキストを適用
def draw_shadow_text(draw, text, position, font, text_color, shadow_color, offset=(3, 3)):
    """影付きテキストを描画"""
    x, y = position
    dx, dy = offset
   
    # 影を描画
    draw.text((x + dx, y + dy), text, font=font, fill=shadow_color)
   
    # メインテキストを描画
    draw.text((x, y), text, font=font, fill=text_color)

# 影の効果を適用
if "arial" in fonts:
    draw_shadow_text(
        draw,
        "影付きテキスト効果",
        (50, 400),
        fonts["arial"],
        text_color=(255, 255, 255),  # 白
        shadow_color=(100, 100, 100),  # グレー
        offset=(3, 3)
    )

image.save("font_styles.png")

画像合成とブレンド

画像の重ね合わせ (paste())

例

from PIL import Image

# 背景画像と前景画像を開く
try:
    background = Image.open("background.jpg")
    foreground = Image.open("foreground.png")
except IOError:
    # 画像ファイルがない場合は、サンプル画像を作成
    background = Image.new("RGB", (800, 600), color="lightblue")
    foreground = Image.new("RGBA", (200, 200), color=(255, 0, 0, 128))  # 半透明の赤い四角形

# 前景画像のサイズを調整(任意)
foreground = foreground.resize((300, 300))

# 貼り付け位置を計算(中央)
paste_position = (
    (background.width - foreground.width) // 2,
    (background.height - foreground.height) // 2
)

# 単純に貼り付け(透明度を考慮しない)
simple_paste = background.copy()
simple_paste.paste(foreground, paste_position)
simple_paste.save("simple_paste.png")

# 透明度を使用して貼り付け(前景にアルファチャンネルがある場合)
if foreground.mode == 'RGBA':
    alpha_paste = background.copy()
    alpha_paste.paste(foreground, paste_position, foreground)
    alpha_paste.save("alpha_paste.png")

透明度の処理 (アルファチャンネル)

例

from PIL import Image

# アルファチャンネル付きの画像を作成
width, height = 500, 500
image = Image.new("RGBA", (width, height), color=(0, 0, 0, 0))  # 完全に透明

# グラデーション透明効果を生成
for y in range(height):
    for x in range(width):
        # 左から右へ透明度が減少(完全不透明から完全透明へ)
        alpha = 255 - int(255 * x / width)
        # 色を上から下へグラデーション
        r = int(255 * y / height)
        g = int(255 * (1 - y / height))
        b = 128
        image.putpixel((x, y), (r, g, b, alpha))

image.save("alpha_gradient.png")

# RGB画像をアルファチャンネル付きの画像に変換
def add_alpha_channel(image, alpha_value=128):
    """RGB画像にアルファチャンネルを追加
   
パラメータ:
image: PIL Image オブジェクト
alpha_value: 透明度値 (0-255)
    """

    if image.mode != 'RGBA':
        # RGBAモードに変換
        rgba_image = image.convert("RGBA")
       
        # ピクセルデータを取得
        data = rgba_image.getdata()
       
        # 透明度を設定
        new_data = []
        for item in data:
            # ピクセルのアルファ値を変更
            if len(item) == 4:  # すでにRGBA
                new_data.append((item[0], item[1], item[2], alpha_value))
            else:  # RGB
                new_data.append((item[0], item[1], item[2], alpha_value))
       
        rgba_image.putdata(new_data)
        return rgba_image
    return image

# サンプルのRGB画像を作成
rgb_image = Image.new("RGB", (300, 300), color="blue")
# アルファチャンネルを追加
rgba_image = add_alpha_channel(rgb_image, alpha_value=128)
rgba_image.save("with_alpha.png")

# 円形マスクを作成
def create_circular_mask(image, radius=None):
    """円形マスクを作成
   
パラメータ:
image: PIL Image オブジェクト
radius: 円の半径。デフォルトは画像の短い辺の半分
    """

    width, height = image.width, image.height
    center_x, center_y = width // 2, height // 2
   
    if radius is None:
        radius = min(center_x, center_y)
   
    # 新しい透明な画像を作成
    mask = Image.new('L', (width, height), 0)
   
    # 円形マスクを作成
    for y in range(height):
        for x in range(width):
            # 中心までの距離を計算
            distance = ((x - center_x) ** 2 + (y - center_y) ** 2) ** 0.5
           
            # 円の内側なら不透明に設定
            if distance <= radius:
                mask.putpixel((x, y), 255)
   
    # マスクを元画像に適用
    if image.mode != 'RGBA':
        image = image.convert('RGBA')
   
    result = Image.new('RGBA', (width, height), (0, 0, 0, 0))
    result.paste(image, (0, 0), mask)
   
    return result

# サンプル画像を作成
square_image = Image.new("RGB", (300, 300), color="green")
# 円形マスクを適用
circular_image = create_circular_mask(square_image)
circular_image.save("circular_image.png")

ブレンドモード (blend())

例

from PIL import Image, ImageChops

# 2つのサンプル画像を作成
width, height = 500, 500
image1 = Image.new("RGB", (width, height), color="blue")
image2 = Image.new("RGB", (width, height), color="yellow")

# 画像にグラデーションを描画
for y in range(height):
    for x in range(width):
        # 画像1: 左から右へ青から黒へ
        blue_value = max(0, 255 - int(255 * x / width))
        image1.putpixel((x, y), (0, 0, blue_value))
       
        # 画像2: 上から下へ黄から赤へ
        red_value = int(255 * y / height)
        green_value = max(0, 255 - int(255 * y / height))
        image2.putpixel((x, y), (red_value, green_value, 0))

image1.save("gradient1.png")
image2.save("gradient2.png")

# さまざまな混合モード

# 1. 通常混合 (blend)
blend_result = Image.blend(image1, image2, alpha=0.5)
blend_result.save("blend.png")

# 2. 加算 (add)
add_result = ImageChops.add(image1, image2)
add_result.save("add.png")

# 3. スクリーン (screen)
screen_result = ImageChops.screen(image1, image2)
screen_result.save("screen.png")

# 4. 乗算 (multiply)
multiply_result = ImageChops.multiply(image1, image2)
multiply_result.save("multiply.png")

# 5. 差分 (difference)
difference_result = ImageChops.difference(image1, image2)
difference_result.save("difference.png")

# 6. 除外 (invert)
invert_result = ImageChops.invert(image1)
invert_result.save("invert.png")

# 7. 明度 (lighter)
lighter_result = ImageChops.lighter(image1, image2)
lighter_result.save("lighter.png")

# 8. 暗度 (darker)
darker_result = ImageChops.darker(image1, image2)
darker_result.save("darker.png")

# カスタム混合関数を作成
def custom_blend(image1, image2, mode="soft_light"):
    """カスタム混合モード
   
パラメータ:
image1, image2: 混合する2つの画像
mode: 混合モード名
    """

    if image1.mode != image2.mode:
        raise ValueError("2つの画像は同じモードを持つ必要があります")
   
    width, height = image1.size
    result = Image.new(image1.mode, (width, height))
   
    for y in range(height):
        for x in range(width):
            r1, g1, b1 = image1.getpixel((x, y))
            r2, g2, b2 = image2.getpixel((x, y))
           
            if mode == "soft_light":
                # ソフトライト混合モードを実装
                r = (r1 * (255 - r2) + r2 * r2 // 255) // 255
                g = (g1 * (255 - g2) + g2 * g2 // 255) // 255
                b = (b1 * (255 - b2) + b2 * b2 // 255) // 255
            elif mode == "hard_light":
                # ハードライト混合モードを実装
                if r2 < 128:
                    r = (2 * r1 * r2) // 255
                else:
                    r = 255 - (2 * (255 - r1) * (255 - r2)) // 255
               
                if g2 < 128:
                    g = (2 * g1 * g2) // 255
                else:
                    g = 255 - (2 * (255 - g1) * (255 - g2)) // 255
               
                if b2 < 128:
                    b = (2 * b1 * b2) // 255
                else:
                    b = 255 - (2 * (255 - b1) * (255 - b2)) // 255
            elif mode == "overlay":
                # オーバーレイ混合モードを実装
                if r1 < 128:
                    r = (2 * r1 * r2) // 255
                else:
                    r = 255 - (2 * (255 - r1) * (255 - r2)) // 255
               
                if g1 < 128:
                    g = (2 * g1 * g2) // 255
                else:
                    g = 255 - (2 * (255 - g1) * (255 - g2)) // 255
               
                if b1 < 128:
                    b = (2 * b1 * b2) // 255
                else:
                    b = 255 - (2 * (255 - b1) * (255 - b2)) // 255
            else:
                # デフォルト: 通常混合を使用
                r = (r1 + r2) // 2
                g = (g1 + g2) // 2
                b = (b1 + b2) // 2
           
            result.putpixel((x, y), (r, g, b))
   
    return result

# カスタム混合モードを適用
soft_light = custom_blend(image1, image2, mode="soft_light")
soft_light.save("soft_light.png")

hard_light = custom_blend(image1, image2, mode="hard_light")
hard_light.save("hard_light.png")

overlay = custom_blend(image1, image2, mode="overlay")
overlay.save("overlay.png")

マスク適用と高度な合成技術

マスクの適用

例

from PIL import Image, ImageDraw

# サンプル画像を作成
width, height = 500, 500
image = Image.new("RGB", (width, height), color="purple")

# グラデーションを作成
for y in range(height):
    for x in range(width):
        # 左上から右下へのグラデーション
        r = int(255 * (x + y) / (width + height))
        g = int(128 * x / width)
        b = int(255 * (1 - y / height))
        image.putpixel((x, y), (r, g, b))

# マスク画像を作成 (Lモードはグレースケール画像)
mask = Image.new('L', (width, height), 0)
draw = ImageDraw.Draw(mask)

# マスク上に形状を描画
# 中心からの放射状グラデーションマスク
center_x, center_y = width // 2, height // 2
max_distance = (width**2 + height**2)**0.5 / 2

for y in range(height):
    for x in range(width):
        # 点から中心までの距離を計算
        distance = ((x - center_x)**2 + (y - center_y)**2)**0.5
        # 距離に基づいて透明度を設定(遠いほど透明)
        alpha = max(0, int(255 * (1 - distance / max_distance)))
        mask.putpixel((x, y), alpha)

# 確認用にマスクを保存
mask.save("radial_mask.png")

# 空白のターゲット画像を作成
result = Image.new("RGBA", (width, height), (0, 0, 0, 0))

# マスクを元画像に適用
result.paste(image, (0, 0), mask)
result.save("radial_masked.png")

# カスタム形状のマスクを作成
shape_mask = Image.new('L', (width, height), 0)
draw = ImageDraw.Draw(shape_mask)

# 多角形マスクを描画
polygon_points = [
    (width//4, height//4),
    (3*width//4, height//4),
    (width, height//2),
    (3*width//4, 3*height//4),
    (width//4, 3*height//4),
    (0, height//2)
]
draw.polygon(polygon_points, fill=255)
shape_mask.save("polygon_mask.png")

# 多角形マスクを適用
poly_result = Image.new("RGBA", (width, height), (0, 0, 0, 0))
poly_result.paste(image, (0, 0), shape_mask)
poly_result.save("polygon_masked.png")

# テキストマスクを作成
text_mask = Image.new('L', (width, height), 0)
draw = ImageDraw.Draw(text_mask)

# カスタムフォントの読み込みを試み、失敗したらデフォルトフォントを使用
try:
    from PIL import ImageFont
    font = ImageFont.truetype("arial.ttf", 120)
except IOError:
    font = ImageFont.load_default()

# マスク上にテキストを描画
text = "PILLOW"
text_width, text_height = draw.textsize(text, font=font)
position = ((width - text_width) // 2, (height - text_height) // 2)
draw.text(position, text, fill=255, font=font)
text_mask.save("text_mask.png")

# テキストマスクを適用
text_result = Image.new("RGBA", (width, height), (0, 0, 0, 0))
text_result.paste(image, (0, 0), text_mask)
text_result.save("text_masked.png")

高度な画像ブレンドと合成効果

さらに高度な画像混合と合成効果を探ってみましょう:

例

from PIL import Image, ImageFilter, ImageChops, ImageOps
import math

# 2つのサンプル画像を作成
width, height = 500, 500
image1 = Image.new("RGB", (width, height), color="blue")
image2 = Image.new("RGB", (width, height), color="yellow")

# 画像にグラデーションを描画
for y in range(height):
    for x in range(width):
        # 画像1: 左から右へ青から黒へ
        blue_value = max(0, 255 - int(255 * x / width))
        image1.putpixel((x, y), (0, 0, blue_value))
       
        # 画像2: 上から下へ黄から赤へ
        red_value = int(255 * y / height)
        green_value = max(0, 255 - int(255 * y / height))
        image2.putpixel((x, y), (red_value, green_value, 0))

# 遷移混合効果
def transition_blend(image1, image2, direction="horizontal", steps=10):
    """2つの画像間のスムーズな遷移効果を作成
   
パラメータ:
image1, image2: 混合する2つの画像
direction: 遷移方向。"horizontal" または "vertical"
steps: 遷移ステップ数
    """

    if image1.size != image2.size:
        raise ValueError("2つの画像は同じサイズである必要があります")
   
    width, height = image1.size
    result = Image.new(image1.mode, (width, height))
   
    for y in range(height):
        for x in range(width):
            if direction == "horizontal":
                # 水平遷移: 左から右へ
                blend_factor = x / width
            elif direction == "vertical":
                # 垂直遷移: 上から下へ
                blend_factor = y / height
            elif direction == "radial":
                # 放射状遷移: 中心から外へ
                center_x, center_y = width // 2, height // 2
                distance = ((x - center_x)**2 + (y - center_y)**2)**0.5
                max_distance = max((width**2 + height**2)**0.5 / 2, 1)
                blend_factor = min(1.0, distance / max_distance)
            else:
                blend_factor = 0.5  # デフォルトは均一混合
           
            # 2つの画像のピクセルを取得
            r1, g1, b1 = image1.getpixel((x, y))
            r2, g2, b2 = image2.getpixel((x, y))
           
            # 混合ピクセルを計算
            r = int(r1 * (1 - blend_factor) + r2 * blend_factor)
            g = int(g1 * (1 - blend_factor) + g2 * blend_factor)
            b = int(b1 * (1 - blend_factor) + b2 * blend_factor)
           
            result.putpixel((x, y), (r, g, b))
   
    return result

# 水平遷移を作成
horizontal_transition = transition_blend(image1, image2, direction="horizontal")
horizontal_transition.save("horizontal_transition.png")

# 垂直遷移を作成
vertical_transition = transition_blend(image1, image2, direction="vertical")
vertical_transition.save("vertical_transition.png")

# 放射状遷移を作成
radial_transition = transition_blend(image1, image2, direction="radial")
radial_transition.save("radial_transition.png")

# チェッカーボード混合効果を作成
def checkerboard_blend(image1, image2, grid_size=50):
    """チェッカーボード混合効果を作成
   
パラメータ:
image1, image2: 混合する2つの画像
grid_size: チェッカーボードのサイズ
    """

    if image1.size != image2.size:
        raise ValueError("2つの画像は同じサイズである必要があります")
   
    width, height = image1.size
    result = Image.new(image1.mode, (width, height))
   
    for y in range(height):
        for x in range(width):
            # 現在のピクセルがどのマスにあるかを判定
            grid_x = x // grid_size
            grid_y = y // grid_size
           
            # チェッカーボードパターンに基づいて画像を選択
            if (grid_x + grid_y) % 2 == 0:
                result.putpixel((x, y), image1.getpixel((x, y)))
            else:
                result.putpixel((x, y), image2.getpixel((x, y)))
   
    return result

# チェッカーボード混合を作成
checkerboard = checkerboard_blend(image1, image2, grid_size=50)
checkerboard.save("checkerboard_blend.png")

# ノイズ混合効果
def noise_blend(image1, image2, noise_level=0.5):
    """ノイズを使用して混合
   
パラメータ:
image1, image2: 混合する2つの画像
noise_level: ノイズレベル (0.0-1.0)
    """

    if image1.size != image2.size:
        raise ValueError("2つの画像は同じサイズである必要があります")
   
    import random
    width, height = image1.size
    result = Image.new(image1.mode, (width, height))
   
    for y in range(height):
        for x in range(width):
            # ランダム値を生成
            random_value = random.random()
           
            # ランダム値とノイズレベルに基づいて画像を選択
            if random_value < noise_level:
                result.putpixel((x, y), image1.getpixel((x, y)))
            else:
                result.putpixel((x, y), image2.getpixel((x, y)))
   
    return result

# ノイズ混合を作成
noise_blended = noise_blend(image1, image2, noise_level=0.5)
noise_blended.save("noise_blend.png")

# 流動的な混合効果を作成
def fluid_blend(image1, image2, turbulence=10.0, seed=42):
    """流動的な混合効果を作成
   
パラメータ:
image1, image2: 混合する2つの画像
turbulence: 乱流の強さ
seed: 乱数シード
    """

    if image1.size != image2.size:
        raise ValueError("2つの画像は同じサイズである必要があります")
   
    import random
    random.seed(seed)
    width, height = image1.size
    result = Image.new(image1.mode, (width, height))
   
    # 簡略化されたPerlinノイズ実装を作成
    def noise(x, y):
        # 簡略化されたノイズ関数
        n = x + y * 57
        n = (n << 13) ^ n
        return (1.0 - ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0)
   
    for y in range(height):
        for x in range(width):
            # 歪んだ座標を使って混合係数を生成
            noise_value = noise(x / turbulence, y / turbulence)
            blend_factor = (noise_value + 1.0) / 2.0  # 0-1の範囲に正規化
           
            # 2つの画像のピクセルを取得
            r1, g1, b1 = image1.getpixel((x, y))
            r2, g2, b2 = image2.getpixel((x, y))
           
            # 混合ピクセルを計算
            r = int(r1 * (1 - blend_factor) + r2 * blend_factor)
            g = int(g1 * (1 - blend_factor) + g2 * blend_factor)
            b = int(b1 * (1 - blend_factor) + b2 * blend_factor)
           
            result.putpixel((x, y), (r, g, b))
   
    return result

# 流動的な混合を作成
fluid_blended = fluid_blend(image1, image2, turbulence=20.0)
fluid_blended.save("fluid_blend.png")

グラデーションマスクと複雑な合成効果の作成

例

from PIL import Image, ImageDraw, ImageFilter, ImageOps
import math

# デモ画像を作成
width, height = 600, 400
original = Image.new("RGB", (width, height), color=(30, 30, 30))

# いくつかの形状を描画
draw = ImageDraw.Draw(original)
draw.rectangle([(50, 50), (width-50, height-50)], outline="white", width=2)
draw.ellipse([(100, 100), (width-100, height-100)], outline="blue", width=3)
draw.line([(width//2, 50), (width//2, height-50)], fill="red", width=5)
draw.line([(50, height//2), (width-50, height//2)], fill="green", width=5)

# 元の画像を保存
original.save("original_composite.png")

# グラデーションマスクを作成
def create_gradient_mask(size, direction="horizontal", start=0, end=255):
    """グラデーションマスクを作成
   
パラメータ:
size: マスクサイズ (width, height)
direction: グラデーション方向 "horizontal", "vertical", "radial", "diagonal"
start: 開始の明度値 (0-255)
end: 終了の明度値 (0-255)
    """

    width, height = size
    mask = Image.new('L', size, 0)
   
    for y in range(height):
        for x in range(width):
            if direction == "horizontal":
                # 水平グラデーション
                value = start + int((end - start) * x / width)
            elif direction == "vertical":
                # 垂直グラデーション
                value = start + int((end - start) * y / height)
            elif direction == "radial":
                # 放射状グラデーション
                center_x, center_y = width // 2, height // 2
                max_dist = math.sqrt((width/2)**2 + (height/2)**2)
                dist = math.sqrt((x - center_x)**2 + (y - center_y)**2)
                value = start + int((end - start) * (dist / max_dist))
            elif direction == "diagonal":
                # 対角線グラデーション
                value = start + int((end - start) * (x + y) / (width + height))
            else:
                value = 0
           
            # 値を0-255の範囲内に保証
            value = max(0, min(255, value))
            mask.putpixel((x, y), value)
   
    return mask

# 異なる方向のグラデーションマスクを作成
horizontal_mask = create_gradient_mask((width, height), direction="horizontal")
horizontal_mask.save("horizontal_mask.png")

vertical_mask = create_gradient_mask((width, height), direction="vertical")
vertical_mask.save("vertical_mask.png")

radial_mask = create_gradient_mask((width, height), direction="radial")
radial_mask.save("radial_mask.png")

diagonal_mask = create_gradient_mask((width, height), direction="diagonal")
diagonal_mask.save("diagonal_mask.png")

# 混合用の新しい画像を作成
new_image = Image.new("RGB", (width, height))
for y in range(height):
    for x in range(width):
        # 複雑なカラーパターンを作成
        r = int(255 * (0.5 + 0.5 * math.sin(x / 30)))
        g = int(255 * (0.5 + 0.5 * math.cos(y / 20)))
        b = int(255 * (0.5 + 0.5 * math.sin((x + y) / 40)))
        new_image.putpixel((x, y), (r, g, b))

new_image.save("pattern_image.png")

# 異なるマスク効果を適用
def apply_mask_blend(image1, image2, mask):
    """マスクを使用して2つの画像を混合
   
パラメータ:
image1, image2: 混合する2つの画像
mask: グレースケールマスク画像
    """

    if image1.size != image2.size or image1.size != mask.size:
        raise ValueError("すべての画像は同じサイズである必要があります")
   
    width, height = image1.size
    result = Image.new(image1.mode, (width, height))
   
    for y in range(height):
        for x in range(width):
            # マスク値を取得 (0-255)
            mask_value = mask.getpixel((x, y))
            blend_factor = mask_value / 255.0
           
            # 2つの画像のピクセルを取得
            pixel1 = image1.getpixel((x, y))
            pixel2 = image2.getpixel((x, y))
           
            # ピクセルの深さに基づいて混合
            if len(pixel1) == 3:  # RGB
                r1, g1, b1 = pixel1
                r2, g2, b2 = pixel2
               
                r = int(r1 * (1 - blend_factor) + r2 * blend_factor)
                g = int(g1 * (1 - blend_factor) + g2 * blend_factor)
                b = int(b1 * (1 - blend_factor) + b2 * blend_factor)
               
                result.putpixel((x, y), (r, g, b))
            elif len(pixel1) == 4:  # RGBA
                r1, g1, b1, a1 = pixel1
                r2, g2, b2, a2 = pixel2
               
                r = int(r1 * (1 - blend_factor) + r2 * blend_factor)
                g = int(g1 * (1 - blend_factor) + g2 * blend_factor)
                b = int(b1 * (1 - blend_factor) + b2 * blend_factor)
                a = int(a1 * (1 - blend_factor) + a2 * blend_factor)
               
                result.putpixel((x, y), (r, g, b, a))
   
    return result

# 異なるマスク混合を適用
horizontal_blend = apply_mask_blend(original, new_image, horizontal_mask)
horizontal_blend.save("horizontal_blend.png")

vertical_blend = apply_mask_blend(original, new_image, vertical_mask)
vertical_blend.save("vertical_blend.png")

radial_blend = apply_mask_blend(original, new_image, radial_mask)
radial_blend.save("radial_blend.png")

diagonal_blend = apply_mask_blend(original, new_image, diagonal_mask)
diagonal_blend.save("diagonal_blend.png")

# パターンマスクを作成
def create_pattern_mask(size, pattern_type="grid", scale=40):
    """パターンマスクを作成
   
パラメータ:
size: マスクサイズ (width, height)
pattern_type: パターンタイプ "grid", "dots", "stripes", "waves"
scale: パターンのスケール係数
    """

    width, height = size
    mask = Image.new('L', size, 0)
   
    for y in range(height):
        for x in range(width):
            value = 0
           
            if pattern_type == "grid":
                グリッドパターン
                if x % scale < scale // 2 or y % scale < scale // 2:
                    value = 255
            elif pattern_type == "dots":
                ドットパターン
                dist_to_center = math.sqrt(((x % scale) - scale/2)**2 +
                                        ((y % scale) - scale/2)**2)
                if dist_to_center < scale // 4:
                    value = 255
            elif pattern_type == "stripes":
                ストライプパターン
                if (x + y) % scale < scale // 2:
                    value = 255
            elif pattern_type == "waves":
                ウェーブパターン
                value = int(127.5 + 127.5 * math.sin(x / scale) * math.cos(y / scale))
            else:
                value = 0
           
            mask.putpixel((x, y), value)
   
    return mask

異なるパターンマスクの作成
grid_mask = create_pattern_mask((width, height), pattern_type="grid", scale=30)
grid_mask.save("grid_mask.png")

dots_mask = create_pattern_mask((width, height), pattern_type="dots", scale=30)
dots_mask.save("dots_mask.png")

stripes_mask = create_pattern_mask((width, height), pattern_type="stripes", scale=20)
stripes_mask.save("stripes_mask.png")

waves_mask = create_pattern_mask((width, height), pattern_type="waves", scale=40)
waves_mask.save("waves_mask.png")

パターンマスクブレンドの適用
grid_blend = apply_mask_blend(original, new_image, grid_mask)
grid_blend.save("grid_blend.png")

dots_blend = apply_mask_blend(original, new_image, dots_mask)
dots_blend.save("dots_blend.png")

stripes_blend = apply_mask_blend(original, new_image, stripes_mask)
stripes_blend.save("stripes_blend.png")

waves_blend = apply_mask_blend(original, new_image, waves_mask)
waves_blend.save("waves_blend.png")
その他の拡張