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?

google colaboratory bitmap画像へ変換

Last updated at Posted at 2025-10-23

■画像をビットマップへ変換する。

・実行環境:google colaboratory

■ソース


"""
Google Colab用 画像BMP変換プログラム
指定フォルダ内の画像を全てBMP形式に変換
"""

from PIL import Image
import os
from pathlib import Path

def convert_images_to_bmp(input_folder, output_folder=None):
    """
    指定フォルダ内の画像をBMP形式に変換
    
    Parameters:
    -----------
    input_folder : str
        変換したい画像が入っているフォルダのパス
    output_folder : str, optional
        変換後の画像を保存するフォルダのパス(指定しない場合は入力フォルダ内に保存)
    """
    
    # 入力フォルダの存在確認
    if not os.path.exists(input_folder):
        print(f"エラー: フォルダ '{input_folder}' が見つかりません")
        return
    
    # 出力フォルダの設定
    if output_folder is None:
        output_folder = input_folder
    else:
        os.makedirs(output_folder, exist_ok=True)
    
    # 対応する画像形式
    supported_formats = {'.jpg', '.jpeg', '.png', '.gif', '.tiff', '.tif', '.webp'}
    
    # 変換カウンター
    converted_count = 0
    skipped_count = 0
    error_count = 0
    
    print(f"変換開始: {input_folder}")
    print("-" * 50)
    
    # フォルダ内の全ファイルを処理
    for filename in os.listdir(input_folder):
        file_path = os.path.join(input_folder, filename)
        
        # ファイルでない場合はスキップ
        if not os.path.isfile(file_path):
            continue
        
        # 拡張子を取得
        file_ext = Path(filename).suffix.lower()
        
        # すでにBMPの場合はスキップ
        if file_ext == '.bmp':
            print(f"スキップ: {filename} (既にBMP形式)")
            skipped_count += 1
            continue
        
        # 対応していない形式はスキップ
        if file_ext not in supported_formats:
            continue
        
        try:
            # 画像を開く
            img = Image.open(file_path)
            
            # RGBAモードの場合はRGBに変換(BMPは透明度をサポートしないため)
            if img.mode == 'RGBA':
                # 白背景で合成
                background = Image.new('RGB', img.size, (255, 255, 255))
                background.paste(img, mask=img.split()[3])  # アルファチャンネルをマスクとして使用
                img = background
            elif img.mode not in ('RGB', 'L'):
                # その他のモードはRGBに変換
                img = img.convert('RGB')
            
            # 出力ファイル名を生成
            output_filename = Path(filename).stem + '.bmp'
            output_path = os.path.join(output_folder, output_filename)
            
            # BMPとして保存
            img.save(output_path, 'BMP')
            
            print(f"変換完了: {filename}{output_filename}")
            converted_count += 1
            
        except Exception as e:
            print(f"エラー: {filename} の変換に失敗しました ({str(e)})")
            error_count += 1
    
    # 結果サマリー
    print("-" * 50)
    print(f"変換完了: {converted_count}")
    print(f"スキップ: {skipped_count}")
    print(f"エラー: {error_count}")
    print(f"出力先: {output_folder}")


# ===== Google Colab での使用例 =====

# 例1: 同じフォルダ内で変換
# convert_images_to_bmp('/content/images')

# 例2: 別のフォルダに保存
# convert_images_to_bmp('/content/images', '/content/converted_images')

# 例3: Google Driveをマウントして使用
# from google.colab import drive
# drive.mount('/content/drive')
# convert_images_to_bmp('/content/drive/MyDrive/画像フォルダ')

# 実行例(フォルダパスを指定)
if __name__ == "__main__":
    # ここにフォルダパスを指定して実行
    input_path = '/content/drive/MyDrive/ネギA_本番テスト1022/'  # 変換したい画像があるフォルダ
    output_path = '/content/drive/MyDrive/ネギA_本番テスト1022/bmp画像変換/'  # 変換後の保存先(省略可)
    
    print("=" * 50)
    print("画像BMP変換プログラム")
    print("=" * 50)
    
    # フォルダが存在しない場合は作成(テスト用)
    # os.makedirs(input_path, exist_ok=True)
    
    # 変換実行
    convert_images_to_bmp(input_path, output_path)

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?