Diffusers 文档

DiffEdit

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

DiffEdit

DiffEdit: 基于扩散的带掩模引导的语义图像编辑由Guillaume Couairon、Jakob Verbeek、Holger Schwenk和Matthieu Cord撰写。

论文摘要如下:

图像生成最近取得了巨大进展,扩散模型能够为各种文本提示合成令人信服的图像。在本文中,我们提出了DiffEdit,这是一种利用文本条件扩散模型进行语义图像编辑任务的方法,其目标是根据文本查询编辑图像。语义图像编辑是图像生成的扩展,额外限制是生成的图像应尽可能与给定输入图像相似。当前基于扩散模型的编辑方法通常需要提供掩模,这使得任务通过将其视为条件修复任务而变得容易得多。相比之下,我们的主要贡献在于能够通过对比扩散模型在不同文本提示下预测的结果,自动生成突出显示输入图像中需要编辑区域的掩模。此外,我们依赖潜在推理来保留这些感兴趣区域中的内容,并展示了与基于掩模的扩散的卓越协同作用。DiffEdit在ImageNet上实现了最先进的编辑性能。此外,我们还在更具挑战性的设置中评估了语义图像编辑,使用了来自COCO数据集的图像以及基于文本生成的图像。

原始代码库可在Xiang-cd/DiffEdit-stable-diffusion找到,您可以在此演示中试用它。

此管道由clarencechen贡献。❤️

提示

  • 该管道可以生成可馈送到其他图像修复管道的掩码。
  • 要使用此管道生成图像,必须提供图像掩码(源和目标提示可以手动指定或生成,并传递给generate_mask())和一组部分反转的潜在值(使用invert()生成)作为参数,以在调用管道生成最终编辑图像时使用。
  • 函数generate_mask()公开了两个提示参数:source_prompttarget_prompt,让您可以控制最终生成图像中语义编辑的位置。假设您想将“猫”转换为“狗”。在这种情况下,编辑方向将是“猫 -> 狗”。为了在生成的掩码中反映这一点,您只需将包含“猫”的短语相关的嵌入设置为source_prompt,将包含“狗”的短语相关的嵌入设置为target_prompt
  • 使用invert生成部分反转的潜在值时,将描述整个图像的标题或文本嵌入分配给prompt参数,以帮助引导反向潜在采样过程。在大多数情况下,源概念足以产生良好的结果,但请随意探索其他选项。
  • 在调用管道生成最终编辑图像时,将源概念分配给negative_prompt,将目标概念分配给prompt。以上述示例为例,您只需将包含“猫”的短语相关的嵌入设置为negative_prompt,将包含“狗”的短语相关的嵌入设置为prompt
  • 如果您想反转上述示例中的方向,即“狗 -> 猫”,那么建议您:
    • generate_mask的参数中交换source_prompttarget_prompt
    • invert()中的输入提示更改为包含“狗”。
    • 在调用管道生成最终编辑图像时,交换promptnegative_prompt的参数。
  • 源和目标提示,或其对应的嵌入,也可以自动生成。有关更多详细信息,请参阅DiffEdit指南。

StableDiffusionDiffEditPipeline

diffusers.StableDiffusionDiffEditPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor inverse_scheduler: DDIMInverseScheduler requires_safety_checker: bool = True )

参数

  • vae (AutoencoderKL) — 用于将图像编码和解码为潜在表示的变分自编码器 (VAE) 模型。
  • text_encoder (CLIPTextModel) — 冻结的文本编码器 (clip-vit-large-patch14)。
  • tokenizer (CLIPTokenizer) — 用于文本分词的CLIPTokenizer
  • unet (UNet2DConditionModel) — 用于对编码图像潜在值进行去噪的UNet2DConditionModel
  • scheduler (SchedulerMixin) — 与unet结合使用,对编码图像潜在值进行去噪的调度器。
  • inverse_scheduler (DDIMInverseScheduler) — 与unet结合使用,用于填充输入潜在值中未被遮罩部分的调度器。
  • safety_checker (StableDiffusionSafetyChecker) — 分类模块,用于评估生成的图像是否可能被视为冒犯性或有害。有关模型潜在危害的更多详细信息,请参阅模型卡片
  • feature_extractor (CLIPImageProcessor) — 用于从生成的图像中提取特征的CLIPImageProcessor;用作safety_checker的输入。

这是一个实验性功能!

使用Stable Diffusion和DiffEdit进行文本引导图像修复的管道。

该模型继承自DiffusionPipeline。有关所有管道实现的通用方法(下载、保存、在特定设备上运行等),请查看超类文档。

该管道还继承了以下加载和保存方法:

生成掩码

< >

( image: typing.Union[torch.Tensor, PIL.Image.Image] = None target_prompt: typing.Union[str, typing.List[str], NoneType] = None target_negative_prompt: typing.Union[str, typing.List[str], NoneType] = None target_prompt_embeds: typing.Optional[torch.Tensor] = None target_negative_prompt_embeds: typing.Optional[torch.Tensor] = None source_prompt: typing.Union[str, typing.List[str], NoneType] = None source_negative_prompt: typing.Union[str, typing.List[str], NoneType] = None source_prompt_embeds: typing.Optional[torch.Tensor] = None source_negative_prompt_embeds: typing.Optional[torch.Tensor] = None num_maps_per_mask: typing.Optional[int] = 10 mask_encode_strength: typing.Optional[float] = 0.5 mask_thresholding_ratio: typing.Optional[float] = 3.0 num_inference_steps: int = 50 guidance_scale: float = 7.5 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None output_type: typing.Optional[str] = 'np' cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None ) List[PIL.Image.Image]np.array

参数

  • image (PIL.Image.Image) — 用于计算掩码的图像或表示图像批次的张量。
  • target_prompt (strList[str], 可选) — 用于引导语义掩码生成的提示。如果未定义,您需要传递prompt_embeds
  • target_negative_prompt (strList[str], 可选) — 用于引导不包含在图像生成中的提示。如果未定义,您需要传递negative_prompt_embeds。当不使用引导时 (guidance_scale < 1),此参数将被忽略。
  • target_prompt_embeds (torch.Tensor, 可选) — 预先生成的文本嵌入。可用于轻松调整文本输入(提示加权)。如果未提供,则从prompt输入参数生成文本嵌入。
  • target_negative_prompt_embeds (torch.Tensor, 可选) — 预先生成的负面文本嵌入。可用于轻松调整文本输入(提示加权)。如果未提供,则从negative_prompt输入参数生成negative_prompt_embeds
  • source_prompt (strList[str], 可选) — 用于使用DiffEdit引导语义掩码生成的提示。如果未定义,您需要传递source_prompt_embedssource_image
  • source_negative_prompt (strList[str], 可选) — 用于使用DiffEdit引导语义掩码生成远离的提示。如果未定义,您需要传递source_negative_prompt_embedssource_image
  • source_prompt_embeds (torch.Tensor, 可选) — 预先生成的文本嵌入,用于引导语义掩码生成。可用于轻松调整文本输入(提示加权)。如果未提供,则从source_prompt输入参数生成文本嵌入。
  • source_negative_prompt_embeds (torch.Tensor, 可选) — 预先生成的文本嵌入,用于负向引导语义掩码生成。可用于轻松调整文本输入(提示加权)。如果未提供,则从source_negative_prompt输入参数生成文本嵌入。
  • num_maps_per_mask (int, 可选, 默认为 10) — 用于使用DiffEdit生成语义掩码的噪声图数量。
  • mask_encode_strength (float, 可选, 默认为 0.5) — 用于使用DiffEdit生成语义掩码的噪声图强度。必须介于0和1之间。
  • mask_thresholding_ratio (float, 可选, 默认为 3.0) — 用于在掩码二值化之前限制语义引导图的平均绝对差的最大倍数。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步数。更多的去噪步数通常会带来更高质量的图像,但会牺牲更慢的推理速度。
  • guidance_scale (float, 可选, 默认为 7.5) — 较高的引导比例值鼓励模型生成与文本prompt紧密相关的图像,但会牺牲图像质量。当guidance_scale > 1时启用引导比例。
  • generator (torch.GeneratorList[torch.Generator], 可选) — torch.Generator,用于使生成具有确定性。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。在PIL.Imagenp.array之间选择。
  • cross_attention_kwargs (dict, 可选) — 一个kwargs字典,如果指定,将传递给AttnProcessor,如self.processor中定义。

返回

List[PIL.Image.Image]np.array

当返回一个 List[PIL.Image.Image] 时,列表由一批单通道二值图像组成,尺寸为 (height // self.vae_scale_factor, width // self.vae_scale_factor)。如果它是 np.array,则形状为 (batch_size, height // self.vae_scale_factor, width // self.vae_scale_factor)

根据掩码提示、目标提示和图像生成潜在掩码。

>>> import PIL
>>> import requests
>>> import torch
>>> from io import BytesIO

>>> from diffusers import StableDiffusionDiffEditPipeline


>>> def download_image(url):
...     response = requests.get(url)
...     return PIL.Image.open(BytesIO(response.content)).convert("RGB")


>>> img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"

>>> init_image = download_image(img_url).resize((768, 768))

>>> pipeline = StableDiffusionDiffEditPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16
... )

>>> pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
>>> pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)
>>> pipeline.enable_model_cpu_offload()

>>> mask_prompt = "A bowl of fruits"
>>> prompt = "A bowl of pears"

>>> mask_image = pipeline.generate_mask(image=init_image, source_prompt=prompt, target_prompt=mask_prompt)
>>> image_latents = pipeline.invert(image=init_image, prompt=mask_prompt).latents
>>> image = pipeline(prompt=prompt, mask_image=mask_image, image_latents=image_latents).images[0]

反转

< >

( prompt: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[torch.Tensor, PIL.Image.Image] = None num_inference_steps: int = 50 inpaint_strength: float = 0.8 guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None decode_latents: bool = False output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: typing.Optional[int] = 1 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None lambda_auto_corr: float = 20.0 lambda_kl: float = 20.0 num_reg_steps: int = 0 num_auto_corr_rolls: int = 5 )

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示词。如果未定义,则需要传入 prompt_embeds
  • image (PIL.Image.Image) — 表示图像批次的图像或张量,用于根据 prompt 引导反转潜在值。
  • inpaint_strength (float, 可选, 默认为 0.8) — 表示运行潜在反转去噪过程的程度。必须在 0 到 1 之间。当 inpaint_strength 为 1 时,反转过程将运行 num_inference_steps 中指定的全部迭代次数。image 用作反转过程的参考,增加更多噪声会增加 inpaint_strength。如果 inpaint_strength 为 0,则不会发生内绘。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步数。更多的去噪步数通常会带来更高质量的图像,但推理速度会变慢。
  • guidance_scale (float, 可选, 默认为 7.5) — 更高的引导比例值鼓励模型生成与文本 prompt 紧密相关的图像,但会牺牲图像质量。当 guidance_scale > 1 时启用引导比例。
  • negative_prompt (strList[str], 可选) — 引导图像生成时不包含的提示词。如果未定义,则需要传入 negative_prompt_embeds。当不使用引导时(guidance_scale < 1)会被忽略。
  • generator (torch.Generator, 可选) — 一个 torch.Generator 用于使生成具有确定性。
  • prompt_embeds (torch.Tensor, 可选) — 预先生成的文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,则文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预先生成的负面文本嵌入。可用于轻松调整文本输入(提示词权重)。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • decode_latents (bool, 可选, 默认为 False) — 是否将反转的潜在值解码为生成的图像。将此参数设置为 True 会将每个时间步的所有反转潜在值解码为生成的图像列表。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。选择 PIL.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.stable_diffusion.DiffEditInversionPipelineOutput 而不是普通元组。
  • callback (Callable, 可选) — 在推理过程中每 callback_steps 步调用的函数。该函数将使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — 调用 callback 函数的频率。如果未指定,则在每一步都调用回调。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 AttnProcessor,如 self.processor 中定义。
  • lambda_auto_corr (float, 可选, 默认为 20.0) — 用于控制自相关性的 Lambda 参数。
  • lambda_kl (float, 可选, 默认为 20.0) — 用于控制 Kullback-Leibler 散度输出的 Lambda 参数。
  • num_reg_steps (int, 可选, 默认为 0) — 正则化损失步数。
  • num_auto_corr_rolls (int, 可选, 默认为 5) — 自相关滚动步数。

根据提示和图像生成反转的潜在值。

>>> import PIL
>>> import requests
>>> import torch
>>> from io import BytesIO

>>> from diffusers import StableDiffusionDiffEditPipeline


>>> def download_image(url):
...     response = requests.get(url)
...     return PIL.Image.open(BytesIO(response.content)).convert("RGB")


>>> img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"

>>> init_image = download_image(img_url).resize((768, 768))

>>> pipeline = StableDiffusionDiffEditPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16
... )

>>> pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
>>> pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)
>>> pipeline.enable_model_cpu_offload()

>>> prompt = "A bowl of fruits"

>>> inverted_latents = pipeline.invert(image=init_image, prompt=prompt).latents

__call__

< >

( prompt: typing.Union[str, typing.List[str], NoneType] = None mask_image: typing.Union[torch.Tensor, PIL.Image.Image] = None image_latents: typing.Union[torch.Tensor, PIL.Image.Image] = None inpaint_strength: typing.Optional[float] = 0.8 num_inference_steps: int = 50 guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_images_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: int = None ) StableDiffusionPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示词。如果未定义,则需要传入 prompt_embeds
  • mask_image (PIL.Image.Image) — 用于遮罩生成图像的图像或张量批次。遮罩中的白色像素将被重新绘制,而黑色像素将被保留。如果 mask_image 是 PIL 图像,它在使用前将转换为单通道(亮度)。如果它是张量,它应该包含一个颜色通道 (L) 而不是 3 个,所以预期的形状是 (B, 1, H, W)
  • image_latents (PIL.Image.Imagetorch.Tensor) — 从反转过程中部分去噪的图像潜在值,用作图像生成的输入。
  • inpaint_strength (float, 可选, 默认为 0.8) — 表示对遮罩区域进行内绘的程度。必须在 0 到 1 之间。当 inpaint_strength 为 1 时,对遮罩区域的去噪过程将运行 num_inference_steps 中指定的全部迭代次数。image_latents 用作遮罩区域的参考,增加更多噪声会增加 inpaint_strength。如果 inpaint_strength 为 0,则不会发生内绘。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步数。更多的去噪步数通常会带来更高质量的图像,但推理速度会变慢。
  • guidance_scale (float, 可选, 默认为 7.5) — 更高的引导比例值鼓励模型生成与文本 prompt 紧密相关的图像,但会牺牲图像质量。当 guidance_scale > 1 时启用引导比例。
  • negative_prompt (strList[str], 可选) — 引导图像生成时不包含的提示词。如果未定义,则需要传入 negative_prompt_embeds。当不使用引导时(guidance_scale < 1)会被忽略。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示词生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中被忽略。
  • generator (torch.Generator, 可选) — 一个 torch.Generator 用于使生成具有确定性。
  • latents (torch.Tensor, 可选) — 从高斯分布中采样的预生成噪声潜在值,用作图像生成的输入。可用于使用不同的提示词调整相同的生成。如果未提供,则通过使用提供的随机 generator 进行采样来生成潜在值张量。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如提示词权重。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。选择 PIL.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 StableDiffusionPipelineOutput 而不是普通元组。
  • callback (Callable, 可选) — 在推理过程中每 callback_steps 步调用的函数。该函数将使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
  • callback_steps (int, 可选, 默认为 1) — 调用 callback 函数的频率。如果未指定,则在每一步都调用回调。
  • cross_attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 self.processor 中定义的 AttentionProcessor
  • clip_skip (int, 可选) — 在计算提示词嵌入时跳过 CLIP 的层数。值为 1 表示将使用倒数第二层的输出计算提示词嵌入。

返回

StableDiffusionPipelineOutputtuple

如果 return_dictTrue,则返回 StableDiffusionPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表,第二个元素是指示相应生成的图像是否包含“不适合工作”(nsfw) 内容的 bool 列表。

用于生成的管道的调用函数。

>>> import PIL
>>> import requests
>>> import torch
>>> from io import BytesIO

>>> from diffusers import StableDiffusionDiffEditPipeline


>>> def download_image(url):
...     response = requests.get(url)
...     return PIL.Image.open(BytesIO(response.content)).convert("RGB")


>>> img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"

>>> init_image = download_image(img_url).resize((768, 768))

>>> pipeline = StableDiffusionDiffEditPipeline.from_pretrained(
...     "stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16
... )

>>> pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
>>> pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)
>>> pipeline.enable_model_cpu_offload()

>>> mask_prompt = "A bowl of fruits"
>>> prompt = "A bowl of pears"

>>> mask_image = pipeline.generate_mask(image=init_image, source_prompt=prompt, target_prompt=mask_prompt)
>>> image_latents = pipeline.invert(image=init_image, prompt=mask_prompt).latents
>>> image = pipeline(prompt=prompt, mask_image=mask_image, image_latents=image_latents).images[0]

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: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )

参数

  • prompt (strList[str], 可选) — 要编码的提示词
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用分类器自由引导
  • negative_prompt (strList[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 表示将使用倒数第二层的输出计算提示词嵌入。

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

StableDiffusionPipelineOutput

class diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput

< >

( images: typing.Union[typing.List[PIL.Image.Image], numpy.ndarray] nsfw_content_detected: typing.Optional[typing.List[bool]] )

参数

  • 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 管道的输出类。

< > 在 GitHub 上更新