Data Visualization

Matplotlibによる複数画像の効率的な表示

Spread the love

Matplotlibは、可視化を作成するための強力なPythonライブラリです。一般的なタスクとして、比較のため、または同じデータの異なる側面を説明するために、単一の図の中に複数の画像を表示することがあります。この記事では、これを達成するための2つの効率的な方法を紹介します。add_subplot() を反復的に使用する方法と、再利用可能な関数を作成する方法です。

目次

add_subplot()による反復的なサブプロットの作成

このアプローチは、画像の数が動的な場合に最適です。add_subplot(nrows, ncols, index)は、図の中にサブプロットを作成し、行数、列数、現在のサブプロットのインデックスを指定します。

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import os

image_dir = "path/to/your/images"  # 画像ディレクトリを指定してください

image_files = [f for f in os.listdir(image_dir) if os.path.isfile(os.path.join(image_dir, f))]

if not image_files:
    print("指定されたディレクトリに画像が見つかりません。")
else:
    num_images = len(image_files)
    nrows = int(num_images**0.5)
    ncols = (num_images + nrows - 1) // nrows

    fig, axes = plt.subplots(nrows, ncols, figsize=(15, 10))
    axes = axes.ravel()

    for i, image_file in enumerate(image_files):
        image_path = os.path.join(image_dir, image_file)
        img = mpimg.imread(image_path)
        axes[i].imshow(img)
        axes[i].set_title(image_file)
        axes[i].axis('off')

    #余分なサブプロットを削除
    for j in range(i + 1, len(axes)):
        fig.delaxes(axes[j])


    plt.tight_layout()
    plt.show()

このコードは、画像を反復処理し、mpimg.imread()を使用して読み込み、サブプロットに表示します。plt.tight_layout()は、重なりを防ぎます。「path/to/your/images」を自分のディレクトリに置き換えてください。このコードは、最適なレイアウトのために行数と列数を動的に調整し、空のサブプロットを削除します。

画像表示のための再利用可能な関数

コードの構成と再利用性を向上させるために、画像表示ロジックを関数にカプセル化します。

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

def display_images(image_paths, titles=None, cols=3, figsize=(15, 10)):
    """単一の図に複数の画像を表示します。

    Args:
        image_paths: 画像パスのリスト。
        titles: (オプション) タイトルのリスト。
        cols: サブプロットグリッドの列数。
        figsize: 図のサイズ。
    """
    num_images = len(image_paths)
    rows = (num_images + cols - 1) // cols
    fig, axes = plt.subplots(rows, cols, figsize=figsize)
    axes = axes.ravel()

    for i, image_path in enumerate(image_paths):
        img = mpimg.imread(image_path)
        axes[i].imshow(img)
        if titles:
            axes[i].set_title(titles[i])
        axes[i].axis('off')

    #余分なサブプロットを削除
    for j in range(i + 1, len(axes)):
        fig.delaxes(axes[j])

    plt.tight_layout()
    plt.show()

# 使用例:
image_paths = ["path/to/image1.jpg", "path/to/image2.png", "path/to/image3.jpeg"]  # 画像パスを指定してください
titles = ["画像1", "画像2", "画像3"]
display_images(image_paths, titles)

この関数は、画像パスとオプションのタイトルを受け取り、サブプロットグリッドを動的に計算し、画像を表示します。反復的なアプローチよりも柔軟で再利用可能です。Matplotlibをインストールするには、pip install matplotlibを使用してください。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です