Buckets:

hf-doc-build/doc / diffusers /main /ja /api /pipelines /control_flux_inpaint.md
mishig's picture
|
download
raw
21.8 kB
# 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/main/src/diffusers/pipelines/flux/pipeline_flux_control_inpaint.py#L204)
**パラメータ:**
transformer ([FluxTransformer2DModel](/docs/diffusers/main/ja/api/models/flux_transformer#diffusers.FluxTransformer2DModel)) : エンコードされた画像潜在変数をノイズ除去するための条件付き Transformer (MMDiT) アーキテクチャ。
scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ja/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer` と組み合わせて、エンコードされた画像の潜在変数をデノイズするために使用するスケジューラー。
vae ([AutoencoderKL](/docs/diffusers/main/ja/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。
tokenizer_2 (`T5TokenizerFast`) : クラス [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) の2番目の Tokenizer。
Flux-dev-Depth/Canny を用いた画像インペインティングのための Flux パイプライン。
参考: https://blackforestlabs.ai/announcing-black-forest-labs/
#### __call__[[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/main/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` として画像の潜在変数(latents)を受け取ることもできますが、潜在変数を直接渡す場合は、再度エンコードされません。
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` をマスクするための `Image`、numpy 配列、またはテンソル。マスク内の白いピクセルは再描画され、黒いピクセルは保持されます。`mask_image` が PIL イメージの場合、使用の前に単一チャネル(輝度)に変換されます。numpy 配列または PyTorch テンソルの場合は、3 チャネルではなく 1 つの色チャネル(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]`) : VAEによって生成された`image`をマスクするための画像バッチを表す`Tensor`。指定されない場合、マスク用の潜変数テンソルは`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` 引数をサポートするスケジューラーにおいて、デノイジングプロセスに使用するカスタムシグマ。`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) 1 つまたはそのリスト。
latents (`torch.FloatTensor`, *任意*) : 画像生成の入力として使用する、ガウス分布からサンプリングされた事前生成されたノイズ付き潜在変数(latents)。異なるプロンプトで同じ生成を調整するために使用できます。指定されない場合、指定されたランダム`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`, *任意*) : 指定された場合、[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) の `self.processor` で定義されている `AttentionProcessor` に渡される kwargs の辞書です。
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`
`return_dict` が True の場合は `~pipelines.flux.FluxPipelineOutput`、それ以外の場合は `tuple` を返します。tuple を返す場合、最初の要素は生成された画像のリストです。
生成用のパイプラインを呼び出したときに実行される関数。
例:
```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/main/src/diffusers/pipelines/flux/pipeline_flux_control_inpaint.py#L376)
**パラメータ:**
prompt (`str` または `list[str]`、*省略可能*) : エンコードするプロンプト
prompt_2 (`str` または `list[str]`、*省略可*) : `tokenizer_2` および `text_encoder_2` に送信するプロンプトです。未定義の場合、すべての text-encoder で `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/main/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画像生成パイプライン用の出力クラス。

Xet Storage Details

Size:
21.8 kB
·
Xet hash:
f6c6c358458a2b28adbad49c48e5b0f55878f4c8ea686550fbc1da346d543bcb

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.