File size: 120,336 Bytes
96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 724285b 96d06f0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 |
# 简介
本节将会涵盖一些基础内容,介绍如何利用现有的管线(pipeline)借助 Stable Diffusion 模型来生成和修改图片。我们也将简要介绍管线内的关键组成部分。总的来讲,本节涵盖以下内容:
- 利用 `StableDiffusionPipeline` 根据文字描述生成图片,并探究各个输入参数的意义
- 用代码来了解管线的一些关键组成部分:
- 让这个模型成为“隐编码扩散模型(latent diffusion model)”的可变分自编码器(VAE)
- 处理文本提示的分词器(tokenizer)和文本编码器
- UNet 模型
- 使用的调度器(scheduler),以及其它不同的调度器
- 使用管线的组成部分来复现采样循环
- 用 Img2Img 管线来编辑现有图片
- 使用 inpainting 管线和 Depth2Img 管线
❓如果你有问题,请在 Hugging Face Discord 的 `#diffusion-models-class` 频道提出。如果你还没有 Hugging Face 的账号,你可以在这里注册:https://huggingface.co/join/discord
# 配置
```python
!pip install -Uq diffusers ftfy accelerate
```
```python
# Installing transformers from source for now since we need the latest version for Depth2Img:
!pip install -Uq git+https://github.com/huggingface/transformers
```
```python
import torch
import requests
from PIL import Image
from io import BytesIO
from matplotlib import pyplot as plt
# We'll be exploring a number of pipelines today!
from diffusers import (
StableDiffusionPipeline,
StableDiffusionImg2ImgPipeline,
StableDiffusionInpaintPipeline,
StableDiffusionDepth2ImgPipeline
)
# We'll use a couple of demo images later in the notebook
def download_image(url):
response = requests.get(url)
return Image.open(BytesIO(response.content)).convert("RGB")
# Download images for inpainting example
img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
init_image = download_image(img_url).resize((512, 512))
mask_image = download_image(mask_url).resize((512, 512))
```
```python
# Set device
device = (
"mps"
if torch.backends.mps.is_available()
else "cuda"
if torch.cuda.is_available()
else "cpu"
)
```
# 从文本生成图像
我们先载入 Stable Diffusion 的管线。现有的 Stable Diffusion 模型有好多不同版本,截至本书编写时的最新版本是第2.1版。修改版本只需要在 `model_id` 处修改即可(比如你可以试试将其改成 `CompVis/stable-diffusion-v1-4` 或从[dreambooth concepts library](https://huggingface.co/sd-dreambooth-library)选一个模型)。
```python
# Load the pipeline
model_id = "stabilityai/stable-diffusion-2-1-base"
pipe = StableDiffusionPipeline.from_pretrained(model_id).to(device)
```
如果你的GPU内存不够用,可以尝试这些方法减少内存使用:
- 载入 FP16 精度的版本(但并不是所有的系统上都支持),此时你也需要保证所有的张量也被改成了 torch.float16 精度:
`pipe = StableDiffusionPipeline.from_pretrained(model_id, revision="fp16", torch_dtype=torch.float16).to(device)`
- 开启注意力机制切分(attention slicing)。这会牺牲一点点速度来减少GPU内存的使用:
`pipe.enable_attention_slicing()`
- 降低生成结果的图片尺寸
当管线加载好了以后,我们可以用以下代码去使用文字提示生成图片:
```python
# Set up a generator for reproducibility
generator = torch.Generator(device=device).manual_seed(42)
# Run the pipeline, showing some of the available arguments
pipe_output = pipe(
prompt="Palette knife painting of an autumn cityscape", # What to generate
negative_prompt="Oversaturated, blurry, low quality", # What NOT to generate
height=480, width=640, # Specify the image size
guidance_scale=8, # How strongly to follow the prompt
num_inference_steps=35, # How many steps to take
generator=generator # Fixed random seed
)
# View the resulting image:
pipe_output.images[0]
```
0%| | 0/35 [00:00<?, ?it/s]

**练习:** 用上面的代码块做实验,使用你自己的文字提示,反复调整各项设置看看这些设置如何影响生成效果。使用不同的随机种子或者移除掉 `generator` 这个输入参数,看看能获取什么不同的效果。
主要的要调节参数介绍:
- `width` 和 `height` 指定了生成图片的尺寸。它们必须是可被 8 整除的数字,只有这样我们的可变分自编码器(VAE)才能正常工作(原因后面会将)。
- 步数 `num_inference_steps` 也会影响生成的质量。默认设成 50 就行,但你也可以试试设成 20,看看设置小了后效果会如何。
- 使用 `negative_prompt` 来强调不希望生成的内容,一般会在无分类器引导(classifier-free guidance)的情况下用到,这种添加额外控制的方式特别管用。列出一些不想要的特性对生成更好结果很有帮助。
- `guidance_scale` 这个参数决定了无分类器引导(CFG)的影响强度有多大。增大这个值会使得生成的内容更接近文字提示;但这个值如果过大,可能会使得结果变得过饱和、不好看。
如果你想为文字提示找点灵感,可以参考这里:[Stable Diffusion Prompt Book](https://stability.ai/sdv2-prompt-book)
下面展示了增大 `guidance_scale` 这个参数所带来的作用:
```python
#@markdown comparing guidance scales:
cfg_scales = [1.1, 8, 12] #@param
prompt = "A collie with a pink hat" #@param
fig, axs = plt.subplots(1, len(cfg_scales), figsize=(16, 5))
for i, ax in enumerate(axs):
im = pipe(prompt, height=480, width=480,
guidance_scale=cfg_scales[i], num_inference_steps=35,
generator=torch.Generator(device=device).manual_seed(42)).images[0]
ax.imshow(im); ax.set_title(f'CFG Scale {cfg_scales[i]}');
```
0%| | 0/35 [00:00<?, ?it/s]
0%| | 0/35 [00:00<?, ?it/s]
0%| | 0/35 [00:00<?, ?it/s]

当然了,如何解读这些参数是个很主观的事情,但总的来说,设置值到 8 到 12 这个区间内是个不错的选择。
# 管线的组成部分
这里我们用的 `StableDiffusionPipeline` 比前面几个单元的 `DDPMPipeline` 要复杂一点。除了 UNet 和调度器之外,管线内还有很多其它的组成部分:
```python
print(list(pipe.components.keys())) # List components
```
['vae', 'text_encoder', 'tokenizer', 'unet', 'scheduler', 'safety_checker', 'feature_extractor']
为了更好地理解管线如何工作,我们简要地逐个了解各个组成部分。然后可以自己用代码实现,并把它们组合在一起,以此复现出整个管线功能。
### 可变分自编码器(VAE)

可变分自编码器(VAE)是一种模型,它可以将输入图像进行编码,得到一个“压缩过”的信息,再把这个“隐式的”压缩信息给解码出来,得到某种接近输入的输出。当我们使用 Stable Diffusion 生成图片时,我们先在VAE的“隐空间”应用扩散过程**生成隐编码**,然后**在结尾对它们解码**来得到最终结果图片。这样UNet的输入就不是完整的图片、而是缩小版的特征,可以极大地减少计算资源的使用。
下面代码就使用了 VAE,把输入图片编码成隐式表示形式,再对它解码:
```python
# Create some fake data (a random image, range (-1, 1))
images = torch.rand(1, 3, 512, 512).to(device) * 2 - 1
print("Input images shape:", images.shape)
# Encode to latent space
with torch.no_grad():
latents = 0.18215 * pipe.vae.encode(images).latent_dist.mean
print("Encoded latents shape:", latents.shape)
# Decode again
with torch.no_grad():
decoded_images = pipe.vae.decode(latents / 0.18215).sample
print("Decoded images shape:", decoded_images.shape)
```
Input images shape: torch.Size([1, 3, 512, 512])
Encoded latents shape: torch.Size([1, 4, 64, 64])
Decoded images shape: torch.Size([1, 3, 512, 512])
在这个例子中,原本 512x512 尺寸的图片被压缩到 64x64的隐式表示形式(有四个通道)中。每一空间维度上都被压缩到了原有的八分之一,这也是上文中为什么我们设定 `width` 和 `height` 时需要它们是 8 的倍数。
使用这些信息量充裕的 4x64x64 隐编码可比使用 512px 大小的图片要高效多了,可以让我们的扩散模型更快,并使用更少的资源来训练和使用。VAE的解码过程并不是完美的,但即使损失了一点点质量,总的来说也足够好了。
注意:上面的代码例子包含了一个值为 0.18215 的缩放因子,以此来适配stable diffusion训练时的处理流程。
### 分词器(Tokenizer)和文本编码器(Text Encoder)

文本编码器的作用是将输入的字符串(文本提示)转化成数值表示形式,这样才能输入进 UNet 作为条件。文本首先要被管线中的分词器(tokenizer)转换成一系列的分词(token)。文本编码器有大约五万分词的词汇量 —— 它可以将一个长句子分解为一个个的文本最小单元,这些最小单元被称为token,在英文中,一般一个单词就可以作为一个分词,而在汉语中,一般一个或多个汉字组成的词语才是一个分词。这些分词的词嵌入(embedding)会被送入文本编码器模型中 —— 文本编码器是一个transformer模型,被训练作为 CLIP 这个模型的文本编码器。在这里,这个预训练过的 transformer 模型已经有了足够好的文本表示能力,能够很好地把文本描述映射到特征空间。
我们这里通过对一个文本描述进行编码,验证一下这个过程。首先,我们手动进行分词,并将它输入到文本编码器中,再使用管线的 `_encode_prompt` 方法,调用一下这个编码过程,该过程包括补全或截断分词串的长度,使得分词串的长度等于最大长度 77 :
```python
# Tokenizing and encoding an example prompt manualy:
# Tokenize
input_ids = pipe.tokenizer(["A painting of a flooble"])['input_ids']
print("Input ID -> decoded token")
for input_id in input_ids[0]:
print(f"{input_id} -> {pipe.tokenizer.decode(input_id)}")
# Feed through CLIP text encoder
input_ids = torch.tensor(input_ids).to(device)
with torch.no_grad():
text_embeddings = pipe.text_encoder(input_ids)['last_hidden_state']
print("Text embeddings shape:", text_embeddings.shape)
```
Input ID -> decoded token
49406 -> <|startoftext|>
320 -> a
3086 -> painting
539 -> of
320 -> a
4062 -> floo
1059 -> ble
49407 -> <|endoftext|>
Text embeddings shape: torch.Size([1, 8, 1024])
```python
# Get the final text embeddings using the pipeline's _encode_prompt function:
text_embeddings = pipe._encode_prompt("A painting of a flooble", device, 1, False, '')
text_embeddings.shape
```
torch.Size([1, 77, 1024])
这些文本嵌入(text embedding),也即文本编码器中最后一个transformer模块的“隐状态(hidden state)”,将会被送入 UNet 中作为 `forward` 函数的一个额外输入,稍后我们会详细看到。
### UNet

在扩散模型中,UNet 模型接收一个带噪的输入,并预测噪声,以此实现去噪。但与以往例子不同的是,这里的输入并不是图片了,而是图片的隐式表示形式(latent representation)。此外,除了把用于暗示带噪程度的 timestep 输入进 UNet 作为条件外,这里模型也把文字提示(prompt)的文本嵌入(text embeddings)也作为输入。这里我们用假数据试着让它预测一下,请注意这一过程中各个输入输出的形状大小:
```python
# Dummy inputs:
timestep = pipe.scheduler.timesteps[0]
latents = torch.randn(1, 4, 64, 64).to(device)
text_embeddings = torch.randn(1, 77, 1024).to(device)
# Model prediction:
with torch.no_grad():
unet_output = pipe.unet(latents, timestep, text_embeddings).sample
print('UNet output shape:', unet_output.shape) # Same shape as the input latents
```
UNet output shape: torch.Size([1, 4, 64, 64])
### 调度器(Scheduler)
调度器保存了如何加噪这一信息,管理着如何基于模型的预测更新带噪样本。默认的调度器是 `PNDMScheduler` 调度器,但你也可以用其它的(比如 `LMSDiscreteScheduler` 调度器),只要它们用相同的配置初始化。
我们可以画出图像来观察如何随着 timestep 添加噪声,看看噪声水平(基于$\bar{\alpha}$这个参数)是怎样变动的:
```python
plt.plot(pipe.scheduler.alphas_cumprod, label=r'$\bar{\alpha}$')
plt.xlabel('Timestep (high noise to low noise ->)');
plt.title('Noise schedule');plt.legend();
```

如果你想尝试不同的调度器,可以参考下面代码修改:
```python
from diffusers import LMSDiscreteScheduler
# Replace the scheduler
pipe.scheduler = LMSDiscreteScheduler.from_config(pipe.scheduler.config)
# Print the config
print('Scheduler config:', pipe.scheduler)
# Generate an image with this new scheduler
pipe(prompt="Palette knife painting of an winter cityscape", height=480, width=480,
generator=torch.Generator(device=device).manual_seed(42)).images[0]
```
Scheduler config: LMSDiscreteScheduler {
"_class_name": "LMSDiscreteScheduler",
"_diffusers_version": "0.11.1",
"beta_end": 0.012,
"beta_schedule": "scaled_linear",
"beta_start": 0.00085,
"clip_sample": false,
"num_train_timesteps": 1000,
"prediction_type": "epsilon",
"set_alpha_to_one": false,
"skip_prk_steps": true,
"steps_offset": 1,
"trained_betas": null
}
0%| | 0/50 [00:00<?, ?it/s]

在[这里](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion_2#how-to-load-and-use-different-schedulers)你可以了解更多使用不同调度器的信息。
### DIY一个采样循环
现在我们已经逐个了解这些组成部分了,我们可以把它们拼装到一起,来复现一下整个管线的功能:
```python
guidance_scale = 8 #@param
num_inference_steps=30 #@param
prompt = "Beautiful picture of a wave breaking" #@param
negative_prompt = "zoomed in, blurry, oversaturated, warped" #@param
# Encode the prompt
text_embeddings = pipe._encode_prompt(prompt, device, 1, True, negative_prompt)
# Create our random starting point
latents = torch.randn((1, 4, 64, 64), device=device, generator=generator)
latents *= pipe.scheduler.init_noise_sigma
# Prepare the scheduler
pipe.scheduler.set_timesteps(num_inference_steps, device=device)
# Loop through the sampling timesteps
for i, t in enumerate(pipe.scheduler.timesteps):
# expand the latents if we are doing classifier free guidance
latent_model_input = torch.cat([latents] * 2)
# Apply any scaling required by the scheduler
latent_model_input = pipe.scheduler.scale_model_input(latent_model_input, t)
# predict the noise residual with the unet
with torch.no_grad():
noise_pred = pipe.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
# perform guidance
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# compute the previous noisy sample x_t -> x_t-1
latents = pipe.scheduler.step(noise_pred, t, latents).prev_sample
# Decode the resulting latents into an image
with torch.no_grad():
image = pipe.decode_latents(latents.detach())
# View
pipe.numpy_to_pil(image)[0]
```

当然大多数情况下,还是使用现有的管线更方便。如果你想看看实际的代码以及深入了解如何修改这些组成部分,你可以参考 Stable Diffusion Deep Dive 这个[笔记本](https://github.com/fastai/diffusion-nbs/blob/master/Stable%20Diffusion%20Deep%20Dive.ipynb)和[视频](https://m.youtube.com/watch?v=0_BBRNYInx8)。这里有对相关内容更全面彻底的探究。
# 其它的一些管线
除了从文字提示生成图片外,我们还能做点什么呢?其实还有很多!下面还会向你展示几个管线,让你了解一些 Stable Diffusion 的应用。
## Img2Img
直到现在,我们生成的图片还都是完全从随机的隐变量来开始生成的,而且也都使用了完整的扩散模型采样循环。但如果使用 Img2Img 管线,我们其实不必从头开始。Img2Img 这个管线首先将一张已有的图片进行编码,编码成一系列的隐变量,然后在这些隐变量上随机加噪声,以这些作为起始点。噪声加多大量、去噪需要多少步数(timestep)决定了这个 img2img 过程的“强度”。只加一点点噪声(强度低)只会带来微小改变,而加入大量噪声并跑完完整去噪过程又会让生成出几乎完全不像原始图片,仅在整体结构上还有点相似。
这个管线无需什么特殊模型,只要模型的 ID 和我们的文字到图像模型一样就行,没有新的需要下载的文件。
```python
# Loading an Img2Img pipeline
model_id = "stabilityai/stable-diffusion-2-1-base"
img2img_pipe = StableDiffusionImg2ImgPipeline.from_pretrained(model_id).to(device)
```
Fetching 16 files: 0%| | 0/16 [00:00<?, ?it/s]
这里是使用该管线的代码:
```python
# Apply Img2Img
result_image = img2img_pipe(
prompt="An oil painting of a man on a bench",
image = init_image, # The starting image
strength = 0.6, # 0 for no change, 1.0 for max strength
).images[0]
# View the result
fig, axs = plt.subplots(1, 2, figsize=(12, 5))
axs[0].imshow(init_image);axs[0].set_title('Input Image')
axs[1].imshow(result_image);axs[1].set_title('Result');
```
0%| | 0/30 [00:00<?, ?it/s]

**练习:** 用这个管线做实验,试试你自己的图片,或者试试不同的强度和文字提示。也可以试试不同的图片尺寸、生成步数。
## In-Painting

如果我们想在一张图中保留一部分不变而在其它部分生成新东西,那该怎么办呢?这种技术叫 inpainting 。虽然我们可以用 `StableDiffusionInpaintPipelineLegacy` 管线来实现,但其实有更简单的选择。这里的 Stable Diffusion 模型接收一个掩模(mask)作为额外条件性输入。这个掩模图片需要和输入图片尺寸一致,白色区域表示要被替换的部分,黑色区域表示要保留的部分。以下代码就展示了我们如何载入这个管线并如何应用到前面载入的示例图片和掩模上:
```python
# Load the inpainting pipeline (requires a suitable inpainting model)
pipe = StableDiffusionInpaintPipeline.from_pretrained("runwayml/stable-diffusion-inpainting")
pipe = pipe.to(device)
```
```python
# Inpaint with a prompt for what we want the result to look like
prompt = "A small robot, high resolution, sitting on a park bench"
image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0]
# View the result
fig, axs = plt.subplots(1, 3, figsize=(16, 5))
axs[0].imshow(init_image);axs[0].set_title('Input Image')
axs[1].imshow(mask_image);axs[1].set_title('Mask')
axs[2].imshow(image);axs[2].set_title('Result');
```
0%| | 0/50 [00:00<?, ?it/s]

当和其它可以自动生成掩模的模型结合起来的时候,这个模型将会相当强大。比如[这个示例space](https://huggingface.co/spaces/nielsr/text-based-inpainting)就用了一个名为 CLIPSeg 的模型,它可以根据文字描述自动地用掩模去掉一个物体。
### 题外话:管理你的模型缓存
探索不同的管线和模型可能会占满你的硬盘空间。你可用这个指令看看你都下载了哪些模型到你的硬盘上:
```python
!ls ~/.cache/huggingface/diffusers/ # List the contents of the cache directory
```
models--CompVis--stable-diffusion-v1-4
models--ddpm-bedroom-256
models--google--ddpm-bedroom-256
models--google--ddpm-celebahq-256
models--runwayml--stable-diffusion-inpainting
models--stabilityai--stable-diffusion-2-1-base
看看[缓存相关文档](https://huggingface.co/docs/huggingface_hub/main/en/how-to-cache)来了解如何高效地查看和管理缓存。
## Depth2Image

_Input image, depth image and generated examples (image source: StabilityAI)_
Img2Img 已经很厉害了,但有时我们还想借用原始图片的整体结构,但使用不同的颜色或纹理来生成新图片。保留图片整体结构但却不保留原有颜色,是很难通过调节 Img2Img 的“强度”来实现的。
所以这里就需要另一个微调的模型了!这个模型需要输入额外的深度信息作为生成条件。相关管线使用了一个深度预测模型来预测出一个深度图,然后这个深度图会被输入微调过的 UNet 中用以生成图片。我们这里希望生成的图片能够保留原始图片的深度信息和总体结构,同时又在相关部分填入全新的内容。
```python
# Load the Depth2Img pipeline (requires a suitable model)
pipe = StableDiffusionDepth2ImgPipeline.from_pretrained("stabilityai/stable-diffusion-2-depth")
pipe = pipe.to(device)
```
```python
# Inpaint with a prompt for what we want the result to look like
prompt = "An oil painting of a man on a bench"
image = pipe(prompt=prompt, image=init_image).images[0]
# View the result
fig, axs = plt.subplots(1, 2, figsize=(16, 5))
axs[0].imshow(init_image);axs[0].set_title('Input Image')
axs[1].imshow(image);axs[1].set_title('Result');
```
0%| | 0/40 [00:00<?, ?it/s]

让我们和 Img2Img 的例子做个对比 —— 这里生成结果有着更丰富的颜色变化,但图片的整体结构仍然忠于原始图片。这里的例子其实并不够理想,因为为了匹配上狗的形状,这里生成的人有着怪异的身体构造。但在某些场景下,这个技术还是相当有用的,比如这个例子中的“杀手级应用软件”(查看[推特](https://twitter.com/CarsonKatri/status/1600248599254007810?s=20&t=BlzSK26sfqi2336SN0gKpQ)),它利用深度模型去给一个 3D 场景加入纹理!
# 下一步?
希望这节的内容让你对 Stable Diffusion 能做的事情有了一个认识!如果你玩烦了本节笔记本中的例子,你可以尝试 **DreamBooth hackathon** 这节笔记本,看看怎样自己来微调 Stable Diffusion 模型,来用在文字到图像或图像到图像的相关管线上。
如果你想深入探索不同的组成部分是如何运作的,你可以看看 **Stable Diffusion Deep Dive** 这节笔记本,这里介绍了大量的细节以及额外的一些小技巧。
一定要和我们以及社区分享你的创造啊!
|