Diffusers 文档
FluxControlInpaint
并获得增强的文档体验
开始使用
FluxControlInpaint
FluxControlInpaintPipeline 是 Flux.1 Depth/Canny 模型图像修复的实现。它是一个允许您使用 Flux.1 Depth/Canny 模型修复图像的 pipeline。该 pipeline 接受图像和蒙版作为输入,并返回修复后的图像。
FLUX.1 Depth 和 Canny [dev] 是一个 120 亿参数的修正流 Transformer,能够根据文本描述生成图像,同时遵循给定输入图像的结构。这不是 ControlNet 模型。
控制类型 | 开发者 | 链接 |
---|---|---|
深度 | Black Forest Labs | 链接 |
Canny | Black Forest Labs | 链接 |
Flux 在消费级硬件设备上运行可能相当昂贵。但是,您可以执行一系列优化,使其运行更快且更节省内存。查看此部分了解更多详情。此外,Flux 可以通过量化来提高内存效率,但需要在推理延迟方面做出权衡。请参阅这篇博客文章以了解更多信息。有关资源的详尽列表,请查看此 gist。
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")
FluxControlInpaintPipeline
class diffusers.FluxControlInpaintPipeline
< source >( scheduler: FlowMatchEulerDiscreteScheduler vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer text_encoder_2: T5EncoderModel tokenizer_2: T5TokenizerFast transformer: FluxTransformer2DModel )
Parameters
- transformer (FluxTransformer2DModel) — 用于去噪编码图像潜在空间的条件 Transformer (MMDiT) 架构。
- scheduler (FlowMatchEulerDiscreteScheduler) — 一个调度器,与
transformer
结合使用,以去噪编码的图像潜在空间。 - vae (AutoencoderKL) — 变分自动编码器 (VAE) 模型,用于将图像编码和解码为潜在表示,以及从潜在表示解码回图像。
- text_encoder (
CLIPTextModel
) — CLIP, 特别是 clip-vit-large-patch14 变体。 - text_encoder_2 (
T5EncoderModel
) — T5, 特别是 google/t5-v1_1-xxl 变体。 - tokenizer (
CLIPTokenizer
) — CLIPTokenizer 类的分词器。 - tokenizer_2 (
T5TokenizerFast
) — T5TokenizerFast 类的第二个分词器。
The Flux pipeline for image inpainting using Flux-dev-Depth/Canny.
Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None mask_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None masked_image_latents: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None strength: float = 0.6 num_inference_steps: int = 28 sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.0 num_images_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.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: typing.Optional[str] = 'pil' return_dict: bool = True joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) → ~pipelines.flux.FluxPipelineOutput
or tuple
Parameters
- 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]]
): ControlNet 输入条件,用于为生成提供unet
指导。 如果类型指定为torch.Tensor
,则按原样传递给 ControlNet。PIL.Image.Image
也可以接受作为图像。 输出图像的尺寸默认为image
的尺寸。 如果传递了 height 和/或 width,则会相应地调整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) 而不是 3 个,因此 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)
。 - mask_image_latent (
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 中定义的 guidance scale。guidance_scale
定义为 Imagen Paper 的公式 2 中的w
。 通过设置guidance_scale > 1
启用 Guidance scale。 较高的 guidance scale 鼓励生成与文本prompt
紧密相关的图像,通常以较低的图像质量为代价。 - num_images_per_prompt (
int
, 可选, 默认为 1) — 每个提示要生成的图像数量。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 一个或多个 torch 生成器,用于使生成具有确定性。 - latents (
torch.FloatTensor
, optional) — 预生成的噪声潜在变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示调整相同的生成结果。如果未提供,将通过使用提供的随机generator
进行采样来生成潜在变量张量。 - prompt_embeds (
torch.FloatTensor
, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,文本嵌入将从prompt
输入参数生成。 - pooled_prompt_embeds (
torch.FloatTensor
, optional) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,池化文本嵌入将从prompt
输入参数生成。 - output_type (
str
, optional, defaults to"pil"
) — 生成图像的输出格式。在 PIL:PIL.Image.Image
或np.array
之间选择。 - return_dict (
bool
, optional, defaults toTrue
) — 是否返回~pipelines.flux.FluxPipelineOutput
而不是普通元组。 - joint_attention_kwargs (
dict
, optional) — 一个 kwargs 字典,如果指定,则作为self.processor
下定义的AttentionProcessor
的参数传递,定义在 diffusers.models.attention_processor 中。 - callback_on_step_end (
Callable
, optional) — 在推理期间,在每个去噪步骤结束时调用的函数。该函数使用以下参数调用: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
, optional) —callback_on_step_end
函数的张量输入列表。列表中指定的张量将作为callback_kwargs
参数传递。您只能包含管道类的._callback_tensor_inputs
属性中列出的变量。 - max_sequence_length (
int
defaults to 512) — 与prompt
一起使用的最大序列长度。
返回
~pipelines.flux.FluxPipelineOutput
或 tuple
如果 return_dict
为 True,则返回 ~pipelines.flux.FluxPipelineOutput
,否则返回 tuple
。当返回元组时,第一个元素是包含生成图像的列表。
调用管道进行生成时调用的函数。
示例
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"
)
禁用切片 VAE 解码。如果之前启用了 enable_vae_slicing
,此方法将恢复为一步计算解码。
禁用平铺 VAE 解码。如果之前启用了 enable_vae_tiling
,此方法将恢复为一步计算解码。
启用切片 VAE 解码。启用此选项后,VAE 将输入张量拆分为切片,以分步计算解码。这有助于节省一些内存并允许更大的批量大小。
启用平铺 VAE 解码。启用此选项后,VAE 会将输入张量拆分为平铺,以分步计算解码和编码。这对于节省大量内存并允许处理更大的图像非常有用。
encode_prompt
< source >( prompt: typing.Union[str, typing.List[str]] prompt_2: typing.Union[str, typing.List[str]] 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: typing.Optional[float] = None )
Parameters
- prompt (
str
orList[str]
, optional) — 要编码的提示词 - prompt_2 (
str
orList[str]
, optional) — 要发送到tokenizer_2
和text_encoder_2
的提示词。如果未定义,则prompt
将用于所有文本编码器 - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个提示应生成的图像数量 - prompt_embeds (
torch.FloatTensor
, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,文本嵌入将从prompt
输入参数生成。 - pooled_prompt_embeds (
torch.FloatTensor
, optional) — 预生成的池化文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,池化文本嵌入将从prompt
输入参数生成。 - lora_scale (
float
, optional) — 如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层的 lora 缩放比例。
FluxPipelineOutput
class diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput
< source >( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] )
Stable Diffusion 管道的输出类。