私的AI研究会 > AI_Program3
#ref(): File not found: "sd_042_gui0_m.jpg" at page "AI_Program8"
これまで検証してきた結果をもとに、Python で生成 AI プログラムを書く
| 画像生成のプログラムを書く |
(base) PS > conda activate sd_test (sd_test) PS > cd workspace_3/sd_test
| 「Stable Diffusion」txt2img 機能を使う最低限の 基本サンプル・コード |
## 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' if torch.cuda.is_available() else 'cpu'
# 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") # 生成画像(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]
| コマンドオプション | 引数 | 初期値 | 意味 |
| --result_image | str | './sd_results/sd.png' | 保存するファイルパスとヘッダ名の指定 |
| --cpu | bool | False | cpu mode. |
| --log | int | 3 | Log level(-1/0/1/2/3/4/5) |
| --model_dir | str | '/StabilityMatrix/Data/Models/StableDiffusion' | モデルフォルダのパス |
| --model_path | str | 'SD1.5/v1-5-pruned-emaonly.safetensors' | モデルファイル |
| --prompt | str | '満開の蘭' | 画像生成のためのプロンプト(日本語/英語) |
| --seed | int | -1 | シード値(-1の時はランダムに生成) |
| --width | int | 512 | 生成画像サイズの幅 |
| --height | int | 512 | 生成画像サイズの高さ |
| --step | int | 30 | 生成ステップ数 |
| --scale | float | 7.0 | ガイダンススケール値 |
#ref(): File not found: "sd_041_m.jpg" at page "AI_Program8"
(sd_test) PS > python sd_041.py Stable Diffusion with diffusers(041) Ver 0.01: Starting application... - result_image : ./sd_results/sd.png - cpu : False - log : 3 - model_path : /StabilityMatrix/Data/Models/StableDiffusion/SD1.5/v1-5-pruned-emaonly.safetensors - prompt : 満開の蘭 - seed : -1 - width : 512 - height : 512 - step : 30 - scale : 7.5 prompt: Orchid in full bloom size: 512, 512 seed: 2008793823 Fetching 11 files: 100%|███████████████████████████████| 11/11 [00:00<?, ?it/s] Loading pipeline components...: 100%|████████████| 6/6 [00:00<00:00, 9.50it/s] 100%|██████████████████████████████████████████| 30/30 [00:03<00:00, 8.17it/s] result_file: ./sd_results/sd_00010_2272584812.png processing start >> 2025/06/17 15:21:30 processing end >> 2025/06/17 15:21:39 processing time >> 0:00:09.063929 Finished.
(sd_test) PS > pip install opencv-python ffmpeg-python imageio scikit-image pyaudio
(sd_test) PS > python -c 'import cv2;print(cv2.__version__)' 4.11.0
#ref(): File not found: "sd_042_gui0_m.jpg" at page "AI_Program8"
#ref(): File not found: "sd_042_gui1_m.jpg" at page "AI_Program8"
(sd_test) PS > python sd_042.py Stable Diffusion with diffusers(042) Ver 0.01: Starting application... - result_image : ./sd_results/sd.png - cpu : False - log : 3 - model_dir : /StabilityMatrix/Data/Models/StableDiffusion - model_path : SD1.5/v1-5-pruned-emaonly.safetensors - prompt : 満開の蘭 - seed : -1 - width : 512 - height : 512 - step : 30 - scale : 7.5 prompt: Orchid in full bloom size: 512, 512 ** Start 1 ** Fetching 11 files: 100%|███████████████████████████████| 11/11 [00:00<?, ?it/s] Loading pipeline components...: 100%|████████████| 6/6 [00:00<00:00, 20.38it/s] 100%|██████████████████████████████████████████| 30/30 [00:03<00:00, 8.51it/s] result_file: ./sd_results/sd_00023_3411634370.png ** Complete ** 00:00:11 Finished.
| 基本のサンプル・コード |
## sd_050.py【SD1.5】 画像から画像生成(img2img)サンプル・ソースコード
## Ver. 1.00 2025/07/01
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' if torch.cuda.is_available() else 'cpu'
# seed 値
seed = 12345678
# パイプラインを作成
if device == 'cpu':
pipeline = StableDiffusionImg2ImgPipeline.from_single_file(model_path).to(device)
else:
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_050.png") # 生成画像(sd_test) PS > python sd_050.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]
| コマンドオプション | 引数 | 初期値 | 意味 |
| --result_image | str | './sd_results/sd.png' | 保存するファイルパスとヘッダ名の指定 |
| --cpu | bool | False | cpu mode. |
| --log | int | 3 | Log level(-1/0/1/2/3/4/5) |
| --model_dir | str | '/StabilityMatrix/Data/Models/StableDiffusion' | モデルフォルダのパス |
| --model_path | str | 'SD1.5/beautifulRealistic_brav5.safetensors' | モデルファイル |
| --prompt | str | '黒髪で短い髪の女性' | 画像生成のためのプロンプト(日本語/英語) |
| --image_path | str | 'images/StableDiffusion_247.png' | 入力画像のファイル・パス名 |
| --seed | int | -1 | シード値(-1の時はランダムに生成) |
| --max_size | int | 0 | 生成画像サイズの最大値(0=入力画像サイズ) |
| --step | int | 30 | 生成ステップ数 |
| --scale | float | 7.0 | ガイダンススケール値 |
| --strength | float | 0.5 | 変化の強さを表すパラメータ |
#ref(): File not found: "sd_051_m.jpg" at page "AI_Program8"
(sd_test) PS > python sd_051.py Stable Diffusion with diffusers(051) Ver 0.01: Starting application... - result_image : ./sd_results2/sd.png - cpu : False - log : 3 - model_dir : /StabilityMatrix/Data/Models/StableDiffusion - model_path : SD1.5/beautifulRealistic_brav5.safetensors - prompt : 黒髪で短い髪の女性 - image_path : images/StableDiffusion_247.png - seed : -1 - max_size : 0 - step : 30 - scale : 7.0 - strength : 0.5 prompt: a woman with short black hair seed: 2247926825 Fetching 11 files: 100%|███████████████████████████████| 11/11 [00:00<?, ?it/s] Loading pipeline components...: 100%|████████████| 6/6 [00:00<00:00, 9.41it/s] 100%|██████████████████████████████████████████| 15/15 [00:02<00:00, 7.02it/s] result_file: ./sd_results2/sd_00004_2247926825.png processing start >> 2025/07/02 13:54:00 processing end >> 2025/07/02 13:54:08 processing time >> 0:00:08.081499 Finished.
#ref(): File not found: "sd_052_m.jpg" at page "AI_Program8"
(sd_test) PS > python sd_052.py Stable Diffusion with diffusers(052) Ver 0.00: Starting application... - result_image : ./sd_results2/sd.png - cpu : False - log : 3 - model_dir : /StabilityMatrix/Data/Models/StableDiffusion - model_path : SD1.5/beautifulRealistic_brav5.safetensors - prompt : 黒髪で短い髪の女性 - image_path : images/StableDiffusion_247.png - seed : -1 - max_size : 0 - step : 30 - scale : 7.0 - strength : 0.5 source image: images/StableDiffusion_247.png prompt: a woman with short black hair ** Start 1 ** Fetching 11 files: 100%|███████████████████████████████| 11/11 [00:00<?, ?it/s] Loading pipeline components...: 100%|████████████| 6/6 [00:00<00:00, 15.64it/s] 100%|██████████████████████████████████████████| 15/15 [00:01<00:00, 10.89it/s] result_file: ./sd_results2/sd_00000_369254691.png ** Complete ** 00:00:04 Finished.
: