# 图像到图像

  

Stable Diffusion 模型也可用于图像到图像的生成，只需传入文本提示和初始图像，即可作为条件来生成新图像。

[StableDiffusionImg2ImgPipeline](/docs/diffusers/main/zh/api/pipelines/stable_diffusion/img2img#diffusers.StableDiffusionImg2ImgPipeline) 使用了 Chenlin Meng、Yutong He、Yang Song、Jiaming Song、Jiajun Wu、Jun-Yan Zhu 和 Stefano Ermon 在 [SDEdit: Guided Image Synthesis and Editing with Stochastic Differential Equations](https://huggingface.co/papers/2108.01073) 中提出的扩散去噪机制。

该论文的摘要如下：

*引导式图像合成使普通用户能够以最小的努力创建和编辑照片级逼真的图像。关键挑战在于平衡对用户输入（例如手绘彩色笔触）的忠实度与合成图像的真实感。现有的基于 GAN 的方法尝试使用条件 GAN 或 GAN 反演来实现这种平衡，但这颇具挑战性，并且通常针对各个具体应用需要额外的训练数据或损失函数。为了解决这些问题，我们提出了一种基于扩散模型生成先验的新图像合成与编辑方法——随机微分编辑（SDEdit），该方法通过随机微分方程（SDE）进行迭代去噪来合成逼真的图像。给定带有任意类型用户引导的输入图像，SDEdit 首先向输入添加噪声，然后通过 SDE 先验对所得图像进行去噪，以提升其真实感。SDEdit 无需针对特定任务的训练或反演，并且能够自然地实现真实感与忠实度之间的平衡。根据一项人类感知研究，在包括基于笔触的图像合成与编辑以及图像合成在内的多项任务中，SDEdit 在真实度上比最先进的基于 GAN 的方法高出多达 98.09%，在整体满意度评分上高出 91.72%。*

> [!TIP]
> 请务必查看 Stable Diffusion 的 [技巧](overview#tips) 部分，了解如何探索调度器速度与质量之间的权衡，以及如何高效地复用流水线组件！

## StableDiffusionImg2ImgPipeline[[diffusers.StableDiffusionImg2ImgPipeline]]

#### diffusers.StableDiffusionImg2ImgPipeline[[diffusers.StableDiffusionImg2ImgPipeline]]

```python
diffusers.StableDiffusionImg2ImgPipeline(vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet2DConditionModel, scheduler: KarrasDiffusionSchedulers, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, image_encoder: CLIPVisionModelWithProjection = None, requires_safety_checker: bool = True)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py#L182)

**参数：**

vae ([AutoencoderKL](/docs/diffusers/main/zh/api/models/autoencoderkl#diffusers.AutoencoderKL))：变分自编码器（VAE）模型，用于将图像编码为潜在表示，并从潜在表示解码回图像。

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModel))：冻结的文本编码器（[clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)）。

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer))：一个用于对文本进行分词的 `CLIPTokenizer`。

unet ([UNet2DConditionModel](/docs/diffusers/main/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel))：一个用于对编码后的图像潜变量进行去噪的 `UNet2DConditionModel`。

scheduler ([SchedulerMixin](/docs/diffusers/main/zh/api/schedulers/overview#diffusers.SchedulerMixin))：用于与 `unet` 配合以去除编码后的图像潜变量噪声的调度器。可以是 [DDIMScheduler](/docs/diffusers/main/zh/api/schedulers/ddim#diffusers.DDIMScheduler)、[LMSDiscreteScheduler](/docs/diffusers/main/zh/api/schedulers/lms_discrete#diffusers.LMSDiscreteScheduler) 或 [PNDMScheduler](/docs/diffusers/main/zh/api/schedulers/pndm#diffusers.PNDMScheduler) 之一。

safety_checker (`StableDiffusionSafetyChecker`)：分类模块，用于评估生成的图像是否可能被视为冒犯性或有害内容。有关模型潜在危害的更多详细信息，请参阅[模型卡片](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)。

feature_extractor ([CLIPImageProcessor](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPImageProcessor))：一个 `CLIPImageProcessor`，用于从生成的图像中提取特征；作为 `safety_checker` 的输入。

使用 Stable Diffusion 进行文本引导的图像到图像生成的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/main/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有流水线实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

该 pipeline 还继承了以下加载方法：
- 用于加载文本反转嵌入的 [load_textual_inversion()](/docs/diffusers/main/zh/api/loaders/textual_inversion#diffusers.loaders.TextualInversionLoaderMixin.load_textual_inversion)
- 用于加载 LoRA 权重的 [load_lora_weights()](/docs/diffusers/main/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_weights)
- 用于保存 LoRA 权重的 [save_lora_weights()](/docs/diffusers/main/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.save_lora_weights)
- 用于加载 `.ckpt` 文件的 [from_single_file()](/docs/diffusers/main/zh/api/loaders/single_file#diffusers.loaders.FromSingleFileMixin.from_single_file)
- 用于加载 IP Adapter 的 [load_ip_adapter()](/docs/diffusers/main/zh/api/loaders/ip_adapter#diffusers.loaders.IPAdapterMixin.load_ip_adapter)

#### __调用__[[diffusers.StableDiffusionImg2ImgPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, strength: float = 0.8, num_inference_steps: int | None = 50, timesteps: list = None, sigmas: list = None, guidance_scale: float | None = 7.5, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float | None = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, output_type: str | None = 'pil', return_dict: bool = True, cross_attention_kwargs: dict[str, typing.Any] | None = None, clip_skip: int = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list = ['latents'], **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py#L858)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则需要传入 `prompt_embeds`。

image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]` 或 `list[np.ndarray]`) : `Image`、numpy 数组或张量，表示用作起点的图像批次。对于 numpy 数组和 PyTorch 张量，预期的值范围为 `[0, 1]`。如果是张量或张量列表，预期的形状应为 `(B, C, H, W)` 或 `(C, H, W)`。如果是 numpy 数组或数组列表，预期的形状应为 `(B, H, W, C)` 或 `(H, W, C)`。它也可以接受图像潜变量作为 `image`，但如果直接传入潜变量，则不会再次进行编码。

strength (`float`，*可选*，默认值为 0.8)：指示对参考 `image` 进行变换的程度。取值必须在 0 到 1 之间。`image` 用作起始点，`strength` 越高，添加的噪声越多。去噪步数取决于初始添加的噪声量。当 `strength` 为 1 时，添加的噪声达到最大值，去噪过程将运行 `num_inference_steps` 中指定的完整迭代次数。值为 1 时，基本上会忽略 `image`。

num_inference_steps (`int`，*可选*，默认值为 50)：去噪步数。更多的去噪步数通常能生成更高质量的图像，但代价是推理速度变慢。此参数受 `strength` 调节。

timesteps (`list[int]`，*可选*)：用于在支持 `set_timesteps` 方法中 `timesteps` 参数的调度器中，指定去噪过程所使用的自定义时间步。如果未定义，则使用传入 `num_inference_steps` 时的默认行为。必须按降序排列。

sigmas (`list[float]`, *可选*) : 用于支持在 `set_timesteps` 方法中接受 `sigmas` 参数的调度器的去噪过程的自定义 sigmas。如果未定义，将使用传入 `num_inference_steps` 时的默认行为。

guidance_scale (`float`, *可选*，默认值为 7.5)：较高的 guidance scale 值会促使模型生成与文本 `prompt` 紧密相关的图像，但代价是图像质量降低。当 `guidance_scale > 1` 时，guidance scale 生效。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于指导图像生成中不应包含的内容的提示词或提示词列表。如果未定义，则需要改为传入 `negative_prompt_embeds`。在未使用引导（`guidance_scale < 1`）时将被忽略。

num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

eta (`float`，*可选*，默认值为 0.0)：对应 [DDIM](https://huggingface.co/papers/2010.02502) 论文中的参数 eta (η)。仅适用于 [DDIMScheduler](/docs/diffusers/main/zh/api/schedulers/ddim#diffusers.DDIMScheduler)，在其他调度器中会被忽略。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：用于使生成过程确定性的 [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html)。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入（提示词权重）。如果未提供，则从 `prompt` 输入参数生成文本嵌入。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入（提示词权重）。如果未提供，`negative_prompt_embeds` 将从 `negative_prompt` 输入参数生成。

ip_adapter_image : (`PipelineImageInput`，*可选*)：用于配合 IP Adapter 使用的可选图像输入。

ip_adapter_image_embeds (`list[torch.Tensor]`，*可选*)：用于 IP-Adapter 的预生成图像嵌入。它应是一个列表，长度与 IP-Adapter 的数量相同。每个元素应为形状为 `(batch_size, num_images, emb_dim)` 的张量。如果 `do_classifier_free_guidance` 设置为 `True`，则应包含负向图像嵌入。如果未提供，嵌入将从 `ip_adapter_image` 输入参数计算得出。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。在 `PIL.Image` 或 `np.array` 之间选择。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [StableDiffusionPipelineOutput](/docs/diffusers/main/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 而不是普通元组。

cross_attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为 [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中定义的 `AttentionProcessor` 的参数传递。

clip_skip (`int`, *可选*) : 在计算提示嵌入时，从 CLIP 中跳过的层数。值为 1 表示将使用倒数第二层的输出来计算提示嵌入。

callback_on_step_end (`Callable`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：一个函数，或 `PipelineCallback` 或 `MultiPipelineCallbacks` 的子类，在推理过程中每个去噪步骤结束时被调用，其参数为：`callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。`callback_kwargs` 将包含由 `callback_on_step_end_tensor_inputs` 指定的所有张量列表。

callback_on_step_end_tensor_inputs (`list`，*可选*)：`callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传递。您只能包含流水线类的 `._callback_tensor_inputs` 属性中列出的变量。

**返回：** [StableDiffusionPipelineOutput](/docs/diffusers/main/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 或 `tuple`

如果 `return_dict` 为 `True`，则返回 [StableDiffusionPipelineOutput](/docs/diffusers/main/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

用于生成的 pipeline 的调用函数。

示例：
```py
>>> import requests
>>> import torch
>>> from PIL import Image
>>> from io import BytesIO

>>> from diffusers import StableDiffusionImg2ImgPipeline

>>> device = "cuda"
>>> model_id_or_path = "stable-diffusion-v1-5/stable-diffusion-v1-5"
>>> pipe = StableDiffusionImg2ImgPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
>>> pipe = pipe.to(device)

>>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"

>>> response = requests.get(url)
>>> init_image = Image.open(BytesIO(response.content)).convert("RGB")
>>> init_image = init_image.resize((768, 512))

>>> prompt = "A fantasy landscape, trending on artstation"

>>> images = pipe(prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5).images
>>> images[0].save("fantasy_landscape.png")
```

#### enable_attention_slicing[[diffusers.StableDiffusionImg2ImgPipeline.enable_attention_slicing]]

```python
enable_attention_slicing(slice_size: str | int = 'auto')
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L2048)

**参数：**

slice_size (`str` 或 `int`，*可选*，默认为 `"auto"`)：当值为 `"auto"` 时，将输入到注意力头的数据减半，因此注意力计算将分两步进行。如果值为 `"max"`，则每次只运行一个切片，以节省最大内存。如果提供了数字，则使用 `attention_head_dim // slice_size` 个切片。在这种情况下，`attention_head_dim` 必须是 `slice_size` 的倍数。

启用切片注意力计算。启用此选项后，注意力模块会将输入张量拆分为多个切片，分步计算注意力。当存在多个注意力头时，计算将按顺序针对每个头执行。此功能可用于节省部分内存，代价是速度略有下降。

> [!WARNING] > ⚠️ 如果你已经在使用 `scaled_dot_product_attention`（SDPA），请勿启用注意力切片
来自 PyTorch > 2.0 或 xFormers。这些注意力计算本身已经非常节省内存，因此您无需启用 > 此功能。如果您在 SDPA 或 xFormers 中启用注意力切片，可能会导致严重的性能下降！

示例：

```py
>>> import torch
>>> from diffusers import StableDiffusionPipeline

>>> pipe = StableDiffusionPipeline.from_pretrained(
...     "stable-diffusion-v1-5/stable-diffusion-v1-5",
...     dtype=torch.float16,
...     use_safetensors=True,
... )

>>> prompt = "a photo of an astronaut riding a horse on mars"
>>> pipe.enable_attention_slicing()
>>> image = pipe(prompt).images[0]
```

#### disable_attention_slicing[[diffusers.StableDiffusionImg2ImgPipeline.disable_attention_slicing]]

```python
disable_attention_slicing()
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L2085)

禁用切片注意力计算。如果之前调用过 `enable_attention_slicing`，则注意力将一次性计算完成。

#### enable_xformers_memory_efficient_attention[[diffusers.StableDiffusionImg2ImgPipeline.enable_xformers_memory_efficient_attention]]

```python
enable_xformers_memory_efficient_attention(attention_op: typing.Optional[typing.Callable] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L1993)

**参数：**

attention_op (`Callable`，*可选*)：覆盖默认的 `None` 运算符，用作 xFormers 的 [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention) 函数的 `op` 参数。

启用来自 [xFormers](https://facebookresearch.github.io/xformers/) 的内存高效注意力机制。启用此选项后，您应能观察到更低的 GPU 内存占用，并可能在推理阶段获得加速。训练阶段的加速不保证。

> [!WARNING] > ⚠️ 当同时启用 memory efficient attention 和 sliced attention 时，memory efficient
attention 的优先级高于 >。

示例：

```py
>>> import torch
>>> from diffusers import DiffusionPipeline
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

>>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", dtype=torch.float16)
>>> pipe = pipe.to("cuda")
>>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
>>> # Workaround for not accepting attention shape using VAE for Flash Attention
>>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
```

#### disable_xformers_memory_efficient_attention[[diffusers.StableDiffusionImg2ImgPipeline.disable_xformers_memory_efficient_attention]]

```python
disable_xformers_memory_efficient_attention()
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_utils.py#L2024)

禁用来自 [xFormers](https://facebookresearch.github.io/xformers/) 的内存高效注意力。

#### load_textual_inversion[[diffusers.StableDiffusionImg2ImgPipeline.load_textual_inversion]]

```python
load_textual_inversion(pretrained_model_name_or_path: str | list[str] | dict[str, torch.Tensor] | list[dict[str, torch.Tensor]], token: str | list[str] | None = None, tokenizer: 'PreTrainedTokenizer' | None = None, text_encoder: 'PreTrainedModel' | None = None, **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders/textual_inversion.py#L271)

**参数：**

pretrained_model_name_or_path (`str` 或 `os.PathLike` 或 `list[str or os.PathLike]` 或 `Dict` 或 `list[Dict]`) : 可以是以下其中一种，也可以是它们的列表： - 一个字符串，即托管在 Hub 上的预训练模型的 *model id*（例如 `sd-concepts-library/low-poly-hd-logos-icons`）。 - 指向包含文本反转（textual inversion）权重的*目录*的路径（例如 `./my_text_inversion_directory/`）。 - 指向包含文本反转权重的*文件*的路径（例如 `./my_text_inversions.pt`）。 - 一个 [torch state dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict)。

token (`str` 或 `list[str]`，*可选*) : 用于覆盖文本反转权重所使用的 token。如果 `pretrained_model_name_or_path` 是一个列表，则 `token` 也必须是一个长度相等的列表。

text_encoder ([CLIPTextModel](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTextModel)，*可选*)：冻结的文本编码器（[clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)）。如果未指定，函数将使用 self.tokenizer。

tokenizer ([CLIPTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/clip#transformers.CLIPTokenizer)，*可选*)：用于对文本进行分词的 `CLIPTokenizer`。如果未指定，函数将使用 self.tokenizer。

weight_name (`str`, *可选*) : 自定义权重文件的名称。在以下情况下应使用此参数： - 保存的文本反转文件采用 🤗 Diffusers 格式，但保存时使用了特定的权重名称，例如 `text_inv.bin`。 - 保存的文本反转文件采用 Automatic1111 格式。

cache_dir (`str | os.PathLike`，*可选*)：如果未使用标准缓存，则已下载的预训练模型配置将缓存到的目录路径。

force_download (`bool`，*可选*，默认为 `False`)：是否强制（重新）下载模型权重和配置文件，如果存在缓存版本则覆盖它们。

proxies (`dict[str, str]`，*可选*)：一个字典，用于按协议或端点指定要使用的代理服务器，例如 `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`。每次请求都会使用这些代理。

local_files_only (`bool`，*可选*，默认为 `False`)：是否仅加载本地模型权重和配置文件。如果设置为 `True`，则不会从 Hub 下载模型。

hf_token (`str` 或 *bool*，*可选*) : 用于远程文件的 HTTP 承载者授权令牌。如果为 `True`，则使用由 `diffusers-cli login` 生成的令牌（存储在 `~/.huggingface` 中）。

revision (`str`，*可选*，默认为 `"main"`)：要使用的特定模型版本。它可以是分支名称、标签名称、提交 ID，或 Git 允许的任何标识符。

subfolder (`str`，*可选*，默认为 `""`)：模型文件在 Hub 或本地的大型模型仓库中的子文件夹位置。

mirror (`str`, *可选*) : 用于解决在中国下载模型时可能遇到的访问问题的镜像源。我们不保证该源的时效性或安全性，详情请参阅镜像站点。

将 Textual Inversion 嵌入加载到 [StableDiffusionPipeline](/docs/diffusers/main/zh/api/pipelines/stable_diffusion/text2img#diffusers.StableDiffusionPipeline) 的文本编码器中（同时支持 🤗 Diffusers 和 Automatic1111 格式）。

示例：

要在 🤗 Diffusers 格式中加载 Textual Inversion 嵌入向量：

```py
from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("sd-concepts-library/cat-toy")

prompt = "A <cat-toy> backpack"

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("cat-backpack.png")
```

要在 Automatic1111 格式中加载 Textual Inversion 嵌入向量，请先下载该向量（例如从 [civitAI](https://civitai.com/models/3036?modelVersionId=9857) 下载），然后加载该向量

本地：

```py
from diffusers import StableDiffusionPipeline
import torch

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")

prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."

image = pipe(prompt, num_inference_steps=50).images[0]
image.save("character.png")
```

#### from_single_file[[diffusers.StableDiffusionImg2ImgPipeline.from_single_file]]

```python
from_single_file(pretrained_model_link_or_path, **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders/single_file.py#L276)

**参数：**

pretrained_model_link_or_path (`str` 或 `os.PathLike`，*可选*) : 可以是以下之一： - 指向 Hub 上 `.ckpt` 文件的链接（例如 `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`）。 - 指向包含所有流水线权重的*文件*的路径。

dtype (`str` 或 `torch.dtype`，*可选*)：覆盖默认的 `torch.dtype`，并使用其他 dtype 加载模型。

force_download (`bool`，*可选*，默认为 `False`)：是否强制（重新）下载模型权重和配置文件，如果存在缓存版本则覆盖它们。

cache_dir (`str | os.PathLike`，*可选*)：如果未使用标准缓存，则已下载的预训练模型配置将缓存到的目录路径。

proxies (`dict[str, str]`，*可选*)：一个字典，用于按协议或端点指定要使用的代理服务器，例如 `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`。每次请求都会使用这些代理。

local_files_only (`bool`，*可选*，默认为 `False`)：是否仅加载本地模型权重和配置文件。如果设置为 `True`，则不会从 Hub 下载模型。

token (`str` 或 *bool*，*可选*) : 用于远程文件的 HTTP 承载者授权令牌。如果为 `True`，则使用由 `diffusers-cli login` 生成的令牌（存储在 `~/.huggingface` 中）。

revision (`str`，*可选*，默认为 `"main"`)：要使用的特定模型版本。它可以是分支名称、标签名称、提交 ID，或 Git 允许的任何标识符。

original_config_file (`str`, *可选*) : 用于训练模型的原始配置文件的路径。如果未提供，则将从检查点文件中推断出配置文件。

config (`str`, *可选*) : 可以是以下之一： - 一个字符串，即托管在 Hub 上的预训练流水线的 *repo id*（例如 `CompVis/ldm-text2im-large-256`）。 - 一个指向 *目录* 的路径（例如 `./my_pipeline_directory/`），其中包含以 Diffusers 格式存储的流水线组件配置。

disable_mmap ('bool', *可选*，默认为 'False')：是否在加载 Safetensors 模型时禁用 mmap。当模型位于网络挂载或硬盘上时，此选项可能带来更好的性能。

kwargs （其余关键字参数字典，*可选*）：可用于覆盖加载和可保存的变量（特定 pipeline 类的 pipeline 组件）。被覆盖的组件会直接传递给 pipeline 的 `__init__` 方法。更多信息请参见下方示例。

从以 `.ckpt` 或 `.safetensors` 格式保存的预训练流水线权重中实例化一个 [DiffusionPipeline](/docs/diffusers/main/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。默认情况下，流水线会设置为评估模式（`model.eval()`）。

示例：

```py
>>> from diffusers import StableDiffusionPipeline

>>> # Download pipeline from huggingface.co and cache.
>>> pipeline = StableDiffusionPipeline.from_single_file(
...     "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
... )

>>> # Download pipeline from local file
>>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
>>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly.ckpt")

>>> # Enable float16 and move to GPU
>>> pipeline = StableDiffusionPipeline.from_single_file(
...     "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
...     torch_dtype=torch.float16,
... )
>>> pipeline.to("cuda")
```

#### load_lora_weights[[diffusers.StableDiffusionImg2ImgPipeline.load_lora_weights]]

```python
load_lora_weights(pretrained_model_name_or_path_or_dict: str | dict[str, torch.Tensor], adapter_name: str | None = None, hotswap: bool = False, **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders/lora_pipeline.py#L148)

**参数：**

pretrained_model_name_or_path_or_dict (`str` 或 `os.PathLike` 或 `dict`)：参见 [lora_state_dict()](/docs/diffusers/main/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.lora_state_dict)。

adapter_name (`str`，*可选*)：用于引用已加载的适配器模型的适配器名称。如果未指定，则使用 `default_{i}`，其中 i 为正在加载的适配器总数。

low_cpu_mem_usage (`bool`，*可选*)：通过仅加载预训练的 LoRA 权重而不初始化随机权重，来加快模型加载速度。

hotswap (`bool`, *可选*) : 默认为 `False`。是否就地用新加载的适配器替换现有的（LoRA）适配器。这意味着，不会加载额外的适配器，而是将现有适配器的权重替换为新适配器的权重。这种方式可能更快且更节省内存。然而，热替换的主要优势在于，当模型使用 torch.compile 编译时，加载新适配器无需重新编译模型。使用热替换时，传入的 `adapter_name` 应为已加载适配器的名称。 如果新适配器和旧适配器的秩（rank）和/或 LoRA alpha（即缩放）不同，在加载适配器之前需要调用一个额外方法：  ```py pipeline = ...  # load diffusers pipeline max_rank = ...  # the highest rank among all LoRAs that you want to load # call *before* compiling and loading the LoRA adapter pipeline.enable_lora_hotswap(target_rank=max_rank) pipeline.load_lora_weights(file_name) # optionally compile the model now ```  请注意，目前尚不支持对文本编码器适配器进行热替换。该技术还有一些其他限制，详见此处：https://huggingface.co/docs/peft/main/en/package_reference/hotswap

kwargs (`dict`，*可选*)：参见 [lora_state_dict()](/docs/diffusers/main/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.lora_state_dict)。

将 `pretrained_model_name_or_path_or_dict` 中指定的 LoRA 权重加载到 `self.unet` 和 `self.text_encoder` 中。

所有 kwargs 都会转发到 `self.lora_state_dict`。

有关状态字典加载方式的更多详细信息，请参阅 [lora_state_dict()](/docs/diffusers/main/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.lora_state_dict)。

有关状态字典如何加载到 `self.unet` 的更多详细信息，请参阅 [load_lora_into_unet()](/docs/diffusers/main/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_into_unet)。

有关状态字典如何加载到 `self.text_encoder` 的更多详细信息，请参阅 [load_lora_into_text_encoder()](/docs/diffusers/main/zh/api/loaders/lora#diffusers.loaders.StableDiffusionLoraLoaderMixin.load_lora_into_text_encoder)。

#### save_lora_weights[[diffusers.StableDiffusionImg2ImgPipeline.save_lora_weights]]

```python
save_lora_weights(save_directory: str | os.PathLike, unet_lora_layers: dict = None, text_encoder_lora_layers: dict = None, is_main_process: bool = True, weight_name: str = None, save_function: typing.Callable = None, safe_serialization: bool = True, unet_lora_adapter_metadata = None, text_encoder_lora_adapter_metadata = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/loaders/lora_pipeline.py#L466)

**参数：**

save_directory (`str` 或 `os.PathLike`)：用于保存 LoRA 参数的目录。如果该目录不存在，将自动创建。

unet_lora_layers (`dict[str, torch.nn.Module]` 或 `dict[str, torch.Tensor]`) : 与 `unet` 对应的 LoRA 层的 state dict。

text_encoder_lora_layers (`dict[str, torch.nn.Module]` 或 `dict[str, torch.Tensor]`) : 与 `text_encoder` 对应的 LoRA 层的 state dict。由于它来自 🤗 Transformers，因此必须显式传入文本编码器的 LoRA state dict。

is_main_process (`bool`，*可选*，默认为 `True`)：调用此函数的进程是否为主进程。在分布式训练期间，如果需要在所有进程上调用此函数，此参数非常有用。在这种情况下，仅在将 `is_main_process=True` 设置为主进程时，以避免竞态条件。

save_function (`Callable`) : 用于保存状态字典的函数。在分布式训练期间，当您需要用其他方法替换 `torch.save` 时非常有用。可通过环境变量 `DIFFUSERS_SAVE_MODE` 进行配置。

safe_serialization (`bool`，*可选*，默认为 `True`)：是否使用 `safetensors` 保存模型，还是使用传统的 PyTorch 方式（通过 `pickle`）。

unet_lora_adapter_metadata : 与 unet 关联的 LoRA 适配器元数据，将随 state dict 一起序列化。

text_encoder_lora_adapter_metadata : 与文本编码器关联的 LoRA 适配器元数据，将随状态字典一起序列化。

保存与 UNet 和文本编码器对应的 LoRA 参数。

#### encode_prompt[[diffusers.StableDiffusionImg2ImgPipeline.encode_prompt]]

```python
encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, lora_scale: float | None = None, clip_skip: int | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py#L358)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

device : (`torch.device`): torch 设备

num_images_per_prompt (`int`) : 每个提示词应生成的图像数量

do_classifier_free_guidance (`bool`) : 是否使用 classifier free guidance

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如* 提示词权重。如果未提供，negative_prompt_embeds 将从 `negative_prompt` 输入参数生成。

lora_scale (`float`, *可选*) : 如果加载了 LoRA 层，将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。

clip_skip (`int`, *可选*) : 在计算提示嵌入时，从 CLIP 中跳过的层数。值为 1 表示将使用倒数第二层的输出来计算提示嵌入。

将提示词编码为文本编码器的隐藏状态。

#### get_guidance_scale_embedding[[diffusers.StableDiffusionImg2ImgPipeline.get_guidance_scale_embedding]]

```python
get_guidance_scale_embedding(w: Tensor, embedding_dim: int = 512, dtype: dtype = torch.float32)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py#L801)

**参数：**

w (`torch.Tensor`) : 生成具有指定 guidance scale 的嵌入向量，以用于后续丰富时间步嵌入。

embedding_dim (`int`，*可选*，默认值为 512)：要生成的嵌入的维度。

dtype (`torch.dtype`，*可选*，默认为 `torch.float32`)：生成嵌入的数据类型。

**返回：** `torch.Tensor`

形状为 `(len(w), embedding_dim)` 的嵌入向量。

参见 https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

## StableDiffusionPipelineOutput[[diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput]]

#### diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput[[diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput]]

```python
diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray, nsfw_content_detected: list[bool] | None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_output.py#L10)

**参数：**

images (`list[PIL.Image.Image]` 或 `np.ndarray`)：长度为 `batch_size` 的去噪 PIL 图像列表，或形状为 `(batch_size, height, width, num_channels)` 的 NumPy 数组。

nsfw_content_detected (`list[bool]`) : 一个列表，指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容；如果无法执行安全检查，则为 `None`。

Stable Diffusion 管道的输出类。

