# FluxControlInpaint

  

FluxControlInpaintPipeline 是 Flux.1 Depth/Canny 模型的 Inpainting 实现。它是一个允许您使用 Flux.1 Depth/Canny 模型对图像进行修复的流水线。该流水线接收图像和掩码作为输入，并返回修复后的图像。

FLUX.1 Depth and Canny [dev] 是一个拥有 120 亿参数的 rectified flow transformer，能够根据文本描述生成图像，同时遵循给定输入图像的结构。**这不是一个 ControlNet 模型**。

| 控制类型 | 开发者 | 链接 |
| -------- | ---------- | ---- |
| 深度 | [Black Forest Labs](https://huggingface.co/black-forest-labs) | [链接](https://huggingface.co/black-forest-labs/FLUX.1-Depth-dev) |
| Canny | [Black Forest Labs](https://huggingface.co/black-forest-labs) | [链接](https://huggingface.co/black-forest-labs/FLUX.1-Canny-dev) |

> [!TIP]
> Flux 在消费级硬件设备上运行可能成本较高。不过，你可以执行一系列优化，使其运行得更快且更节省内存。有关更多详细信息，请参阅[本节](https://huggingface.co/blog/sd3#memory-optimizations-for-sd3)。此外，Flux 可以通过量化来提升内存效率，但代价是推理延迟会增加。要了解更多信息，请参阅[这篇博客文章](https://huggingface.co/blog/quanto-diffusers)。如需完整的资源列表，请查看[此 gist](https://gist.github.com/sayakpaul/b664605caf0aa3bf8585ab109dd5ac9c)。

```python
import torch
from diffusers import FluxControlInpaintPipeline
from diffusers.models.transformers import FluxTransformer2DModel
from transformers import T5EncoderModel
from diffusers.utils import load_image, make_image_grid
from image_gen_aux import DepthPreprocessor # https://github.com/huggingface/image_gen_aux
from PIL import Image
import numpy as np

pipe = FluxControlInpaintPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-Depth-dev",
    dtype=torch.bfloat16,
)
# use following lines if you have GPU constraints
# ---------------------------------------------------------------
transformer = FluxTransformer2DModel.from_pretrained(
    "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="transformer", dtype=torch.bfloat16
)
text_encoder_2 = T5EncoderModel.from_pretrained(
    "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="text_encoder_2", dtype=torch.bfloat16
)
pipe.transformer = transformer
pipe.text_encoder_2 = text_encoder_2
pipe.enable_model_cpu_offload()
# ---------------------------------------------------------------
pipe.to("cuda")  # or "mps", "xpu", "cpu"

prompt = "a blue robot singing opera with human-like expressions"
image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")

head_mask = np.zeros_like(image)
head_mask[65:580,300:642] = 255
mask_image = Image.fromarray(head_mask)

processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
control_image = processor(image)[0].convert("RGB")

output = pipe(
    prompt=prompt,
    image=image,
    control_image=control_image,
    mask_image=mask_image,
    num_inference_steps=30,
    strength=0.9,
    guidance_scale=10.0,
    generator=torch.Generator().manual_seed(42),
).images[0]
make_image_grid([image, control_image, mask_image, output.resize(image.size)], rows=1, cols=4).save("output.png")
```

## FluxControlInpaintPipeline[[diffusers.FluxControlInpaintPipeline]]

#### diffusers.FluxControlInpaintPipeline[[diffusers.FluxControlInpaintPipeline]]

```python
diffusers.FluxControlInpaintPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/flux/pipeline_flux_control_inpaint.py#L204)

**参数：**

transformer ([FluxTransformer2DModel](/docs/diffusers/v0.43.0/zh/api/models/flux_transformer#diffusers.FluxTransformer2DModel))：用于对编码后的图像潜变量进行去噪的条件 Transformer (MMDiT) 架构。

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler))：用于与 `transformer` 配合，对编码后的图像潜变量进行去噪的调度器。

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

text_encoder (`CLIPTextModel`)：即 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)，具体为 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 变体。

text_encoder_2 (`T5EncoderModel`)：即 [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)，具体为 [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) 变体。

tokenizer (`CLIPTokenizer`)：[CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) 类的分词器。

tokenizer_2 (`T5TokenizerFast`)：第二个 [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) 类的 Tokenizer。

使用 Flux-dev-Depth/Canny 进行图像修复的 Flux 流水线。

参考：https://blackforestlabs.ai/announcing-black-forest-labs/

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

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, masked_image_latents: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, height: int | None = None, width: int | None = None, strength: float = 0.6, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 7.0, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/flux/pipeline_flux_control_inpaint.py#L753)

**参数：**

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

prompt_2 (`str` 或 `list[str]`，*可选*) : 要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表。如果未定义，则使用 `prompt` 代替

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`，但如果直接传入潜变量，则不会再次进行编码。

control_image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、`list[np.ndarray]`、`list[list[torch.Tensor]]`、`list[list[np.ndarray]]` 或 `list[list[PIL.Image.Image]]`)：用于为 `unet` 提供生成引导的 ControlNet 输入条件。如果类型指定为 `torch.Tensor`，则会原样传递给 ControlNet。也可以接受 `PIL.Image.Image` 作为图像。输出图像的默认尺寸与 `image` 的尺寸相同。如果传入了高度和/或宽度，`image` 将相应地调整大小。如果在 `init` 中指定了多个 ControlNet，则必须以列表形式传入图像，以便列表中的每个元素都能被正确批处理，作为单个 ControlNet 的输入。

mask_image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]` 或 `list[np.ndarray]`) : `Image`、numpy 数组或张量，表示用于对 `image` 进行遮罩处理的图像批次。遮罩中的白色像素将被重绘，而黑色像素将保留。如果 `mask_image` 是 PIL 图像，则在使用前会将其转换为单通道（亮度）。如果它是 numpy 数组或 PyTorch 张量，则应包含一个颜色通道（L）而不是三个，因此 PyTorch 张量的预期形状为 `(B, 1, H, W)`、`(B, H, W)`、`(1, H, W)` 或 `(H, W)`。而 numpy 数组的预期形状为 `(B, H, W, 1)`、`(B, H, W)`、`(H, W, 1)` 或 `(H, W)`。

masked_image_latents (`torch.Tensor`, `list[torch.Tensor]`) : `Tensor`，表示用于对 VAE 生成的 `image` 进行遮罩的图像批次。如果未提供，遮罩潜变量张量将由 `mask_image` 生成。

height (`int`，*可选*，默认为 self.unet.config.sample_size * self.vae_scale_factor)：生成图像的高度（以像素为单位）。默认设置为 1024，以获得最佳效果。

width (`int`，*可选*，默认为 self.unet.config.sample_size * self.vae_scale_factor)：生成图像的像素宽度。默认设置为 1024 以获得最佳效果。

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

num_inference_steps (`int`, *可选*，默认为 50)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

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

guidance_scale (`float`，*可选*，默认值为 7.0)：[Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) 中定义的引导尺度。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，但通常以牺牲图像质量为代价。

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

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

latents (`torch.FloatTensor`, *可选*) : 预先生成的噪声潜变量，从高斯分布中采样得到，用作图像生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

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

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

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.flux.FluxPipelineOutput` 而不是普通元组。

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

callback_on_step_end (`Callable`，*可选*)：一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用：`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` 属性中列出的变量。

max_sequence_length (`int` 默认为 512)：用于 `prompt` 的最大序列长度。

**返回：** `~pipelines.flux.FluxPipelineOutput` 或 `tuple`

`~pipelines.flux.FluxPipelineOutput`（当 `return_dict` 为 True 时），否则为 `tuple`。返回元组时，第一个元素是包含生成图像的列表。

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

示例：
```py
import torch
from diffusers import FluxControlInpaintPipeline
from diffusers.models.transformers import FluxTransformer2DModel
from transformers import T5EncoderModel
from diffusers.utils import load_image, make_image_grid
from image_gen_aux import DepthPreprocessor  # https://github.com/huggingface/image_gen_aux
from PIL import Image
import numpy as np

pipe = FluxControlInpaintPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-Depth-dev",
    torch_dtype=torch.bfloat16,
)
# use following lines if you have GPU constraints
# ---------------------------------------------------------------
transformer = FluxTransformer2DModel.from_pretrained(
    "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="transformer", torch_dtype=torch.bfloat16
)
text_encoder_2 = T5EncoderModel.from_pretrained(
    "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="text_encoder_2", torch_dtype=torch.bfloat16
)
pipe.transformer = transformer
pipe.text_encoder_2 = text_encoder_2
pipe.enable_model_cpu_offload()
# ---------------------------------------------------------------
pipe.to("cuda")

prompt = "a blue robot singing opera with human-like expressions"
image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")

head_mask = np.zeros_like(image)
head_mask[65:580, 300:642] = 255
mask_image = Image.fromarray(head_mask)

processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
control_image = processor(image)[0].convert("RGB")

output = pipe(
    prompt=prompt,
    image=image,
    control_image=control_image,
    mask_image=mask_image,
    num_inference_steps=30,
    strength=0.9,
    guidance_scale=10.0,
    generator=torch.Generator().manual_seed(42),
).images[0]
make_image_grid([image, control_image, mask_image, output.resize(image.size)], rows=1, cols=4).save(
    "output.png"
)
```

#### encode_prompt[[diffusers.FluxControlInpaintPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], prompt_2: str | list[str] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/flux/pipeline_flux_control_inpaint.py#L376)

**参数：**

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

prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表。如果未定义，则所有文本编码器均使用 `prompt`。

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

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

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

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

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

## FluxPipelineOutput[[diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput]]

#### diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput[[diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput]]

```python
diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/flux/pipeline_output.py#L11)

**参数：**

images (`list[PIL.Image.Image]` 或 `torch.Tensor` 或 `np.ndarray`)：长度为 `batch_size` 的去噪 PIL 图像列表，或形状为 `(batch_size, height, width, num_channels)` 的 numpy 数组或 torch 张量。PIL 图像或 numpy 数组表示扩散流水线生成的去噪图像。Torch 张量可以表示去噪图像，也可以表示可直接传入解码器的中间潜变量。

Flux 图像生成流水线的输出类。

