私的AI研究会 > AI_Program3

生成 AI プログラミング3 == 編集中 ==

sd_037_512_m.jpg

 これまで検証してきた結果をもとに、Python で生成 AI プログラムを書く

▲ 目 次
※ 最終更新:2025/06/17 

diffusersではじめめる Stable Diffusion (実践編)

 画像生成のプログラムを書く

Step 40:テキストから画像を生成する

 基本のサンプル・コード
  1. 「sd_040.py」
    ## sd_040.py【SD1.5】 テキストから画像生成(txt2img)サンプル・ソースコード
    ##      Ver. 1.00   2025/06/16
    
    import torch
    from diffusers import StableDiffusionPipeline, logging
    from translate import Translator
    
    logging.set_verbosity_error()
    
    # モデルのフォルダーのパス
    model_path = "/StabilityMatrix/Data/Models/StableDiffusion/SD1.5/v1-5-pruned-emaonly.safetensors"        # モデル
    
    # GPUを使う場合は"cuda" 使わない場合は"cpu"
    device = 'cuda'
    
    # seed 値
    seed = 12345678
    
    # パイプラインを作成
    pipeline = StableDiffusionPipeline.from_single_file(model_path).to(device)
    
    # プロンプト
    trans = Translator('en','ja').translate
    prompt_jp = '満開の蘭'                                                                                   # プロンプト
    prompt = trans(prompt_jp)
    
    # Generatorオブジェクト作成
    generator = torch.Generator(device).manual_seed(seed)
    
    print(f'Seed: {seed}, Model: {model_path}')
    print(f'prompt : {prompt_jp} → {prompt}')
    
    # 画像を生成
    image = pipeline(
                        prompt=prompt,
                        num_inference_steps = 30,
                        guidance_scale = 7.5,
                        width = 512,
                        height = 512,
                        generator = generator,
                        ).images[0]
    image.save("results/sd_040.png")                                                                     # 生成画像
  2. プログラムを実行する(実行時間:約 3秒 RTX 4070 Ti 12GB)
    (sd_test) PS > python sd_040.py
    
    Fetching 11 files: 100%|████████████████████| 11/11 [00:00<00:00, 11048.21it/s]
    Loading pipeline components...: 100%|████████████| 6/6 [00:00<00:00,  8.85it/s]
    Seed: 12345678, Model: /StabilityMatrix/Data/Models/StableDiffusion/SD1.5/v1-5-pruned-emaonly.safetensors
    prompt : 満開の蘭 → Orchid in full bloom
    100%|██████████████████████████████████████████| 30/30 [00:03<00:00,  8.31it/s]
  3. 画像ファイル「sd_040.png」が生成される

Step 41: ~ コマンドラインからパラメータ入力 ~

Step 42: ~ GUI プログラム ~

       :

Step 50:画像から画像を生成する

 基本のサンプル・コード
  1. 「sd_img2img.py」
    ## sd_img2img.py【SD1.5】 画像から画像生成(img2img)サンプル・ソースコード
    ##      Ver. 1.00   2025/06/16
    
    import torch
    from PIL import Image
    from diffusers import StableDiffusionImg2ImgPipeline,DPMSolverMultistepScheduler, logging
    from translate import Translator
    
    logging.set_verbosity_error()
    
    # モデルフォルダーのパス
    model_path = "/StabilityMatrix/Data/Models/StableDiffusion/SD1.5/v1-5-pruned-emaonly.safetensors"       # モデル
    image_path = "images/kamo.jpg"                                                                          # 元画像
    
    # GPUを使う場合は"cuda" 使わない場合は"cpu"
    device = 'cuda'
    
    # seed 値
    seed = 12345678
    
    # パイプラインを作成
    pipeline = StableDiffusionImg2ImgPipeline.from_single_file(
                        model_path,
                        torch_dtype = torch.float16,
                        ).to(device)
    
    # スケジューラ設定
    pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
    
    # プロンプト
    trans = Translator('en','ja').translate
    prompt_jp = '兎'                                                                                      # プロンプト
    prompt = trans(prompt_jp)
    src_image = Image.open(image_path)
    
    # Generatorオブジェクト作成
    generator = torch.Generator(device).manual_seed(seed)
    
    print(f'Seed: {seed}, Model: {model_path}')
    print(f'prompt : {prompt_jp} → {prompt}')
    
    # 画像を生成
    image = pipeline(
                        prompt = prompt,
                        image = src_image,
                        num_inference_steps = 30,
                        guidance_scale = 7,
                        strength = 0.6,
                        generator = generator
                        ).images[0]
    
    image.save("results/sd_img2img.png")                                                                    # 生成画像
  2. プログラムを実行する(実行時間:約 5秒 RTX 4070 Ti 12GB)
    (sd_test) PS > python sd_img2img.py
    
    Fetching 11 files: 100%|███████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|████████████| 6/6 [00:01<00:00,  3.51it/s]
    Seed: 12345678, Model: /StabilityMatrix/Data/Models/StableDiffusion/SD1.5/v1-5-pruned-emaonly.safetensors
    prompt : 兎 → Domestic Rabbit
    100%|██████████████████████████████████████████| 18/18 [00:04<00:00,  3.78it/s]
    (sd_test) PS D:\anaconda_win\workspace_3\sd_test> python sd_037.py
  3. 画像ファイル「sd_img2img.png」が生成される

Step 51: ~ コマンドラインからパラメータ入力 ~

       :

Step 52: ~ GUI プログラム ~

       :

Step 60:統合した『私的 AI 生成プログラム』

       :
 

忘備録

 

更新履歴

参考資料