# SegGPT

## 概要

SegGPTモデルは、Xinlong Wang、Xiaosong Zhang、Yue Cao、Wen Wang、Chunhua Shen、Tiejun Huang による [SegGPT: Segmenting Everything In Context](https://huggingface.co/papers/2304.03284) で提案されました。SegGPTは、入力画像、プロンプト画像、およびそれに対応するプロンプトマスクが与えられたときにセグメンテーションマスクを生成できる、デコーダーのみで構成されるTransformerを採用しています。このモデルは、COCO-20で56.1 mIoU、FSS-1000で85.6 mIoUという、ワンショット条件下での優れた結果を達成しています。

論文の抄録は以下の通りです。

*我々は、コンテキスト内であらゆるものをセグメンテーションする汎用モデルであるSegGPTを提案します。SegGPTは、異なる種類のセグメンテーションデータを同一形式の画像に変換することでそれらを収容する汎用的なインコンテキスト学習フレームワークに、多様なセグメンテーションタスクを統合します。SegGPTの学習は、各データサンプルに対してランダムなカラーマッピングを用いたインコンテキストカラーリング問題として定式化されます。その目的は、特定のカラーに依存するのではなく、コンテキストに基づいて多様なタスクを達成することです。学習後、SegGPTは、オブジェクトインスタンス、スタフ、パーツ、輪郭、テキストなどのインコンテキスト推論を通じて、画像や動画における任意のセグメンテーションタスクを実行できます。SegGPTは、フェューショットセマンティックセグメンテーション、ビデオオブジェクトセグメンテーション、セマンティックセグメンテーション、パノプティックセグメンテーションを含む幅広いタスクで評価されます。我々の結果は、ドメイン内およびドメイン外のセグメンテーションにおける強力な能力を示しています。*

ヒント:

- [SegGptImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/seggpt#transformers.SegGptImageProcessor) を使用して、モデルへの画像入力、プロンプト、マスクを準備できます。
- プロンプトマスクとして、セグメンテーションマップまたはRGB画像のいずれかを使用できます。後者を使用する場合は、`preprocess`メソッド内で`do_convert_rgb=False`を設定してください。
- `segmentation_maps`（背景を考慮しない）を前処理および後処理で使用する場合、[SegGptImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/seggpt#transformers.SegGptImageProcessor) には `num_labels` を渡すことを強く推奨します。
- [SegGptForImageSegmentation](/docs/transformers/v5.23.0/ja/model_doc/seggpt#transformers.SegGptForImageSegmentation) を用いて推論を行う場合、`batch_size` が 1 より大きい場合は、forward メソッドに `feature_ensemble=True` を渡すことで、画像間のフィーチャーアンサンブルを利用できます。

ワンショットセマンティックセグメンテーションにモデルを使用する方法は以下の通りです。

```python
import torch
from datasets import load_dataset

from transformers import SegGptForImageSegmentation, SegGptImageProcessor

checkpoint = "BAAI/seggpt-vit-large"
image_processor = SegGptImageProcessor.from_pretrained(checkpoint)
model = SegGptForImageSegmentation.from_pretrained(checkpoint, device_map="auto")

dataset_id = "EduardoPacheco/FoodSeg103"
ds = load_dataset(dataset_id, split="train")
# Number of labels in FoodSeg103 (not including background)
num_labels = 103

image_input = ds[4]["image"]
ground_truth = ds[4]["label"]
image_prompt = ds[29]["image"]
mask_prompt = ds[29]["label"]

inputs = image_processor(
    images=image_input,
    prompt_images=image_prompt,
    segmentation_maps=mask_prompt,
    num_labels=num_labels,
    return_tensors="pt"
)

with torch.no_grad():
    outputs = model(**inputs)

target_sizes = [image_input.size[::-1]]
mask = image_processor.post_process_semantic_segmentation(outputs, target_sizes, num_labels=num_labels)[0]
```

このモデルは[EduardoPacheco](https://huggingface.co/EduardoPacheco)によって提供されました。元のコードは[こちら](https://github.com/baaivision/Painter/tree/main)で確認できます。

## SegGptConfig[[transformers.SegGptConfig]]

#### transformers.SegGptConfig[[transformers.SegGptConfig]]

```python
transformers.SegGptConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 1024, num_hidden_layers: int = 24, num_attention_heads: int = 16, hidden_act: str = 'gelu', hidden_dropout_prob: float | int = 0.0, initializer_range: float = 0.02, layer_norm_eps: float = 1e-06, image_size: int | list[int] | tuple[int, ...] = (896, 448), patch_size: int | list[int] | tuple[int, int] = 16, num_channels: int = 3, qkv_bias: bool = True, mlp_dim: int | None = None, drop_path_rate: float | int = 0.1, pretrain_image_size: int | list[int] | tuple[int, int] = 224, decoder_hidden_size: int = 64, use_relative_position_embeddings: bool = True, merge_index: int = 2, intermediate_hidden_state_indices: list[int] | tuple[int, ...] = (5, 11, 17, 23), beta: float = 0.01)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/seggpt/configuration_seggpt.py#L24)

**パラメータ:**

hidden_size (`int`、*任意*、デフォルトは`1024`) : 隠れ表現の次元数。

num_hidden_layers (`int`、*optional*、デフォルトは `24`) : Transformer デコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは`16`) : Transformerデコーダーの各アテンション層におけるアテンションヘッドの数。

hidden_act (`str`、*任意*、デフォルトは`gelu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

hidden_dropout_prob (`Union[float, int]`、*任意*、デフォルトは`0.0`) : embeddings、encoder、pooler 内のすべての全結合層における dropout 確率。

initializer_range (`float`、*任意*、デフォルトは`0.02`) : すべての重み行列を初期化するためのtruncated_normal_initializerの標準偏差です。

layer_norm_eps (`float`、*任意*、デフォルトは`1e-06`) : Layer Normalization 層で使用する epsilon です。

image_size (`Union[int, list[int], tuple[int, ...]]`、*任意*、デフォルトは`(896, 448)`) : 各画像のサイズ（解像度）。

patch_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`16`) : 各パッチのサイズ（解像度）。

num_channels (`int`、*任意*、デフォルトは`3`) : 入力チャネル数。

qkv_bias (`bool`, *任意*, デフォルトは `True`) : クエリ、キー、バリューにバイアスを追加するかどうか。

mlp_dim (`int`, *optional*) : TransformerエンコーダーのMLP層の次元数。未設定の場合、`hidden_size` * 4がデフォルト値として使用されます。

drop_path_rate (`Union[float, int]`、*任意*、デフォルトは`0.1`) : パッチ融合のドロップパス率。

pretrain_image_size (`int`, *optional*, デフォルトは 224) : 絶対位置埋め込みの事前学習サイズ。

decoder_hidden_size (`int`、*任意*、デフォルトは`64`) : 隠れ表現の次元数。

use_relative_position_embeddings (`bool`、*任意*、デフォルトは`True`) : アテンション層で相対位置埋め込みを使用するかどうか。

merge_index (`int`、*optional*、デフォルトは 2) : 埋め込みをマージするエンコーダ層のインデックス。

intermediate_hidden_state_indices (`list[int]`、*optional*、デフォルトは`[5, 11, 17, 23]`) : デコーダー用の特徴として保存するエンコーダー層のインデックスです。

beta (`float`、*optional*、デフォルトは 0.01) : SegGptLoss (smooth-l1 loss) の正則化係数。

これはSegGptModelの設定を保存するための設定クラスです。指定された引数に基づいてSeggptモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[BAAI/seggpt-vit-large](https://huggingface.co/BAAI/seggpt-vit-large)と類似した設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/v5.23.0/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/v5.23.0/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

例:

```python
>>> from transformers import SegGptConfig, SegGptModel

>>> # Initializing a SegGPT seggpt-vit-large style configuration
>>> configuration = SegGptConfig()

>>> # Initializing a model (with random weights) from the seggpt-vit-large style configuration
>>> model = SegGptModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## SegGptImageProcessor[[transformers.SegGptImageProcessor]]

#### transformers.SegGptImageProcessor[[transformers.SegGptImageProcessor]]

```python
transformers.SegGptImageProcessor(**kwargs: *<class 'transformers.models.seggpt.image_processing_seggpt.SegGptImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/seggpt/image_processing_seggpt.py#L74)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *任意*, デフォルトは `True`) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルト値は`{'height' : 448, 'width': 448}`): モデルへの最大入力次元を説明します。

default_to_square (`bool`, *kwargs*, *任意*、デフォルトは `True`) : size が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルトは `3`) : 画像をリサイズする場合に使用するリサンプリングフィルター。`PILImageResampling` の列挙型のいずれかになります。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.485, 0.456, 0.406]`) : 正規化に使用する画像の平均値です。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.229, 0.224, 0.225]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

num_labels (`int`, *kwargs*, *optional*) : セグメンテーションタスクにおけるクラス数（背景を除く）。指定された場合、class_idx 0 が背景であると仮定して、プレーンなセグメンテーションマップからプロンプトマスクを3チャネルのRGB画像へマッピングするためのパレットが構築されます。これを指定しない場合、`do_convert_rgb` が `True` のとき、プロンプトマスクはチャネル次元に沿って複製されます。

SegGptImageProcessor イメージプロセッサを構築します。

#### preprocess[[transformers.SegGptImageProcessor.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, prompt_images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, prompt_masks: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.models.seggpt.image_processing_seggpt.SegGptImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/seggpt/image_processing_seggpt.py#L135)

**パラメータ:**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`, *任意*) : 前処理を行う画像。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチの画像を想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、`do_rescale=False` を設定してください。

prompt_images (`ImageInput`, *任意*) : 前処理するプロンプト画像。ピクセル値が0から255の範囲にある単一の画像またはバッチの画像を期待します。

prompt_masks (`ImageInput`, *任意*) : 前処理を行うプロンプトマスク。セグメンテーションマップ（チャネルなし）またはRGB画像の形式で指定できます。RGB画像の形式の場合、`do_convert_rgb`は`False`に設定する必要があります。セグメンテーションマップの形式の場合、プロンプトマスクを単一チャネルから3チャネルのRGBへマッピングするためのパレットを構築するために、`num_labels`の指定が推奨されます。`num_labels`が指定されていない場合、プロンプトマスクはチャネル次元に沿って複製されます。

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *任意*) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

num_labels (`int`, *kwargs*, *optional*) : セグメンテーションタスクにおけるクラス数（背景を除く）。指定された場合、class_idx 0 が背景であると仮定して、プレーンなセグメンテーションマップからプロンプトマスクを3チャネルのRGB画像へマッピングするためのパレットが構築されます。これを指定しない場合、`do_convert_rgb` が `True` のとき、プロンプトマスクはチャネル次元に沿って複製されます。

**戻り値:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ メソッドによって返されるリスト/配列/テンソルの辞書（'pixel_values' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

#### post_process_semantic_segmentation[[transformers.SegGptImageProcessor.post_process_semantic_segmentation]]

```python
post_process_semantic_segmentation(outputs, target_sizes: list[tuple[int, int]] | None = None, num_labels: int | None = None, return_segmentation_scores: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/seggpt/image_processing_seggpt.py#L256)

**パラメータ:**

outputs (`SegGptImageSegmentationOutput`) : モデルの生出力。

target_sizes (`list[tuple[int, int]]`, *任意*) : 長さが `batch_size` のリストで、各要素は各予測の要求される最終サイズ `(height, width)` に対応します。`None` の場合、予測はリサイズされません。

num_labels (`int`, *optional*) : セグメンテーションタスクにおけるクラス数（背景を除く）。指定された場合、予測マスクのRGB値をクラスインデックスにマッピングするためのパレットが構築されます。前処理で使用された値と一致させる必要があります。

return_segmentation_scores (`bool`, *任意*, デフォルトは `False`) : セグメンテーションマップとともにセグメンテーションスコアを返すかどうか。`True` の場合、返されるリストの各要素は、フィールド `segmentation`（クラス ID、形状 `(height, width)`）と `segmentation_scores`（各パレットカラーへの負の二乗 L2 距離の形状 `(num_labels+1, height, width)`、または `num_labels` が指定されていない場合は `None`）を持つ `SemanticSegmentationPostProcessorOutput` になります。

**戻り値:** `list[torch.Tensor]` または `list[SemanticSegmentationPostProcessorOutput]`

`return_segmentation_scores=False` (デフォルト)の場合、各要素がクラス ID を持つ形状 `(height, width)` のセグメンテーションマップである長さ `batch_size` のリストを返します。`return_segmentation_scores=True` の場合、フィールド `segmentation` (クラス ID、形状 `(height, width)`) と `segmentation_scores` (形状 `(num_labels+1, height, width)`) を持つ `SemanticSegmentationPostProcessorOutput` のリストを返します。どちらの場合も、`(height, width)` はターゲットサイズ (`target_sizes` が指定されている場合) に対応します。

`SegGptImageSegmentationOutput`の出力をセグメンテーションマップに変換します。PyTorchのみサポートしています。

## SegGptImageProcessorPil[[transformers.SegGptImageProcessorPil]]

#### transformers.SegGptImageProcessorPil[[transformers.SegGptImageProcessorPil]]

```python
transformers.SegGptImageProcessorPil(**kwargs: *<class 'transformers.models.seggpt.image_processing_pil_seggpt.SegGptImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/seggpt/image_processing_pil_seggpt.py#L75)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *任意*, デフォルトは `True`) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルト値は`{'height' : 448, 'width': 448}`): モデルへの最大入力次元を説明します。

default_to_square (`bool`, *kwargs*, *任意*、デフォルトは `True`) : size が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルトは `3`) : 画像をリサイズする場合に使用するリサンプリングフィルター。`PILImageResampling` の列挙型のいずれかになります。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.485, 0.456, 0.406]`) : 正規化に使用する画像の平均値です。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.229, 0.224, 0.225]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

num_labels (`int`, *kwargs*, *optional*) : セグメンテーションタスクにおけるクラス数（背景を除く）。指定された場合、class_idx 0 が背景であると仮定して、プレーンなセグメンテーションマップからプロンプトマスクを3チャネルのRGB画像へマッピングするためのパレットが構築されます。これを指定しない場合、`do_convert_rgb` が `True` のとき、プロンプトマスクはチャネル次元に沿って複製されます。

SegGptImageProcessor イメージプロセッサを構築します。

#### preprocess[[transformers.SegGptImageProcessorPil.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, prompt_images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, prompt_masks: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.models.seggpt.image_processing_pil_seggpt.SegGptImageProcessorKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/seggpt/image_processing_pil_seggpt.py#L136)

**パラメータ:**

images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]`, *任意*) : 前処理を行う画像。ピクセル値が 0 から 255 の範囲にある単一の画像またはバッチの画像を想定しています。ピクセル値が 0 から 1 の範囲にある画像を渡す場合は、`do_rescale=False` を設定してください。

prompt_images (`ImageInput`, *任意*) : 前処理するプロンプト画像。ピクセル値が0から255の範囲にある単一の画像またはバッチの画像を期待します。

prompt_masks (`ImageInput`, *任意*) : 前処理を行うプロンプトマスク。セグメンテーションマップ（チャネルなし）またはRGB画像の形式で指定できます。RGB画像の形式の場合、`do_convert_rgb`は`False`に設定する必要があります。セグメンテーションマップの形式の場合、プロンプトマスクを単一チャネルから3チャネルのRGBへマッピングするためのパレットを構築するために、`num_labels`の指定が推奨されます。`num_labels`が指定されていない場合、プロンプトマスクはチャネル次元に沿って複製されます。

do_convert_rgb (`bool`, *kwargs*, *optional*) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *optional*) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *optional*) : size が int の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*) : 画像をリサイズする場合に使用するリサンプリングフィルタ。`PILImageResampling` の列挙型のいずれかです。`do_resize` が `True` に設定されている場合のみ有効です。

do_rescale (`bool`, *kwargs*, *任意*) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*) : `do_rescale` が `True` に設定されている場合、画像をリサイズするためのリスケール係数。

do_normalize (`bool`, *kwargs*, *optional*) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の平均値。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *任意*) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 画像をパディングするサイズを`{"height": int, "width" int}`で指定します。前処理に提供されたすべての画像サイズより大きい必要があります。`pad_size`が指定されない場合、バッチ内の最大の幅と高さにパディングされます。`do_pad=True.`の場合にのみ適用されます。

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

num_labels (`int`, *kwargs*, *optional*) : セグメンテーションタスクにおけるクラス数（背景を除く）。指定された場合、class_idx 0 が背景であると仮定して、プレーンなセグメンテーションマップからプロンプトマスクを3チャネルのRGB画像へマッピングするためのパレットが構築されます。これを指定しない場合、`do_convert_rgb` が `True` のとき、プロンプトマスクはチャネル次元に沿って複製されます。

**戻り値:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ メソッドによって返されるリスト/配列/テンソルの辞書（'pixel_values' など）。
- **tensor_type** (`Union[None, str, TensorType]`、*省略可*) -- 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

#### post_process_semantic_segmentation[[transformers.SegGptImageProcessorPil.post_process_semantic_segmentation]]

```python
post_process_semantic_segmentation(outputs, target_sizes: list[tuple[int, int]] | None = None, num_labels: int | None = None, return_segmentation_scores: bool = False)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/seggpt/image_processing_pil_seggpt.py#L238)

**パラメータ:**

outputs (`SegGptImageSegmentationOutput`) : モデルの生出力。

target_sizes (`list[tuple[int, int]]`, *任意*) : 長さが `batch_size` のリストで、各要素は各予測の要求される最終サイズ `(height, width)` に対応します。`None` の場合、予測はリサイズされません。

num_labels (`int`, *optional*) : セグメンテーションタスクにおけるクラス数（背景を除く）。指定された場合、予測マスクのRGB値をクラスインデックスにマッピングするためのパレットが構築されます。前処理で使用された値と一致させる必要があります。

return_segmentation_scores (`bool`, *任意*, デフォルトは `False`) : セグメンテーションマップとともにセグメンテーションスコアを返すかどうか。`True` の場合、返されるリストの各要素は、フィールド `segmentation`（クラス ID、形状 `(height, width)`）と `segmentation_scores`（各パレットカラーへの負の二乗 L2 距離の形状 `(num_labels+1, height, width)`、または `num_labels` が指定されていない場合は `None`）を持つ `SemanticSegmentationPostProcessorOutput` になります。

**戻り値:** `list[torch.Tensor]` または `list[SemanticSegmentationPostProcessorOutput]`

`return_segmentation_scores=False` (デフォルト)の場合、各要素がクラス ID を持つ形状 `(height, width)` のセグメンテーションマップである長さ `batch_size` のリストを返します。`return_segmentation_scores=True` の場合、フィールド `segmentation` (クラス ID、形状 `(height, width)`) と `segmentation_scores` (形状 `(num_labels+1, height, width)`) を持つ `SemanticSegmentationPostProcessorOutput` のリストを返します。どちらの場合も、`(height, width)` はターゲットサイズ (`target_sizes` が指定されている場合) に対応します。

`SegGptImageSegmentationOutput`の出力をセグメンテーションマップに変換します。PyTorchのみサポートしています。

## SegGptModel[[transformers.SegGptModel]]

#### transformers.SegGptModel[[transformers.SegGptModel]]

```python
transformers.SegGptModel(config: SegGptConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/seggpt/modeling_seggpt.py#L613)

**パラメータ:**

config ([SegGptConfig](/docs/transformers/v5.23.0/ja/model_doc/seggpt#transformers.SegGptConfig)) : モデルのすべてのパラメータを含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/v5.23.0/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

Seggptのベースモデルで、特定のヘッドを付加せずに生のhidden-statesを出力します。

このモデルは [PreTrainedModel](/docs/transformers/v5.23.0/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.SegGptModel.forward]]

```python
forward(pixel_values: Tensor, prompt_pixel_values: Tensor, prompt_masks: Tensor, bool_masked_pos: typing.Optional[torch.BoolTensor] = None, feature_ensemble: bool | None = None, embedding_type: str | None = None, labels: typing.Optional[torch.Tensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/seggpt/modeling_seggpt.py#L627)

**パラメータ:**

pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソルです。ピクセル値は [SegGptImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/seggpt#transformers.SegGptImageProcessor) を使用して取得できます。詳細は [SegGptImageProcessor.__call__()](/docs/transformers/v5.23.0/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（`processor_class` は画像の処理に [SegGptImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/seggpt#transformers.SegGptImageProcessor) を使用します）。

prompt_pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, height, width)`) : プロンプトのピクセル値。プロンプトのピクセル値は、[AutoImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/auto#transformers.AutoImageProcessor) を使用して取得できます。詳細は [SegGptImageProcessor.__call__()](/docs/transformers/v5.23.0/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください。

prompt_masks (`torch.Tensor`、形状 `(batch_size, num_channels, height, width)`) : プロンプトマスク。[AutoImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/auto#transformers.AutoImageProcessor) を使用してプロンプトマスクを取得できます。詳細は [SegGptImageProcessor.__call__()](/docs/transformers/v5.23.0/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください。

bool_masked_pos (`torch.BoolTensor`、shape `(batch_size, num_patches)`、*optional*) : ブール型のマスク位置。どのパッチがマスクされているか（1）、されていないか（0）を示します。

feature_ensemble (`bool`, *任意*) : 特徴量アンサンブルを使用するかどうかを示すブール値。`True`の場合、プロンプトが少なくとも2つある場合、モデルは特徴量アンサンブルを使用します。`False`の場合、モデルは特徴量アンサンブルを使用しません。この引数は、入力画像に対して複数のプロンプトを用いるフェューショット推論を行う際に考慮すべきです。

embedding_type (`str`, *任意*) : 埋め込みの種類。プロンプトがセマンティック埋め込みかインスタンス埋め込みかを指定します。instance または semantic のいずれかを指定できます。

labels (`torch.Tensor`、形状 `(batch_size, num_channels, height, width)`、`optional`) : 入力画像の正解マスク。

output_attentions (`bool`, *任意*) : すべてのアテンション層のアテンションテンソルを返すかどうか。詳細は、返されるテンソルの `attentions` を参照してください。

output_hidden_states (`bool`, *任意*) : 全レイヤーの hidden states を返すかどうかを指定します。詳細は、返されるテンソルの `hidden_states` を参照してください。

return_dict (`bool`, *任意*) : プレーンなタプルではなく [ModelOutput](/docs/transformers/v5.23.0/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

**戻り値:** `SegGptEncoderOutput` または `tuple(torch.Tensor)`

`SegGptEncoderOutput`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[SegGptConfig](/docs/transformers/v5.23.0/ja/model_doc/seggpt#transformers.SegGptConfig)）や入力に応じて、さまざまな要素で構成されます。

[SegGptModel](/docs/transformers/v5.23.0/ja/model_doc/seggpt#transformers.SegGptModel)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **last_hidden_state** (`torch.Tensor`、形状 `(batch_size, patch_height, patch_width, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **hidden_states** (`tuple[torch.Tensor]`、`optional`、`config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込みの出力用 1 つ + 各層の出力用 1 つ）で、形状は `(batch_size, patch_height, patch_width, hidden_size)` です。
- **attentions** (`tuple[torch.Tensor]`、`optional`、`config.output_attentions=True` の場合に返されます) -- 各レイヤーごとに1つの *torch.Tensor* からなるタプルで、形状は `(batch_size, num_heads, seq_len, seq_len)` です。
- **intermediate_hidden_states** (`tuple[torch.Tensor]`、*optional*、`config.intermediate_hidden_state_indices`が設定されている場合に返されます) -- 形状が`(batch_size, patch_height, patch_width, hidden_size)`の`torch.Tensor`のタプルです。タプルの各要素は、`config.intermediate_hidden_state_indices`で指定された層の出力に対応します。また、各特徴量はLayerNormを通過します。

例:

```python
>>> from transformers import SegGptImageProcessor, SegGptModel
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> image_input_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_2.jpg"
>>> image_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1.jpg"
>>> mask_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1_target.png"

>>> with httpx.stream("GET", image_input_url) as response:
...     image_input = Image.open(BytesIO(response.read()))

>>> with httpx.stream("GET", image_prompt_url) as response:
...     image_prompt = Image.open(BytesIO(response.read()))

>>> with httpx.stream("GET", mask_prompt_url) as response:
...     mask_prompt = Image.open(BytesIO(response.read())).convert("L")

>>> checkpoint = "BAAI/seggpt-vit-large"
>>> model = SegGptModel.from_pretrained(checkpoint)
>>> image_processor = SegGptImageProcessor.from_pretrained(checkpoint)

>>> inputs = image_processor(images=image_input, prompt_images=image_prompt, prompt_masks=mask_prompt, return_tensors="pt")

>>> outputs = model(**inputs)
>>> list(outputs.last_hidden_state.shape)
[1, 56, 28, 1024]
```

## SegGptForImageSegmentation[[transformers.SegGptForImageSegmentation]]

#### transformers.SegGptForImageSegmentation[[transformers.SegGptForImageSegmentation]]

```python
transformers.SegGptForImageSegmentation(config: SegGptConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/seggpt/modeling_seggpt.py#L819)

**パラメータ:**

config ([SegGptConfig](/docs/transformers/v5.23.0/ja/model_doc/seggpt#transformers.SegGptConfig)) : モデルのすべてのパラメータを含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/v5.23.0/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

ワンショット画像セグメンテーションのために、デコーダーを上に配置したSegGptモデル。

このモデルは [PreTrainedModel](/docs/transformers/v5.23.0/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.SegGptForImageSegmentation.forward]]

```python
forward(pixel_values: Tensor, prompt_pixel_values: Tensor, prompt_masks: Tensor, bool_masked_pos: typing.Optional[torch.BoolTensor] = None, feature_ensemble: bool | None = None, embedding_type: str | None = None, labels: typing.Optional[torch.Tensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/seggpt/modeling_seggpt.py#L830)

**パラメータ:**

pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソルです。ピクセル値は [SegGptImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/seggpt#transformers.SegGptImageProcessor) を使用して取得できます。詳細は [SegGptImageProcessor.__call__()](/docs/transformers/v5.23.0/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください（`processor_class` は画像の処理に [SegGptImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/seggpt#transformers.SegGptImageProcessor) を使用します）。

prompt_pixel_values (`torch.Tensor`、形状 `(batch_size, num_channels, height, width)`) : プロンプトのピクセル値。プロンプトのピクセル値は、[AutoImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/auto#transformers.AutoImageProcessor) を使用して取得できます。詳細は [SegGptImageProcessor.__call__()](/docs/transformers/v5.23.0/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください。

prompt_masks (`torch.Tensor`、形状 `(batch_size, num_channels, height, width)`) : プロンプトマスク。[AutoImageProcessor](/docs/transformers/v5.23.0/ja/model_doc/auto#transformers.AutoImageProcessor) を使用してプロンプトマスクを取得できます。詳細は [SegGptImageProcessor.__call__()](/docs/transformers/v5.23.0/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) を参照してください。

bool_masked_pos (`torch.BoolTensor`、shape `(batch_size, num_patches)`、*optional*) : ブール型のマスク位置。どのパッチがマスクされているか（1）、されていないか（0）を示します。

feature_ensemble (`bool`, *任意*) : 特徴量アンサンブルを使用するかどうかを示すブール値。`True`の場合、プロンプトが少なくとも2つある場合、モデルは特徴量アンサンブルを使用します。`False`の場合、モデルは特徴量アンサンブルを使用しません。この引数は、入力画像に対して複数のプロンプトを用いるフェューショット推論を行う際に考慮すべきです。

embedding_type (`str`, *任意*) : 埋め込みの種類。プロンプトがセマンティック埋め込みかインスタンス埋め込みかを指定します。instance または semantic のいずれかを指定できます。

labels (`torch.Tensor`、形状 `(batch_size, num_channels, height, width)`、`optional`) : 入力画像の正解マスク。

output_attentions (`bool`, *任意*) : すべてのアテンション層のアテンションテンソルを返すかどうか。詳細は、返されるテンソルの `attentions` を参照してください。

output_hidden_states (`bool`, *任意*) : 全レイヤーの hidden states を返すかどうかを指定します。詳細は、返されるテンソルの `hidden_states` を参照してください。

return_dict (`bool`, *任意*) : プレーンなタプルではなく [ModelOutput](/docs/transformers/v5.23.0/ja/main_classes/output#transformers.utils.ModelOutput) を返すかどうか。

**戻り値:** `SegGptImageSegmentationOutput` または `tuple(torch.Tensor)`

`SegGptImageSegmentationOutput`、または`torch.Tensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。構成要素は、設定（[SegGptConfig](/docs/transformers/v5.23.0/ja/model_doc/seggpt#transformers.SegGptConfig)）と入力に応じて異なります。

[SegGptForImageSegmentation](/docs/transformers/v5.23.0/ja/model_doc/seggpt#transformers.SegGptForImageSegmentation)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **loss** (`torch.Tensor`、*任意*、`labels` が指定された場合に返されます) -- 損失値。
- **pred_masks** (`torch.Tensor`、形状 `(batch_size, num_channels, height, width)`) -- 予測されたマスクです。
- **hidden_states** (`tuple[torch.Tensor]`、`optional`、`config.output_hidden_states=True` の場合に返されます) -- `torch.Tensor` のタプル（埋め込みの出力用 1 つ + 各層の出力用 1 つ）で、形状は `(batch_size, patch_height, patch_width, hidden_size)` です。
- **attentions** (`tuple[torch.Tensor]`、`optional`、`config.output_attentions=True` の場合に返されます) -- 各層に対応する `torch.Tensor` のタプルで、形状は `(batch_size, num_heads, seq_len, seq_len)` です。

例:

```python
>>> from transformers import SegGptImageProcessor, SegGptForImageSegmentation
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> image_input_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_2.jpg"
>>> image_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1.jpg"
>>> mask_prompt_url = "https://raw.githubusercontent.com/baaivision/Painter/main/SegGPT/SegGPT_inference/examples/hmbb_1_target.png"

>>> with httpx.stream("GET", image_input_url) as response:
...     image_input = Image.open(BytesIO(response.read()))

>>> with httpx.stream("GET", image_prompt_url) as response:
...     image_prompt = Image.open(BytesIO(response.read()))

>>> with httpx.stream("GET", mask_prompt_url) as response:
...     mask_prompt = Image.open(BytesIO(response.read())).convert("L")

>>> checkpoint = "BAAI/seggpt-vit-large"
>>> model = SegGptForImageSegmentation.from_pretrained(checkpoint)
>>> image_processor = SegGptImageProcessor.from_pretrained(checkpoint)

>>> inputs = image_processor(images=image_input, prompt_images=image_prompt, prompt_masks=mask_prompt, return_tensors="pt")
>>> outputs = model(**inputs)
>>> result = image_processor.post_process_semantic_segmentation(outputs, target_sizes=[(image_input.height, image_input.width)])[0]
>>> print(list(result.shape))
[170, 297]
```

