私的AI研究会 > AI_Program3

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

image_040_m.jpg

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

▲ 目 次
※ 最終更新:2025/07/11 

diffusersではじめめる Stable Diffusion (応用編2)

 画像から画像を生成する instruct-pix2pixcontrolnet instruct-pix2pix

 参考サイト:instruct-pix2pixで画像を指示した通り変更したり

概要

動作環境

Step 40:「instruct-pix2pix」で画像を変換する

  SD1.5 版  「雪の中の場面にする」

  1. 「sd_040.py」  生成画像(左) image_040.png 元になる画像(右) sd_040_test.png
    ## sd_040.py【SD1.5】 画像から画像生成(instruct-pix2pix)サンプル・ソースコード
    ##      https://qiita.com/phyblas/items/28c342740c2ed00250b8
    ##      Model: https://huggingface.co/timbrooks/instruct-pix2pix
    ##      Ver. 0.00   2025/07/05
    
    import torch
    from PIL import Image
    from diffusers import StableDiffusionInstructPix2PixPipeline, logging
    from translate import Translator
    
    logging.set_verbosity_error()
    
    # フォルダーのパス
    model_path = "timbrooks/instruct-pix2pix"                       # モデル
    image_path = "images/sd_040_test.png"                           # 元画像
    
    # GPUを使う場合は"cuda" 使わない場合は"cpu"
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    
    # seed 値
    seed = 0
    
    # パイプラインを作成
    if device == 'cpu':
        pipeline = StableDiffusionInstructPix2PixPipeline.from_pretrained(model_path).to(device)
    else:
        pipeline = StableDiffusionInstructPix2PixPipeline.from_pretrained(
                        model_path,
                        torch_dtype = torch.float16,
                        ).to(device)
    
    # プロンプト
    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'source_image: {image_path}')
    print(f'prompt : {prompt_jp} → {prompt}')
    
    # 画像を生成
    image = pipeline(
                        prompt = prompt,
                        image = src_image,
                        num_inference_steps = 20,
                        image_guidance_scale = 1.5,
                        generator = generator
                        ).images[0]
    
    image.save("results/image_040.png")                            # 生成画像
  2. プログラムを実行する(実行時間:約 3秒 RTX 4070 Ti 12GB)
    (sd_test) PS > python sd_040.py
    Loading pipeline components...: 100%|████████████| 7/7 [00:02<00:00,  2.48it/s]
    Seed: 0, Model: timbrooks/instruct-pix2pix
    source_image: images/sd_040_test.png
    prompt : 雪の中の場面にする → Make it a scene in the snow
    100%|██████████████████████████████████████████| 20/20 [00:01<00:00, 16.78it/s]
  3. 画像ファイル「image_040.png」が生成される

  SDXL 版  「雪の中の場面にする」

  1. 「sd_040a.py」  生成画像 image_040a.png 元になる画像は同じ sd_040_test.png
    ## sd_040a.py【SDXL】 画像から画像生成(instruct-pix2pix)サンプル・ソースコード
    ##      https://qiita.com/phyblas/items/28c342740c2ed00250b8
    ##      Model: https://huggingface.co/timbrooks/instruct-pix2pix
    ##      Ver. 0.00   2025/07/07
    
    import torch
    from PIL import Image
    from diffusers import StableDiffusionXLInstructPix2PixPipeline, logging
    from translate import Translator
    
    logging.set_verbosity_error()
    
    # フォルダーのパス
    model_path = "diffusers/sdxl-instructpix2pix-768"              # モデル
    image_path = "images/sd_040_test.png"                          # 元画像
    
    # GPUを使う場合は"cuda" 使わない場合は"cpu"
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    
    # seed 値
    seed = 0
    
    # 画像サイズ
    resolution = 768
    
    # パイプラインを作成
    if device == 'cpu':
        pipeline = StableDiffusionXLInstructPix2PixPipeline.from_pretrained(model_path).to(device)
    else:
        pipeline = StableDiffusionXLInstructPix2PixPipeline.from_pretrained(
                        model_path,
                        torch_dtype = torch.float16,
                        ).to(device)
    
    # プロンプト
    trans = Translator('en','ja').translate
    prompt_jp = '雪の中の場面にする'                                # プロンプト
    prompt = trans(prompt_jp)
    #src_image = Image.open(image_path)
    
    from diffusers.utils import load_image
    src_image = load_image(image_path).resize((resolution, resolution))
    
    # Generatorオブジェクト作成
    generator = torch.Generator(device).manual_seed(seed)
    
    print(f'Seed: {seed}, Model: {model_path}')
    print(f'source_image: {image_path}')
    print(f'prompt : {prompt_jp} → {prompt}')
    
    # 画像を生成
    image = pipeline(
                        prompt = prompt,
                        image = src_image,
                        height = resolution,
                        width = resolution,
                        guidance_scale=3.0,
                        image_guidance_scale = 1.5,
                        num_inference_steps = 20,
                        generator = generator
                        ).images[0]
    
    image.save("results/image_040a.png")                            # 生成画像
  2. プログラムを実行する(実行時間:約 8秒 RTX 4070 Ti 12GB)
    (sd_test) PS > python sd_040a.py
    Loading pipeline components...: 100%|████████████| 7/7 [00:05<00:00,  1.38it/s]
    Seed: 0, Model: diffusers/sdxl-instructpix2pix-768
    source_image: images/sd_040_test.png
    prompt : 雪の中の場面にする → Make it a scene in the snow
    100%|██████████████████████████████████████████| 20/20 [00:03<00:00,  5.30it/s]
  3. 画像ファイル「image_040a.png」が生成される

Step 41:「instruct-pix2pix」image_guidance_scale パラメータによる変化をみる

  SD1.5 版 

  1. プログラムを実行する(実行時間:約 12秒 RTX 4070 Ti 12GB)
    (sd_test) PS > python sd_041.py
    Seed: 12345678, Model: timbrooks/instruct-pix2pix
    source_image: images/sd_040_test.png
    prompt : 雪の中の場面にする → Make it a scene in the snow
    ** image_guidance_scale 1.0 ~ 1.5 **
    Loading pipeline components...: 100%|████████████| 7/7 [00:01<00:00,  5.17it/s]
    100%|██████████████████████████████████████████| 20/20 [00:01<00:00, 17.95it/s]
    Loading pipeline components...: 100%|████████████| 7/7 [00:01<00:00,  5.85it/s]
    100%|██████████████████████████████████████████| 20/20 [00:01<00:00, 18.39it/s]
    Loading pipeline components...: 100%|████████████| 7/7 [00:01<00:00,  6.01it/s]
    100%|██████████████████████████████████████████| 20/20 [00:01<00:00, 17.88it/s]
    Loading pipeline components...: 100%|████████████| 7/7 [00:01<00:00,  5.57it/s]
    100%|██████████████████████████████████████████| 20/20 [00:01<00:00, 18.38it/s]
    Loading pipeline components...: 100%|████████████| 7/7 [00:01<00:00,  6.14it/s]
    100%|██████████████████████████████████████████| 20/20 [00:01<00:00, 18.45it/s]
    Loading pipeline components...: 100%|████████████| 7/7 [00:01<00:00,  6.13it/s]
    100%|██████████████████████████████████████████| 20/20 [00:01<00:00, 18.44it/s]
  2. 画像ファイル「image_041.png」が生成される

  3. モジュール・ソースコード
    ▼「sd_041.py」

  SDXL 版 

  1. プログラムを実行する(実行時間:約 42秒 RTX 4070 Ti 12GB)
    (sd_test) PS > python sd_041a.py
    Seed: 0, Model: diffusers/sdxl-instructpix2pix-768
    source_image: images/sd_040_test.png
    prompt : 雪の中の場面にする → Make it a scene in the snow
    ** image_guidance_scale 1.0 ~ 1.5 **
    Loading pipeline components...: 100%|████████████| 7/7 [00:02<00:00,  2.95it/s]
    100%|██████████████████████████████████████████| 30/30 [00:05<00:00,  5.40it/s]
    Loading pipeline components...: 100%|████████████| 7/7 [00:02<00:00,  3.10it/s]
    100%|██████████████████████████████████████████| 30/30 [00:05<00:00,  5.41it/s]
    Loading pipeline components...: 100%|████████████| 7/7 [00:02<00:00,  2.97it/s]
    100%|██████████████████████████████████████████| 30/30 [00:05<00:00,  5.40it/s]
    Loading pipeline components...: 100%|████████████| 7/7 [00:02<00:00,  3.10it/s]
    100%|██████████████████████████████████████████| 30/30 [00:05<00:00,  5.41it/s]
    Loading pipeline components...: 100%|████████████| 7/7 [00:02<00:00,  3.00it/s]
    100%|██████████████████████████████████████████| 30/30 [00:05<00:00,  5.38it/s]
    Loading pipeline components...: 100%|████████████| 7/7 [00:02<00:00,  3.09it/s]
    100%|██████████████████████████████████████████| 30/30 [00:05<00:00,  5.39it/s]
  2. 画像ファイル「image_041a.png」が生成される

  3. モジュール・ソースコード
    ▼「sd_041a.py」

Step 42:「controlnet instruct-pix2pix」で画像を変換する

  SD1.5 版  「浜辺の場面にする」

  1. 「sd_042.py」  生成画像(左) image_040.png 元になる画像(右) sd_040_test.png
    ## sd_042.py【SD1.5】 画像から画像生成(controlnet instruct-pix2pix)サンプル・ソースコード
    ##      https://qiita.com/phyblas/items/28c342740c2ed00250b8
    ##      Ver. 0.00   2025/07/07
    ##
    ##      command:    python sd_042.py [プロンプト]
    ##
    ##       プロンプト     '浜辺の場面にする'  (デフォールト)
    ##                      '雪の中の場面にする'
    ##                      '炎の中の場面にする'
    ##                      '森の中の場面にする'
    ##                      '山中の場面にする'
    ##                      '砂漠の場面にする'
    ##                      '着物姿に着替える'
    ##
    ##                      'イラスト画像にする'
    ##                      'アニメ画像にする'
    ##                      '微笑んだ顔のアニメ画像にする'
    ##                      '泣き顔のアニメ画像にする'
    ##                      '嬉しそうな顔のアニメ画像にする'
    ##
    ##      model:          control_v11e_sd15_ip2p_fp16.safetensors
    ##      base model:     beautifulRealistic_brav5.safetensors        (リアル系)
    ##                      animePastelDream_softBakedVae.safetensors   (イラスト系)
    
    import torch
    from PIL import Image
    from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, EulerAncestralDiscreteScheduler, logging
    from translate import Translator
    import sys
    
    logging.set_verbosity_error()
    
    # フォルダーのパス
    model_path = '/StabilityMatrix/Data/Models/ControlNet/control_v11e_sd15_ip2p_fp16.safetensors'              # コントロールネット・モデル
    model_base_path = '/StabilityMatrix/Data/Models/StableDiffusion/SD1.5/beautifulRealistic_brav5.safetensors' # ベースモデル
    #model_base_path = '/StabilityMatrix/Data/Models/StableDiffusion/SD1.5/animePastelDream_softBakedVae.safetensors' # ベースモデル
    image_path = "images/sd_040_test.png"                           # 元画像
    
    # GPUを使う場合は"cuda" 使わない場合は"cpu"
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    
    # seed 値
    seed = 12345678
    
    # パイプラインを作成
    if device == 'cpu':
        controlnet = ControlNetModel.from_single_file(model_path).to(device)
        pipeline = StableDiffusionControlNetPipeline.from_single_file(model_base_path, controlnet=controlnet).to(device)
    else:
        controlnet = ControlNetModel.from_single_file(model_path, torch_dtype=torch.float16).to(device)
        pipeline = StableDiffusionControlNetPipeline.from_single_file(
                        model_base_path,
                        controlnet=controlnet,
                        torch_dtype = torch.float16,
                        ).to(device)
    
    # スケジューラー
    pipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(pipeline.scheduler.config)
    
    # プロンプト
    trans = Translator('en','ja').translate
    args = sys.argv
    prompt_jp = '浜辺の場面にする' if len(args) <= 1 else args[1]    # プロンプト
    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'base Model: {model_base_path}')
    print(f'source_image: {image_path}')
    print(f'prompt : {prompt_jp} → {prompt}')
    
    # 画像を生成
    image = pipeline(
                        prompt = prompt,
                        image = src_image,
                        num_inference_steps = 25,
                        generator = generator
                        ).images[0]
    
    image.save("results/image_042.png")                             # 生成画像
  2. プログラムを実行する(実行時間:約 2秒 RTX 4070 Ti 12GB)
    (sd_test) PS > python sd_042.py
    Fetching 11 files: 100%|███████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|████████████| 6/6 [00:00<00:00, 14.80it/s]
    Seed: 12345678, Model: /StabilityMatrix/Data/Models/ControlNet/control_v11e_sd15_ip2p_fp16.safetensors
    base Model: /StabilityMatrix/Data/Models/StableDiffusion/SD1.5/beautifulRealistic_brav5.safetensors
    source_image: images/sd_040_test.png
    prompt : 浜辺の場面にする → Set the scene on the beach
    100%|██████████████████████████████████████████| 25/25 [00:02<00:00,  9.98it/s]
  3. 画像ファイル「image_042.png」が生成される

  4. プロンプトを変えて生成する
    ・「python sd_042.py ['プロンプト']」
    (sd_test) PS > python sd_042.py '雪の中の場面にする'
    ・ベースモデル「beautifulRealistic_brav5.safetensors(リアル系)」
    浜辺の場面にする雪の中の場面にする炎の中の場面にする森の中の場面にする山中の場面にする砂漠の場面にする
    image_042_m.jpg image_042_0_m.jpg image_042_1_m.jpg image_042_2_m.jpg image_042_3_m.jpg image_042_4_m.jpg
    着物姿に着替えるイラスト画像にするアニメ画像にする微笑んだ顔のアニメ画像泣き顔のアニメ画像にする嬉しそうな顔のアニメ画像
    image_042_5_m.jpg image_042_6_m.jpg image_042_7_m.jpg image_042_8_m.jpg image_042_9_m.jpg image_042_10_m.jpg
    ・ベースモデル「animePastelDream_softBakedVae.safetensors(イラスト系)」
    浜辺の場面にする雪の中の場面にする炎の中の場面にする森の中の場面にする山中の場面にする砂漠の場面にする
    image_042_ani_m.jpg image_042_ani_0_m.jpg image_042_ani_1_m.jpg image_042_ani_2_m.jpg image_042_ani_3_m.jpg image_042_ani_4_m.jpg
    着物姿に着替えるイラスト画像にするアニメ画像にする微笑んだ顔のアニメ画像泣き顔のアニメ画像にする嬉しそうな顔のアニメ画像
    image_042_ani_5_m.jpg image_042_ani_6_m.jpg image_042_ani_7_m.jpg image_042_ani_8_m.jpg image_042_ani_9_m.jpg image_042_ani_10_m.jpg

Step 43:「controlnet instruct-pix2pix」controlnet_conditioning_scale パラメータによる変化をみる

  1. プログラムを実行する(実行時間:約 6秒 RTX 4070 Ti 12GB)
    (sd_test) PS > python sd_043.py
    Seed: 12345678, Model: /StabilityMatrix/Data/Models/ControlNet/control_v11e_sd15_ip2p_fp16.safetensors
    source_image: images/sd_040_test.png
    prompt : 浜辺の場面にする → Set the scene on the beach
    ** controlnet_conditioning_scale 0.6 ~ 1.0 **
    Fetching 11 files: 100%|███████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|████████████| 6/6 [00:00<00:00, 18.80it/s]
    100%|██████████████████████████████████████████| 25/25 [00:01<00:00, 14.93it/s]
    Fetching 11 files: 100%|███████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|████████████| 6/6 [00:00<00:00, 32.75it/s]
    100%|██████████████████████████████████████████| 25/25 [00:01<00:00, 17.17it/s]
    Fetching 11 files: 100%|███████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|████████████| 6/6 [00:00<00:00, 33.71it/s]
    100%|██████████████████████████████████████████| 25/25 [00:01<00:00, 17.11it/s]
    Fetching 11 files: 100%|████████████████████| 11/11 [00:00<00:00, 11013.93it/s]
    Loading pipeline components...: 100%|████████████| 6/6 [00:00<00:00, 21.55it/s]
    100%|██████████████████████████████████████████| 25/25 [00:01<00:00, 17.10it/s]
    Fetching 11 files: 100%|███████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|████████████| 6/6 [00:00<00:00, 33.15it/s]
    100%|██████████████████████████████████████████| 25/25 [00:01<00:00, 17.17it/s]
    Fetching 11 files: 100%|███████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|████████████| 6/6 [00:00<00:00, 32.32it/s]
    100%|██████████████████████████████████████████| 25/25 [00:01<00:00, 17.17it/s]
  2. 画像ファイル「image_043.png」が生成される

  3. モジュール・ソースコード
    ▼「sd_043.py」

Step 44:「controlnet inpaint」で画像の一部を変換する

  1. 「sd_044.py」  マスク画像(左) sd_038_test_mask.png 元画像(右) sd_038_test.png
    ## sd_044.py【SD1.5】 画像から画像生成(controlnet inpaint)サンプル・ソースコード
    ##      https://qiita.com/phyblas/items/7cacb9297650afd63d34
    ##      https://zako-lab929.hatenablog.com/entry/20240212/1707743575
    ##      Ver. 0.00   2025/07/08
    ##
    ##      command:    python sd_044.py [プロンプト]
    ##
    ##       プロンプト     '微笑んでいる女性'(デフォールト)
    ##                      '泣いている女性'
    ##                      '怒っている女性'
    ##                      '照れている女性'
    ##                      '見つめている女性'
    ##                      '笑っている女性'
    ##                      '目を瞑っている女性'
    ##                      'ウィンクしている女性'
    ##                      '苛立っている女性'
    ##                      '怖がっている女性'
    ##                      '驚いている女性'
    ##                      '疲れている女性'
    ##
    ##      model:          control_v11p_sd15_inpaint_fp16.safetensors
    ##      base model:     beautifulRealistic_brav5.safetensors        (リアル系)
    ##                      animePastelDream_softBakedVae.safetensors   (イラスト系)
    ##
    ##      元画像:         images/sd_038_test.png
    ##                      images/sd_044_test1.png
    ##                      images/sd_044_test2.png
    ##                      images/sd_044_test3.png
    ##      マスク画像:     images/sd_038_test_mask.png
    ##                      images/sd_044_test1_mask.png
    ##                      images/sd_044_test2_mask.png
    ##                      images/sd_044_test3_mask.png
    
    import torch
    from diffusers import StableDiffusionControlNetInpaintPipeline, ControlNetModel, EulerAncestralDiscreteScheduler, logging
    from diffusers.utils import load_image
    from translate import Translator
    import numpy as np
    import sys
    
    logging.set_verbosity_error()
    
    # コントロールイメージを作成するメソッド
    def make_inpaint_condition(image, image_mask):
        image = np.array(image.convert("RGB")).astype(np.float32) / 255.0
        image_mask = np.array(image_mask.convert("L")).astype(np.float32) / 255.0
    
        assert image.shape[0:1] == image_mask.shape[0:1], "image and image_mask must have the same image size"
        image[image_mask > 0.5] = -1.0  # set as masked pixel
        image = np.expand_dims(image, 0).transpose(0, 3, 1, 2)
        image = torch.from_numpy(image)
        return image
    
    # フォルダーのパス
    model_path = '/StabilityMatrix/Data/Models/ControlNet/control_v11p_sd15_inpaint_fp16.safetensors'                   # コントロールネット・モデル
    model_base_path = '/StabilityMatrix/Data/Models/StableDiffusion/SD1.5/beautifulRealistic_brav5.safetensors'         # ベースモデル
    
    image_path = "images/sd_038_test.png"                           # 元画像
    mask_path = "images/sd_038_test_mask.png"                       # マスク
    
    # GPUを使う場合は"cuda" 使わない場合は"cpu"
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    
    # seed 値
    seed = 12345678
    
    # パイプラインを作成
    if device == 'cpu':
        controlnet = ControlNetModel.from_single_file(model_path).to(device)
        pipeline = StableDiffusionControlNetInpaintPipeline.from_single_file(model_base_path, controlnet=controlnet).to(device)
    else:
        controlnet = ControlNetModel.from_single_file(model_path, torch_dtype=torch.float16).to(device)
        pipeline = StableDiffusionControlNetInpaintPipeline.from_single_file(
                        model_base_path,
                        controlnet=controlnet,
                        torch_dtype = torch.float16,
                        ).to(device)
    
    # スケジューラー
    pipeline.scheduler = EulerAncestralDiscreteScheduler.from_config(pipeline.scheduler.config)
    
    # プロンプト
    trans = Translator('en','ja').translate
    args = sys.argv
    prompt_jp = '微笑んでいる女性' if len(args) <= 1 else args[1]   # プロンプト
    prompt = trans(prompt_jp)
    
    src_image = load_image(image_path).resize((512, 512))           # 元画像
    msk_image = load_image(mask_path).resize((512, 512))            # マスク画像
    img_ctrl = make_inpaint_condition(src_image,msk_image)          # コントロール画像
    
    # Generatorオブジェクト作成
    generator = torch.Generator(device).manual_seed(seed)
    
    print(f'Seed: {seed}, Model: {model_path}')
    print(f'base Model: {model_base_path}')
    print(f'source_image: {image_path}')
    print(f'mask_image: {mask_path}')
    print(f'prompt : {prompt_jp} → {prompt}')
    
    # 画像を生成
    image = pipeline(
                        prompt = prompt,
                        image = src_image,
                        mask_image = msk_image,
                        control_image=img_ctrl,
                        num_inference_steps = 20,
                        generator = generator
                        ).images[0]
    
    image.save("results/image_044.png")                             # 生成画像
  2. プログラムを実行する(実行時間:約 1秒 RTX 4070 Ti 12GB)
    (sd_test) PS > python sd_044.py
    Fetching 11 files: 100%|███████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|████████████| 6/6 [00:00<00:00, 12.47it/s]
    Seed: 12345678, Model: /StabilityMatrix/Data/Models/ControlNet/control_v11p_sd15_inpaint_fp16.safetensors
    base Model: /StabilityMatrix/Data/Models/StableDiffusion/SD1.5/beautifulRealistic_brav5.safetensors
    source_image: images/sd_038_test.png
    mask_image: images/sd_038_test_mask.png
    prompt : 微笑んでいる女性 → Woman smiling
    100%|██████████████████████████████████████████| 20/20 [00:01<00:00, 10.60it/s]
  3. 画像ファイル「image_044.png」が生成される

  4. プロンプトを変えて生成する
    ・「python sd_044.py ['プロンプト']」
    (sd_test) PS > python sd_044.py '見つめている女性'
    ・元画像
    ・ベースモデル「beautifulRealistic_brav5.safetensors(リアル系)」
    微笑んでいる女性泣いている女性怒っている女性照れている女性見つめている女性笑っている女性
    image_044_m.jpg image_044_61_m.jpg image_044_62_m.jpg image_044_63_m.jpg image_044_64_m.jpg image_044_65_m.jpg
    目を瞑っている女性ウィンクしている女性苛立っている女性怖がっている女性驚いている女性疲れている女性
    image_044_66_m.jpg image_044_67_m.jpg image_044_68_m.jpg image_044_69_m.jpg image_044_70_m.jpg image_044_71_m.jpg
    ・ベースモデル「animePastelDream_softBakedVae.safetensors(イラスト系)」
    微笑んでいる女性泣いている女性怒っている女性照れている女性見つめている女性笑っている女性
    image_044_0_m.jpg image_044_1_m.jpg image_044_2_m.jpg image_044_3_m.jpg image_044_4_m.jpg image_044_5_m.jpg
    image_044_20_m.jpg image_044_21_m.jpg image_044_22_m.jpg image_044_23_m.jpg image_044_24_m.jpg image_044_25_m.jpg
    image_044_40_m.jpg image_044_41_m.jpg image_044_42_m.jpg image_044_43_m.jpg image_044_44_m.jpg image_044_45_m.jpg
    目を瞑っている女性ウィンクしている女性苛立っている女性怖がっている女性驚いている女性疲れている女性
    image_044_6_m.jpg image_044_7_m.jpg image_044_8_m.jpg image_044_9_m.jpg image_044_10_m.jpg image_044_11_m.jpg
    image_044_26_m.jpg image_044_27_m.jpg image_044_28_m.jpg image_044_29_m.jpg image_044_30_m.jpg image_044_31_m.jpg
    image_044_46_m.jpg image_044_47_m.jpg image_044_48_m.jpg image_044_49_m.jpg image_044_50_m.jpg image_044_51_m.jpg

Step 45:「controlnet inpaint」strength パラメータによる変化をみる

image_045_m.jpg
  1. プログラムを実行する(実行時間:約 5秒 RTX 4070 Ti 12GB)
    (sd_test) PS > python sd_045.py
    Seed: 12345678, Model: /StabilityMatrix/Data/Models/ControlNet/control_v11p_sd15_inpaint_fp16.safetensors
    base Model: /StabilityMatrix/Data/Models/StableDiffusion/SD1.5/beautifulRealistic_brav5.safetensors
    source_image: images/sd_038_test.png
    mask_image: images/sd_038_test_mask.png
    prompt : 微笑んでいる女性 → Woman smiling
    ** strength 0.1 ~ 1.0 **
    Fetching 11 files: 100%|████████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|█████████████| 6/6 [00:00<00:00, 22.39it/s]
    100%|█████████████████████████████████████████████| 2/2 [00:00<00:00, 10.33it/s]
    Fetching 11 files: 100%|████████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|█████████████| 6/6 [00:00<00:00, 33.31it/s]
    100%|█████████████████████████████████████████████| 4/4 [00:00<00:00, 16.52it/s]
    Fetching 11 files: 100%|████████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|█████████████| 6/6 [00:00<00:00, 34.29it/s]
    100%|█████████████████████████████████████████████| 6/6 [00:00<00:00, 15.99it/s]
    Fetching 11 files: 100%|████████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|█████████████| 6/6 [00:00<00:00, 22.93it/s]
    100%|█████████████████████████████████████████████| 8/8 [00:00<00:00, 15.01it/s]
    Fetching 11 files: 100%|████████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|█████████████| 6/6 [00:00<00:00, 33.96it/s]
    100%|███████████████████████████████████████████| 10/10 [00:00<00:00, 16.53it/s]
    Fetching 11 files: 100%|████████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|█████████████| 6/6 [00:00<00:00, 33.38it/s]
    100%|███████████████████████████████████████████| 12/12 [00:00<00:00, 16.25it/s]
    Fetching 11 files: 100%|████████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|█████████████| 6/6 [00:00<00:00, 32.07it/s]
    100%|███████████████████████████████████████████| 14/14 [00:00<00:00, 15.34it/s]
    Fetching 11 files: 100%|████████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|█████████████| 6/6 [00:00<00:00, 33.52it/s]
    100%|███████████████████████████████████████████| 16/16 [00:01<00:00, 15.45it/s]
    Fetching 11 files: 100%|████████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|█████████████| 6/6 [00:00<00:00, 33.84it/s]
    100%|███████████████████████████████████████████| 18/18 [00:01<00:00, 16.50it/s]
    Fetching 11 files: 100%|████████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|█████████████| 6/6 [00:00<00:00, 33.51it/s]
    100%|███████████████████████████████████████████| 20/20 [00:01<00:00, 16.35it/s]
  2. 画像ファイル「image_045.png」が生成される

  3. モジュール・ソースコード
    ▼「sd_045.py」

Step 46:「outpaint」画像の外側を書き加える

  1. プログラムを実行する(実行時間:約 1秒 RTX 4070 Ti 12GB)
    (sd_test) PS > python sd_046.py
    Fetching 11 files: 100%|█████████████████████| 11/11 [00:00<00:00, 11069.42it/s]
    Loading pipeline components...: 100%|█████████████| 6/6 [00:00<00:00, 14.91it/s]
    Seed: 12345678, Model: /StabilityMatrix/Data/Models/ControlNet/control_v11p_sd15_inpaint_fp16.safetensors
    base Model: /StabilityMatrix/Data/Models/StableDiffusion/SD1.5/beautifulRealistic_brav5.safetensors
    source_image: images/sd_046_test_src.png
    mask_image: images/sd_046_test_msk.png
    prompt : 庭に立って微笑んでいる女性 → Woman standing in a garden smiling
    100%|███████████████████████████████████████████| 20/20 [00:01<00:00, 11.12it/s]
  2. 画像ファイル「image_046.png」が生成される

  3. モジュール・ソースコード
    ▼「sd_045.py」

Step 47:「controlnet scribble」手描きの線画から画像を生成

  1. 「sd_047.py」  線画イラスト(左) sd_038_test_mask.png 生成画像(右) sd_037.png
    ## sd_047.py【SD1.5】 手描きの線画から画像を生成(ControlNet scribble)サンプル・ソースコード
    ##      https://blog.mindboardapps.com/posts/stable-diffusion-and-control-net-img2img/
    ##      Ver. 0.00   2025/07/10
    ##
    ##      command:    python sd_047.py [プロンプト]
    ##
    ##       プロンプト     'テーブル上の白いコーヒーカップ'(デフォールト)
    ##                      '木製のテーブルの上に置かれた白いコーヒーカップ'
    ##                      'ビーチに置かれたオレンジ色のコーヒーカップ'
    ##
    ##      model:          control_v11p_sd15_scribble_fp16.safetensors
    ##      base model:     v1-5-pruned-emaonly.safetensors
    ##
    ##      線画画像:       images/sd_047.png
    ##                      images/sd_047_1.png
    ##                      images/sd_047_2.png
    
    import torch
    from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, logging
    from diffusers.utils import load_image
    from translate import Translator
    import numpy as np
    import sys
    
    logging.set_verbosity_error()
    
    # フォルダーのパス
    model_path = '/StabilityMatrix/Data/Models/ControlNet/control_v11p_sd15_scribble_fp16.safetensors'      # コントロールネット・モデル
    model_base_path = '/StabilityMatrix/Data/Models/StableDiffusion/SD1.5/v1-5-pruned-emaonly.safetensors'  # ベースモデル
    
    image_path = 'images/sd_047.png'
    
    # GPUを使う場合は"cuda" 使わない場合は"cpu"
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    
    # seed 値
    seed = 12345678
    
    # パイプラインを作成
    if device == 'cpu':
        controlnet = ControlNetModel.from_single_file(model_path).to(device)
        pipeline = StableDiffusionControlNetPipeline.from_single_file(model_base_path, controlnet=controlnet).to(device)
    else:
        controlnet = ControlNetModel.from_single_file(model_path, torch_dtype=torch.float16).to(device)
        pipeline = StableDiffusionControlNetPipeline.from_single_file(
                        model_base_path,
                        controlnet=controlnet,
                        torch_dtype = torch.float16,
                        ).to(device)
    
    # プロンプト
    trans = Translator('en','ja').translate
    args = sys.argv
    prompt_jp = 'テーブル上の白いコーヒーカップ' if len(args) <= 1 else args[1]     # プロンプト
    prompt = trans(prompt_jp)
    
    src_image = load_image(image_path).resize((512, 512))                           # 線画画像
    
    # Generatorオブジェクト作成
    generator = torch.Generator(device).manual_seed(seed)
    
    print(f'Seed: {seed}, Model: {model_path}')
    print(f'base Model: {model_base_path}')
    print(f'source_image: {image_path}')
    print(f'prompt : {prompt_jp} → {prompt}')
    
    # 画像を生成
    image = pipeline(
                        prompt = prompt,
                        image = src_image,
                        num_inference_steps = 20,
                        generator = generator
                        ).images[0]
    
    image.save("results/image_047.png")                                             # 生成画像
  2. プログラムを実行する(実行時間:約 1秒 RTX 4070 Ti 12GB)
    (sd_test) PS > python sd_047.py
    Fetching 11 files: 100%|███████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|████████████| 6/6 [00:01<00:00,  5.68it/s]
    Seed: 12345678, Model: /StabilityMatrix/Data/Models/ControlNet/control_v11p_sd15_scribble_fp16.safetensors
    base Model: /StabilityMatrix/Data/Models/StableDiffusion/SD1.5/v1-5-pruned-emaonly.safetensors
    source_image: images/sd_047.png
    prompt : テーブル上の白いコーヒーカップ → White coffee cup on the table
    100%|██████████████████████████████████████████| 20/20 [00:01<00:00, 10.10it/s]
  3. 画像ファイル「image_047.png」が生成される

  4. プロンプトを変えて生成する
    ・「python sd_047.py ['プロンプト']」
    (sd_test) PS > python sd_047.py '木製のテーブルの上に置かれた白いコーヒーカップ'
    ・ベースモデル「v1-5-pruned-emaonly.safetensors
    線画イラストテーブル上の白いコーヒーカップ木製のテーブルの上に置かれた白いコーヒーカップビーチに置かれたオレンジ色のコーヒーカップ
    sd_047_m.jpg image_047_m.jpg image_047_1_m.jpg image_047_2_m.jpg
    sd_047_1_m.jpg image_047_3_m.jpg image_047_4_m.jpg image_047_5_m.jpg
    sd_047_2_m.jpg image_047_6_m.jpg image_047_7_m.jpg image_047_8_m.jpg
 

忘備録

 

更新履歴

参考資料