![見出し画像](https://assets.st-note.com/production/uploads/images/96525281/rectangle_large_type_2_f5d4509ca36ad14613449713c5bd8bcd.png?width=1200)
Google Colab ではじめる Instruct-Pix2Pix
Google Colab で「Instruct-Pix2Pix」を試したのでまとめました。
・diffusers v0.12.0
1. Instruct-Pix2Pix
「Instruct-Pix2Pix」は、人間の指示で画像編集するためにファインチューニングされた「Stable Diffusion」モデルです。 入力画像と、モデルに何をすべきかを与えると、モデルがそれに従って画像編集を行います。
画像に対して、次のような指示を与えることができます。
・swap sunflowers with roses (ひまわりをバラと交換)
・add fireworks to the sky (空に花火を追加)
・replace the fruits with cake (果物をケーキに置き換える)
![](https://assets.st-note.com/img/1674722342718-5U1PnK9ACN.png?width=1200)
2. Colabでの実行
Google Colabでの実行手順は、次のとおりです。
(1) 新規のColabのノートブックを開き、メニュー「編集 → ノートブックの設定」で「GPU」を選択
(2) パッケージのインストール。
# パッケージのインストール
!pip install diffusers transformers safetensors accelerate
(3) パイプラインの準備。
StableDiffusionInstructPix2PixPipelineクラスを使い、モデルIDに"timbrooks/instruct-pix2pix"を指定します。
import torch
from diffusers import StableDiffusionInstructPix2PixPipeline
# パイプラインの準備
pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(
"timbrooks/instruct-pix2pix",
torch_dtype=torch.float16
).to("cuda")
(4) 画像のアップロード。
左端のフォルダアイコンでファイル一覧を表示し、画像 (cat.png) をドラッグ&ドロップします。
![](https://assets.st-note.com/img/1674722884644-v5uaafaOPW.png?width=1200)
・cat.png
![](https://assets.st-note.com/img/1674722783608-TXBEx43zvY.png)
(5) 画像の読み込み。
cat.pngを読み込み、512x512のRGB画像に補正しています。
from PIL import Image
# 画像の読み込み
image = Image.open("cat.png").resize((512, 512)).convert("RGB")
image
(6) 画像編集。
今回の指示は、"replace the cat with teddy bear" (猫をクマのぬいぐるみに置き換え)としました。
# 画像編集
prompt = "replace the cat with teddy bear"
edit_image = pipe(prompt,
image=image,
num_inference_steps=20,
image_guidance_scale=1.5,
guidance_scale=7).images[0]
edit_image
![](https://assets.st-note.com/img/1674723051959-eLgz5vwpcD.png)
"shiba inu" や "tiger" にすると、次のようになりました。
![](https://assets.st-note.com/img/1674723159118-ddI0NcVzJr.png)
![](https://assets.st-note.com/img/1674723168229-gvaQKypiSm.png)