私的AI研究会 > AI_Program2

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

image_004_m.jpg

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

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

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

 画像から画像を生成する img2img

Step 30:一番簡単な画像から画像生成プログラム

  1. 「sd_030.py」
    ## sd_030.py 画像から画像生成(img2img )
    ## model:   beautifulRealistic_brav5.safetensors
    
    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/beautifulRealistic_brav5.safetensors"
    image_path = "images/StableDiffusion_247.png"
    
    # 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/image_030.png")
  2. プログラムを実行する
    (sd_test) PS > python sd_030.py
    
    Fetching 11 files: 100%|███████████████████████████████| 11/11 [00:00<?, ?it/s]
    Loading pipeline components...: 100%|████████████| 6/6 [00:00<00:00, 10.30it/s]
    Seed: 12345678, Model: /StabilityMatrix/Data/Models/StableDiffusion/SD1.5/beautifulRealistic_brav5.safetensors
    prompt : 黒髪で短い髪の女性 → a woman with short black hair
    100%|██████████████████████████████████████████| 18/18 [00:01<00:00, 15.78it/s]
  3. 画像ファイル「image_030.png」が生成される
 

忘備録

 

更新履歴

参考資料