# OneFormer

## 개요

OneFormer 모델은 Jitesh Jain, Jiachen Li, MangTik Chiu, Ali Hassani, Nikita Orlov, Humphrey Shi가 발표한 [OneFormer: One Transformer to Rule Universal Image Segmentation](https://huggingface.co/papers/2211.06220)에서 제안되었습니다. OneFormer는 단일 panoptic 데이터셋으로 학습하여 semantic, instance, panoptic segmentation 작업을 수행할 수 있는 범용 이미지 분할 프레임워크입니다. OneFormer는 작업 토큰을 사용하여 모델이 현재 초점을 맞춘 작업에 조건부화되도록 하며, 이를 통해 학습 시에는 작업 기반(task-guided) 아키텍처를, 추론 시에는 작업 동적(task-dynamic) 동작을 구현합니다.

해당 논문의 초록은 다음과 같습니다:

*Universal Image Segmentation은 새로운 개념이 아닙니다. 지난 수십 년간 이미지 분할을 통합하려는 시도로는 scene parsing, panoptic segmentation, 그리고 최근에는 새로운 panoptic architectures가 있습니다. 그러나 이러한 panoptic architectures는 최고의 성능을 달성하기 위해 semantic, instance, 또는 panoptic segmentation 각각에 대해 개별적으로 학습되어야 하므로 이미지 분할을 진정한 의미에서 통합하지는 못합니다. 이상적으로, 진정한 범용 프레임워크는 한 번만 학습되어 세 가지 이미지 분할 작업 모두에서 SOTA 성능을 달성해야 합니다. 이를 위해, 우리는 multi-task train-once 설계로 분할을 통합하는 범용 이미지 분할 프레임워크인 OneFormer를 제안합니다. 먼저, 단일 multi-task 학습 프로세스 내에서 각 도메인(semantic, instance, panoptic segmentation)의 ground truth를 사용하여 학습할 수 있도록 하는 task-conditioned joint training 전략을 제안합니다. 두 번째로, 현재 작업에 따라 모델을 조건부화하기 위해 task token을 도입하여, 모델이 multi-task 학습과 추론을 지원하는 task-dynamic 특성을 갖도록 합니다. 세 번째로, 학습 중에 query-text contrastive loss를 사용하여 작업 간 및 클래스 간 구분을 더 잘 확립하는 것을 제안합니다. 주목할 점은, OneFormer 단일 모델이 ADE20k, CityScapes, COCO에서 세 가지 분할 작업 모두에서, 각 세 가지 작업을 개별적으로 3배의 리소스를 사용하여 학습된 전문화된 Mask2Former 모델보다 우수한 성능을 보인다는 것입니다. 새로운 ConvNeXt와 DiNAT backbones을 사용하면 성능이 더욱 향상되는 것을 관찰할 수 있습니다. 우리는 OneFormer가 이미지 분할을 더 범용적이고 접근 가능하게 만드는 데 있어 중요한 단계라고 믿습니다.*

아래 그림은 OneFormer의 아키텍처를 보여줍니다. [원본 논문](https://huggingface.co/papers/2211.06220)에서 가져왔습니다.

이 모델은 [Jitesh Jain](https://huggingface.co/praeclarumjj3)이 기여했습니다. 원본 코드는 [여기](https://github.com/SHI-Labs/OneFormer)에서 찾을 수 있습니다.

## 사용 팁

- OneFormer는 추론 시 두 가지 입력이 필요합니다: *image*와 *task token*.
- OneFormer는 학습 중에 panoptic 어노테이션만 사용합니다.
- 모델을 여러 노드에 걸친 분산 환경에서 학습하려면, `modeling_oneformer.py`의 `OneFormerLoss` 클래스 안의 `get_num_masks` 함수를 업데이트해야 합니다. 여러 노드에서 학습하는 경우, [여기](https://github.com/SHI-Labs/OneFormer/blob/33ebb56ed34f970a30ae103e786c0cb64c653d9a/oneformer/modeling/criterion.py#L287)에서 볼 수 있듯이 원래 구현과 같이 모든 노드에 걸친 대상 마스크의 평균 개수로 설정해야 합니다.
- [OneFormerProcessor](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerProcessor)를 사용하여 모델의 입력 이미지와 작업 입력, 그리고 선택적 모델 타겟을 준비할 수 있습니다. [OneFormerProcessor](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerProcessor)는 [OneFormerImageProcessor](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerImageProcessor)와 [CLIPTokenizer](/docs/transformers/main/ko/model_doc/clip#transformers.CLIPTokenizer)를 단일 인스턴스로 묶어 이미지를 준비하고 작업 입력을 인코딩합니다.
- 작업에 따라 `post_process_semantic_segmentation()` 또는 [post_process_instance_segmentation()](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerImageProcessor.post_process_instance_segmentation) 또는 [post_process_panoptic_segmentation()](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerImageProcessor.post_process_panoptic_segmentation)를 호출하여 최종 분할 결과를 얻을 수 있습니다. 세 가지 작업 모두 [OneFormerForUniversalSegmentation](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerForUniversalSegmentation)의 출력으로 해결할 수 있으며, panoptic segmentation은 대상 객체(예: 하늘)의 인스턴스를 병합하기 위한 선택적 `label_ids_to_fuse` 인수를 지원합니다.

## 리소스

OneFormer를 시작하는 데 도움이 되는 공식 Hugging Face 및 커뮤니티(🌎로 표시) 리소스 목록입니다.

- 커스텀 데이터에 대한 추론 + 파인튜닝에 관한 데모 노트북은 [여기](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/OneFormer)에서 찾을 수 있습니다.

여기에 포함할 리소스를 제출하고 싶으시다면, Pull Request를 열어 주시면 검토하겠습니다. 기존 리소스와 중복되는 것이 아니라 새로운 것을 보여주는 것이 이상적입니다.

## OneFormer 전용 출력[[transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput]]

#### transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput[[transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput]]

```python
transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput(encoder_hidden_states: tuple[torch.Tensor] | None = None, pixel_decoder_hidden_states: tuple[torch.Tensor] | None = None, transformer_decoder_hidden_states: typing.Optional[torch.Tensor] = None, transformer_decoder_object_queries: typing.Optional[torch.Tensor] = None, transformer_decoder_contrastive_queries: typing.Optional[torch.Tensor] = None, transformer_decoder_mask_predictions: typing.Optional[torch.Tensor] = None, transformer_decoder_class_predictions: typing.Optional[torch.Tensor] = None, transformer_decoder_auxiliary_predictions: tuple[dict[str, torch.Tensor]] | None = None, text_queries: typing.Optional[torch.Tensor] = None, task_token: typing.Optional[torch.Tensor] = None, attentions: tuple[torch.Tensor] | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/modeling_oneformer.py#L829)

**매개변수:**

encoder_hidden_states (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되거나 `config.output_hidden_states=True`인 경우 반환됨) : `torch.Tensor`의 튜플 (임베딩의 출력 하나 + 각 단계의 출력 하나)로, 모양은 `(batch_size, num_channels, height, width)`입니다. 각 단계의 출력에서 인코더 모델의 히든 스테이트(피처 맵이라고도 함).

pixel_decoder_hidden_states (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되거나 `config.output_hidden_states=True`인 경우 반환됨) : `torch.Tensor`의 튜플 (임베딩의 출력 하나 + 각 단계의 출력 하나)로, 모양은 `(batch_size, num_channels, height, width)`입니다. 각 단계의 출력에서 픽셀 디코더 모델의 히든 스테이트(피처 맵이라고도 함).

transformer_decoder_hidden_states (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되거나 `config.output_hidden_states=True`인 경우 반환됨) : `torch.Tensor`의 튜플 (임베딩의 출력 하나 + 각 단계의 출력 하나)로, 모양은 `(batch_size, sequence_length, hidden_size)`입니다. 각 단계의 출력에서 transformer 디코더의 hidden-states(또는 feature maps이라고도 함).

transformer_decoder_object_queries (`torch.Tensor`, shape `(batch_size, num_queries, hidden_dim)`) : transformer decoder의 마지막 레이어에서 출력된 object queries.

transformer_decoder_contrastive_queries (`torch.Tensor`, shape `(batch_size, num_queries, hidden_dim)`) : Transformer decoder에서 생성된 대조적 쿼리.

transformer_decoder_mask_predictions (`torch.Tensor`, shape `(batch_size, num_queries, height, width)`) : Transformer decoder의 마지막 레이어에서 생성된 마스크 예측 값.

transformer_decoder_class_predictions (`torch.Tensor`, shape `(batch_size, num_queries, num_classes+1)`) : transformer decoder의 마지막 레이어에서 생성된 클래스 예측 값.

transformer_decoder_auxiliary_predictions (`Tuple` of `str, torch.Tensor`의 Dict, *선택 사항*) : transformer decoder의 각 레이어에서 생성된 클래스 및 마스크 예측의 Tuple.

text_queries (`torch.Tensor`, *선택 사항*, shape `(batch_size, num_queries, hidden_dim)`) : 학습 중 대조적 손실을 계산하는 데 사용되는 입력 텍스트 목록에서 파생된 텍스트 쿼리.

task_token (`torch.Tensor`, shape `(batch_size, hidden_dim)`) : 쿼리를 조건화하기 위한 1D 태스크 토큰.

attentions (`tuple(tuple(torch.Tensor))`, *선택*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`인 경우 반환됨) : `tuple(torch.Tensor)`의 튜플(레이어당 하나)로, 모양은 `(batch_size, num_heads, sequence_length, sequence_length)`입니다. Transformer 디코더의 Self 및 Cross Attention 가중치입니다.

[OneFormerModel](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerModel)의 출력을 위한 클래스입니다. 이 클래스는 logits를 계산하는 데 필요한 모든 hidden states를 반환합니다.

#### transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput[[transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput]]

```python
transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput(loss: typing.Optional[torch.Tensor] = None, class_queries_logits: typing.Optional[torch.Tensor] = None, masks_queries_logits: typing.Optional[torch.Tensor] = None, auxiliary_predictions: list = None, encoder_hidden_states: tuple[torch.Tensor] | None = None, pixel_decoder_hidden_states: list[torch.Tensor] | None = None, transformer_decoder_hidden_states: typing.Optional[torch.Tensor] = None, transformer_decoder_object_queries: typing.Optional[torch.Tensor] = None, transformer_decoder_contrastive_queries: typing.Optional[torch.Tensor] = None, transformer_decoder_mask_predictions: typing.Optional[torch.Tensor] = None, transformer_decoder_class_predictions: typing.Optional[torch.Tensor] = None, transformer_decoder_auxiliary_predictions: list[dict[str, torch.Tensor]] | None = None, text_queries: typing.Optional[torch.Tensor] = None, task_token: typing.Optional[torch.Tensor] = None, attentions: tuple[tuple[torch.Tensor]] | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/modeling_oneformer.py#L886)

**매개변수:**

loss (`torch.Tensor`, *선택 사항*) : 라벨이 존재할 때 반환되는 계산된 손실입니다.

class_queries_logits (`torch.Tensor`, *선택 사항*) : 각 쿼리에 대해 제안된 클래스를 나타내는 `(batch_size, num_queries, num_labels + 1)` 모양의 텐서입니다. `+ 1`은 null 클래스를 포함해야 하므로 필요합니다.

masks_queries_logits (`torch.Tensor`, *선택 사항*) : 각 쿼리에 대한 제안된 마스크를 나타내는 `(batch_size, num_queries, height, width)` 모양의 텐서.

auxiliary_predictions (`List` of Dict of `str, torch.Tensor`, *선택 사항*) : transformer decoder의 각 레이어에서 생성된 클래스 및 마스크 예측 값 목록.

encoder_hidden_states (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되거나 `config.output_hidden_states=True`인 경우 반환됨) : `torch.Tensor`의 튜플 (임베딩의 출력 하나 + 각 단계의 출력 하나)로, 모양은 `(batch_size, num_channels, height, width)`입니다. 각 단계의 출력에서 인코더 모델의 히든 스테이트(피처 맵이라고도 함).

pixel_decoder_hidden_states (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되거나 `config.output_hidden_states=True`인 경우 반환됨) : `torch.Tensor`의 튜플 (임베딩의 출력 하나 + 각 단계의 출력 하나)로, 모양은 `(batch_size, num_channels, height, width)`입니다. 각 단계의 출력에서 픽셀 디코더 모델의 히든 스테이트(피처 맵이라고도 함).

transformer_decoder_hidden_states (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되거나 `config.output_hidden_states=True`인 경우 반환됨) : `torch.Tensor`의 튜플 (임베딩의 출력 하나 + 각 단계의 출력 하나)로, 모양은 `(batch_size, sequence_length, hidden_size)`입니다. 각 단계의 출력에서 transformer 디코더의 hidden-states(또는 feature maps이라고도 함).

transformer_decoder_object_queries (`torch.Tensor`, shape `(batch_size, num_queries, hidden_dim)`) : transformer decoder의 마지막 레이어에서 출력된 object queries.

transformer_decoder_contrastive_queries (`torch.Tensor`, shape `(batch_size, num_queries, hidden_dim)`) : Transformer decoder에서 생성된 대조적 쿼리.

transformer_decoder_mask_predictions (`torch.Tensor`, shape `(batch_size, num_queries, height, width)`) : Transformer decoder의 마지막 레이어에서 생성된 마스크 예측 값.

transformer_decoder_class_predictions (`torch.Tensor`, shape `(batch_size, num_queries, num_classes+1)`) : transformer decoder의 마지막 레이어에서 생성된 클래스 예측 값.

transformer_decoder_auxiliary_predictions (`List` of Dict of `str, torch.Tensor`, *선택 사항*) : transformer decoder의 각 레이어에서 생성된 클래스 및 마스크 예측 값 목록.

text_queries (`torch.Tensor`, *선택 사항*, shape `(batch_size, num_queries, hidden_dim)`) : 학습 중 대조적 손실을 계산하는 데 사용되는 입력 텍스트 목록에서 파생된 텍스트 쿼리.

task_token (`torch.Tensor`, shape `(batch_size, hidden_dim)`) : 쿼리를 조건화하기 위한 1D 태스크 토큰.

attentions (`tuple(tuple(torch.Tensor))`, *선택*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`인 경우 반환됨) : `tuple(torch.Tensor)`의 튜플(레이어당 하나)로, 모양은 `(batch_size, num_heads, sequence_length, sequence_length)`입니다. Transformer 디코더의 Self 및 Cross Attention 가중치입니다.

`OneFormerForUniversalSegmentationOutput`의 출력에 대한 클래스입니다.

이 출력은 작업에 따라 [post_process_semantic_segmentation()](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerImageProcessor.post_process_semantic_segmentation) 또는 [post_process_instance_segmentation()](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerImageProcessor.post_process_instance_segmentation) 또는 [post_process_panoptic_segmentation()](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerImageProcessor.post_process_panoptic_segmentation)에 직접 전달할 수 있습니다. 사용법에 대한 자세한 내용은 [`~OneFormerImageProcessor]를 참고하세요.

## OneFormerConfig[[transformers.OneFormerConfig]]

#### transformers.OneFormerConfig[[transformers.OneFormerConfig]]

```python
transformers.OneFormerConfig(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, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, ignore_value: int = 255, num_queries: int = 150, no_object_weight: float = 0.1, class_weight: float = 2.0, mask_weight: float = 5.0, dice_weight: float = 5.0, contrastive_weight: float = 0.5, contrastive_temperature: float = 0.07, train_num_points: int = 12544, oversample_ratio: float = 3.0, importance_sample_ratio: float = 0.75, init_std: float = 0.02, init_xavier_std: float = 1.0, layer_norm_eps: float = 1e-05, is_training: bool = False, use_auxiliary_loss: bool = True, output_auxiliary_logits: bool = True, strides: list[int] | tuple[int, ...] = (4, 8, 16, 32), task_seq_len: int = 77, text_encoder_width: int = 256, text_encoder_context_length: int = 77, text_encoder_num_layers: int = 6, text_encoder_vocab_size: int = 49408, text_encoder_proj_layers: int = 2, text_encoder_n_ctx: int = 16, conv_dim: int = 256, mask_dim: int = 256, hidden_dim: int = 256, encoder_feedforward_dim: int = 1024, norm: str = 'GN', encoder_layers: int = 6, decoder_layers: int = 10, use_task_norm: bool = True, num_attention_heads: int = 8, dropout: float | int = 0.1, dim_feedforward: int = 2048, pre_norm: bool = False, enforce_input_proj: bool = False, query_dec_layers: int = 2, common_stride: int = 4)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/configuration_oneformer.py#L25)

**매개변수:**

backbone_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`, *선택*) : 백본 모델의 구성입니다.

ignore_value (`int`, *선택 사항*, 기본값 255) : 손실 계산 시 GT label에서 무시할 값.

num_queries (`int`, *선택 사항*, 기본값 150) : 객체 쿼리의 수.

no_object_weight (`float`, *선택 사항*, 기본값 `0.1`) : 객체 감지 손실에서 no-object 클래스의 상대 분류 가중치입니다.

class_weight (`float`, *선택 사항*, 기본값 `2.0`) : 헝가리안 매칭 비용에서 분류 오류의 상대적 가중치입니다.

mask_weight (`float`, *선택 사항*, 기본값 `5.0`) : 파노픽 세분화 손실에서 포칼 손실의 상대적 가중치입니다.

dice_weight (`float`, *선택 사항*, 기본값 `5.0`) : 파노픽 세분화 손실에서 dice loss의 상대적 가중치입니다.

contrastive_weight (`float`, *선택 사항*, 기본값 0.5) : 대조적 손실(contrastive loss)의 가중치.

contrastive_temperature (`float`, *선택 사항*, 기본값 0.07) : 대조적 로짓을 스케일링하기 위한 초기 값입니다.

train_num_points (`int`, *선택 사항*, 기본값 12544) : 마스크 예측에 대한 손실을 계산할 때 샘플링할 포인트의 수.

oversample_ratio (`float`, *선택 사항*, 기본값 3.0) : 오버샘플링할 포인트 수를 결정하는 비율입니다.

importance_sample_ratio (`float`, *선택 사항*, 기본값 0.75) : 중요도 샘플링을 통해 샘플링되는 포인트의 비율입니다.

init_std (`float`, *선택 사항*, 기본값 `0.02`) : 모든 가중치 행렬을 초기화하는 truncated_normal_initializer의 표준 편차입니다.

init_xavier_std (`float`, *선택 사항*, 기본값 `1.0`) : cross-attention 가중치의 Xavier 초기화에 사용되는 스케일링 계수입니다.

layer_norm_eps (`float`, *선택 사항*, 기본값 `1e-05`) : layer normalization 레이어에서 사용되는 epsilon 값입니다.

is_training (`bool`, *선택 사항*, 기본값 `False`) : 학습 모드 또는 추론 모드 중 어느 모드로 실행할지 여부.

use_auxiliary_loss (`bool`, *선택 사항*, 기본값 `True`) : Transformer decoder의 중간 예측을 사용하여 손실을 계산할지 여부.

output_auxiliary_logits (`bool`, *선택 사항*, 기본값 `True`) : transformer decoder의 중간 예측을 반환할지 여부.

strides (`list`, *선택 사항*, 기본값 `[4, 8, 16, 32]`) : 인코더의 feature map에 사용할 strides를 포함하는 리스트.

task_seq_len (`int`, *선택 사항*, 기본값 77) : 텍스트 목록 입력을 토큰화할 때 사용할 시퀀스 길이입니다.

text_encoder_width (`int`, *선택 사항*, 기본값 256) : 텍스트 인코더의 숨겨진 크기(hidden size)입니다.

text_encoder_context_length (`int`, *선택 사항*, 기본값 77) : 텍스트 인코더의 입력 시퀀스 길이입니다.

text_encoder_num_layers (`int`, *선택 사항*, 기본값 6) : 텍스트 인코더의 transformer 레이어 수.

text_encoder_vocab_size (`int`, *선택 사항*, 기본값 49408) : 토크나이저의 어휘 크기입니다.

text_encoder_proj_layers (`int`, *선택 사항*, 기본값 2) : 텍스트 쿼리를 투영하기 위한 MLP의 레이어 수.

text_encoder_n_ctx (`int`, *선택 사항*, 기본값 16) : 학습 가능한 텍스트 컨텍스트 쿼리의 수.

conv_dim (`int`, *선택 사항*, 기본값 256) : 백본의 출력을 매핑할 특징 맵 차원.

mask_dim (`int`, *선택 사항*, 기본값 256) : 픽셀 디코더의 피처 맵 차원.

hidden_dim (`int`, *선택 사항*, 기본값 256) : transformer decoder의 hidden states 차원.

encoder_feedforward_dim (`int`, *선택 사항*, 기본값 1024) : 픽셀 디코더의 FFN 레이어 차원.

norm (`str`, *선택 사항*, 기본값 `"GN"`) : 정규화 유형.

encoder_layers (`int`, *선택 사항*, 기본값 `6`) : Transformer 인코더의 숨겨진 레이어 수. 설정되지 않으면 `num_layers`와 동일한 값을 사용합니다.

decoder_layers (`int`, *선택 사항*, 기본값 `10`) : Transformer 디코더의 숨겨진 레이어 수. 설정되지 않으면 `num_layers`와 동일한 값을 사용합니다.

use_task_norm (`bool`, *선택 사항*, 기본값 `True`) : 태스크 토큰을 정규화할지 여부.

num_attention_heads (`int`, *선택 사항*, 기본값 `8`) : Transformer decoder의 각 attention layer에 사용할 attention head의 수입니다.

dropout (`Union[float, int]`, *선택 사항*, 기본값 `0.1`) : 모든 dropout 레이어의 비율입니다.

dim_feedforward (`int`, *선택 사항*, 기본값 2048) : transformer decoder의 FFN 레이어 차원.

pre_norm (`bool`, *선택 사항*, 기본값 `False`) : Transformer decoder에서 attention 레이어 전에 hidden states를 정규화할지 여부.

enforce_input_proj (`bool`, *선택 사항*, 기본값 `False`) : transformer decoder에서 hidden states를 투영할지 여부.

query_dec_layers (`int`, *선택 사항*, 기본값 2) : query transformer의 레이어 수.

common_stride (`int`, *선택 사항*, 기본값 4) : 픽셀 디코더의 특징에 사용되는 공통 스트라이드입니다.

이것은 OneFormerModel의 구성을 저장하기 위한 구성 클래스입니다. 지정된 인자에 따라 Oneformer 모델을 인스턴스화하여 모델 아키텍처를 정의하는 데 사용됩니다. 기본값으로 구성을 인스턴스화하면 [shi-labs/oneformer_ade20k_swin_tiny](https://huggingface.co/shi-labs/oneformer_ade20k_swin_tiny)와 유사한 구성이 생성됩니다.

Configuration 객체는 [PreTrainedConfig](/docs/transformers/main/ko/main_classes/configuration#transformers.PreTrainedConfig)를 상속하며, 모델 출력을 제어하는 데 사용할 수 있습니다. 자세한 내용은 [PreTrainedConfig](/docs/transformers/main/ko/main_classes/configuration#transformers.PreTrainedConfig)의 문서를 참고하세요.

예:
```python
>>> from transformers import OneFormerConfig, OneFormerModel

>>> # Initializing a OneFormer shi-labs/oneformer_ade20k_swin_tiny configuration
>>> configuration = OneFormerConfig()
>>> # Initializing a model (with random weights) from the shi-labs/oneformer_ade20k_swin_tiny style configuration
>>> model = OneFormerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```

## OneFormerImageProcessor[[transformers.OneFormerImageProcessor]]

#### transformers.OneFormerImageProcessor[[transformers.OneFormerImageProcessor]]

```python
transformers.OneFormerImageProcessor(**kwargs: *<class 'transformers.models.oneformer.image_processing_oneformer.OneFormerImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_oneformer.py#L275)

**매개변수:**

do_convert_rgb (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 RGB로 변환할지 여부.

do_resize (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 리사이즈할지 여부.

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, 기본값 `{'shortest_edge' : 800, 'longest_edge': 1333}`): 모델에 입력되는 최대 차원을 설명합니다.

default_to_square (`bool`, *kwargs*, *선택 사항*, 기본값 `False`) : 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*, 기본값 `2`) : 이미지를 리사이즈할 때 사용할 리샘플링 필터입니다. 이는 `PILImageResampling` enum 중 하나일 수 있습니다. `do_resize`가 `True`로 설정된 경우에만 효과가 있습니다.

do_rescale (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 다시 스케일링할지 여부.

rescale_factor (`float`, *kwargs*, *선택 사항*, 기본값 `0.00392156862745098`) : `do_rescale`이 `True`로 설정된 경우 이미지를 재조정하는 데 사용되는 재조정 계수입니다.

do_normalize (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 정규화할지 여부.

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택 사항*, 기본값은 `[0.485, 0.456, 0.406]`) : 정규화에 사용할 이미지 평균입니다. `do_normalize`가 `True`로 설정된 경우에만 효과가 있습니다.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택 사항*, 기본값은 `[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*, *선택*) : 이미지를 중앙 크롭할지 여부.

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : `ChannelDimension.FIRST`만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.

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*, *선택*) : 이미지의 크기에 따른 그룹화를 비활성화하여 이미지를 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.

image_seq_length (`int`, *kwargs*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

repo_path (`str`, *kwargs*, *선택 사항*, 기본값은 `shi-labs/oneformer_demo`) : 모델 메타데이터를 포함하는 로컬 디렉터리 또는 HuggingFace Hub 저장소의 경로.

class_info_file (`str`, *kwargs*, *선택*) : 클래스 메타데이터를 포함하는 저장소 내 JSON 파일의 경로.

num_text (`int`, *kwargs*, *선택*) : 텍스트 인코더의 텍스트 쿼리 수로, 태스크 유도 프롬프트로 사용됩니다.

num_labels (`int`, *kwargs*, *선택 사항*) : 분할을 위한 의미론적 클래스의 수로, 출력 레이어의 크기를 결정합니다.

ignore_index (`int`, *kwargs*, *선택*) : 세그멘테이션 맵에서 무시할 레이블로, 패딩에 자주 사용됩니다.

do_reduce_labels (`bool`, *kwargs*, *선택 사항*, 기본값 `False`) : 모든 라벨 값을 1만큼 감소시켜 배경 클래스를 `ignore_index`로 매핑할지 여부.

OneFormerImageProcessor 이미지 프로세서를 생성합니다.

#### preprocess[[transformers.OneFormerImageProcessor.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']], task_inputs: list[str] | None = None, segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None, **kwargs: *<class 'transformers.models.oneformer.image_processing_oneformer.OneFormerImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_oneformer.py#L300)

**매개변수:**

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`로 설정하세요.

task_inputs (`list[str]`, *선택 사항*) : 배치의 각 이미지에 대한 작업 목록(`"panoptic"`, `"instance"`, `"semantic"`).

segmentation_maps (`ImageInput`, *선택 사항*) : 세그멘테이션 맵입니다.

instance_id_to_semantic_id (`Union[list[dict[int, int]], dict[int, int]]`, *선택*) : 인스턴스 ID에서 의미론적 ID로 매핑하는 딕셔너리.

do_convert_rgb (`bool`, *kwargs*, *선택*) : 이미지를 RGB로 변환할지 여부.

do_resize (`bool`, *kwargs*, *선택*) : 이미지를 리사이즈할지 여부.

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 모델의 최대 입력 차원을 설명합니다.

default_to_square (`bool`, *kwargs*, *선택*) : 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` enum 중 하나를 사용할 수 있습니다. `do_resize`가 `True`로 설정된 경우에만 효과가 있습니다.

do_rescale (`bool`, *kwargs*, *선택*) : 이미지를 다시 스케일링할지 여부.

rescale_factor (`float`, *kwargs*, *선택*) : `do_rescale`가 `True`로 설정된 경우 이미지를 재조정하는 데 사용되는 재조정 계수입니다.

do_normalize (`bool`, *kwargs*, *선택*) : 이미지를 정규화할지 여부.

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*) : 정규화에 사용할 이미지 평균값. `do_normalize`이 `True`로 설정된 경우에만 효과가 있습니다.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*) : 정규화에 사용할 이미지 표준 편차. `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*, *선택*) : 이미지를 중앙 크롭할지 여부.

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : `ChannelDimension.FIRST`만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.

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*, *선택*) : 이미지의 크기에 따른 그룹화를 비활성화하여 이미지를 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.

image_seq_length (`int`, *kwargs*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

repo_path (`str`, *kwargs*, *선택 사항*, 기본값은 `shi-labs/oneformer_demo`) : 모델 메타데이터를 포함하는 로컬 디렉터리 또는 HuggingFace Hub 저장소의 경로.

class_info_file (`str`, *kwargs*, *선택*) : 클래스 메타데이터를 포함하는 저장소 내 JSON 파일의 경로.

num_text (`int`, *kwargs*, *선택*) : 텍스트 인코더의 텍스트 쿼리 수로, 태스크 유도 프롬프트로 사용됩니다.

num_labels (`int`, *kwargs*, *선택 사항*) : 분할을 위한 의미론적 클래스의 수로, 출력 레이어의 크기를 결정합니다.

ignore_index (`int`, *kwargs*, *선택*) : 세그멘테이션 맵에서 무시할 레이블로, 패딩에 자주 사용됩니다.

do_reduce_labels (`bool`, *kwargs*, *선택 사항*, 기본값 `False`) : 모든 라벨 값을 1만큼 감소시켜 배경 클래스를 `ignore_index`로 매핑할지 여부.

**반환값:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ 메서드가 반환하는 리스트/배열/텐서 딕셔너리('pixel_values' 등).
- **tensor_type** (`Union[None, str, TensorType]`, *선택 사항*) -- 초기화 시 PyTorch/Numpy 텐서에서 정수 목록을 변환하려면 여기에 tensor_type을 지정할 수 있습니다.

#### post_process_semantic_segmentation[[transformers.OneFormerImageProcessor.post_process_semantic_segmentation]]

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

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_oneformer.py#L690)

**매개변수:**

outputs ([OneFormerForUniversalSegmentation](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerForUniversalSegmentation)) : 모델의 원시 출력.

target_sizes (`list[tuple[int, int]]`, *선택 사항*) : (batch_size) 길이의 리스트로, 각 리스트 항목(`Tuple[int, int]]`)은 각 예측의 요청된 최종 크기(높이, 너비)에 해당합니다. None으로 두면 예측 결과가 리사이즈되지 않습니다.

return_segmentation_scores (`bool`, *선택 사항*, 기본값 `False`) : 분할 맵과 함께 분할 점수를 반환할지 여부입니다. `True`인 경우, 반환된 리스트의 각 요소는 `segmentation` 필드(클래스 ID, shape `(height, width)`)와 `segmentation_scores` 필드(shape `(num_classes, height, width)`)를 가진 `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_classes, height, width)` 모양) 필드를 가진 `SemanticSegmentationPostProcessorOutput` 리스트를 반환합니다. 두 경우 모두 `(height, width)`는 대상 크기(`target_sizes`가 지정된 경우)에 해당합니다.

[OneFormerForUniversalSegmentation](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerForUniversalSegmentation)의 출력을 의미 분할 맵으로 변환합니다. PyTorch만 지원합니다.

#### post_process_instance_segmentation[[transformers.OneFormerImageProcessor.post_process_instance_segmentation]]

```python
post_process_instance_segmentation(outputs, task_type: str = 'instance', is_demo: bool = True, threshold: float = 0.5, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, target_sizes: list[tuple[int, int]] | None = None, return_coco_annotation: bool | None = False)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_oneformer.py#L766)

**매개변수:**

outputs (`OneFormerForUniversalSegmentationOutput`) : `OneFormerForUniversalSegmentationOutput`의 출력입니다.

task_type (`str`, *선택 사항*, 기본값 "instance") : 후처리는 태스크 토큰 입력에 따라 달라집니다. `task_type`가 "panoptic"인 경우, stuff 예측을 무시해야 합니다.

is_demo (`bool`, *선택 사항*, 기본값 `True`) : 모델이 데모 모드인지 여부입니다. 참인 경우, 임계값을 사용하여 최종 마스크를 예측합니다.

threshold (`float`, *선택 사항*, 기본값 0.5) : 예측된 인스턴스 마스크를 유지하기 위한 확률 점수 임계값입니다.

mask_threshold (`float`, *선택*, 기본값 0.5) : 예측된 마스크를 이진 값으로 변환할 때 사용할 임계값입니다.

overlap_mask_area_threshold (`float`, *선택 사항*, 기본값 0.8) : 각 바이너리 인스턴스 마스크 내에서 작은 분리된 부분을 병합하거나 제거하기 위한 오버랩 마스크 영역 임계값입니다.

target_sizes (`List[Tuple]`, *선택 사항*) : (batch_size) 길이의 리스트로, 각 리스트 항목(`Tuple[int, int]]`)은 배치 내 각 예측의 요청된 최종 크기(높이, 너비)에 해당합니다. None으로 두면 예측 결과가 리사이즈되지 않습니다.

return_coco_annotation (`bool`, *선택 사항*, 기본값 `False`) : COCO 형식으로 예측 결과를 반환할지 여부.

**반환값:** `List[Dict]`

이미지별로 하나씩 포함된 딕셔너리 목록이며, 각 딕셔너리에는 두 개의 키가 포함됩니다:
- **segmentation** -- 각 픽셀이 `segment_id`를 나타내는 `(height, width)` 형태의 텐서. `threshold`보다 높은 값이 발견되지 않으면 `None`으로 설정됩니다. `target_sizes`가 지정된 경우, segmentation은 해당 `target_sizes` 항목으로 리사이즈됩니다.
- **segments_info** -- 각 세그먼트에 대한 추가 정보를 포함하는 사전입니다.
  - **id** -- `segment_id`를 나타내는 정수입니다.
  - **label_id** -- `segment_id`에 해당하는 라벨/의미론적 클래스 ID를 나타내는 정수입니다.
  - **was_fused** -- `label_id`가 `label_ids_to_fuse`에 포함되어 있으면 `True`, 그렇지 않으면 `False`인 불리언 값. 동일한 클래스/라벨의 여러 인스턴스가 병합되어 단일 `segment_id`가 할당되었습니다.
  - **score** -- `segment_id`를 가진 세그먼트의 예측 점수.

`OneFormerForUniversalSegmentationOutput`의 출력을 이미지 인스턴스 분할 예측으로 변환합니다. PyTorch만 지원합니다.

#### post_process_panoptic_segmentation[[transformers.OneFormerImageProcessor.post_process_panoptic_segmentation]]

```python
post_process_panoptic_segmentation(outputs, threshold: float = 0.5, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, label_ids_to_fuse: set[int] | None = None, target_sizes: list[tuple[int, int]] | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_oneformer.py#L886)

**매개변수:**

outputs (`MaskFormerForInstanceSegmentationOutput`) : [MaskFormerForInstanceSegmentation](/docs/transformers/main/ko/model_doc/maskformer#transformers.MaskFormerForInstanceSegmentation)의 출력입니다.

threshold (`float`, *선택 사항*, 기본값 0.5) : 예측된 인스턴스 마스크를 유지하기 위한 확률 점수 임계값입니다.

mask_threshold (`float`, *선택*, 기본값 0.5) : 예측된 마스크를 이진 값으로 변환할 때 사용할 임계값입니다.

overlap_mask_area_threshold (`float`, *선택 사항*, 기본값 0.8) : 각 바이너리 인스턴스 마스크 내에서 작은 분리된 부분을 병합하거나 제거하기 위한 오버랩 마스크 영역 임계값입니다.

label_ids_to_fuse (`Set[int]`, *선택 사항*) : 이 상태의 라벨은 모든 인스턴스가 하나로 병합됩니다. 예를 들어 이미지에는 하늘이 하나만 있을 수 있지만 여러 명의 사람이 있을 수 있으므로, 하늘의 라벨 ID는 해당 세트에 포함되지만 사람의 라벨 ID는 포함되지 않습니다.

target_sizes (`list[Tuple]`, *선택 사항*) : (batch_size) 길이의 리스트로, 각 리스트 항목(`tuple[int, int]]`)은 배치 내 각 예측의 요청된 최종 크기(높이, 너비)에 해당합니다. None으로 두면 예측 결과가 리사이즈되지 않습니다.

**반환값:** `list[Dict]`

이미지별로 하나씩 포함된 딕셔너리 목록이며, 각 딕셔너리에는 두 개의 키가 포함됩니다:
- **segmentation** -- 각 픽셀이 `segment_id`를 나타내는 `(height, width)` 형태의 텐서. `threshold`보다 높은 값이 발견되지 않으면 `None`으로 설정됩니다. `target_sizes`가 지정된 경우, segmentation은 해당 `target_sizes` 항목으로 리사이즈됩니다.
- **segments_info** -- 각 세그먼트에 대한 추가 정보를 포함하는 사전입니다.
  - **id** -- `segment_id`를 나타내는 정수입니다.
  - **label_id** -- `segment_id`에 해당하는 라벨/의미론적 클래스 ID를 나타내는 정수입니다.
  - **was_fused** -- `label_id`가 `label_ids_to_fuse`에 포함되어 있으면 `True`, 그렇지 않으면 `False`인 불리언 값. 동일한 클래스/라벨의 여러 인스턴스가 병합되어 단일 `segment_id`가 할당되었습니다.
  - **score** -- `segment_id`를 가진 세그먼트의 예측 점수.

`MaskFormerForInstanceSegmentationOutput`의 출력을 이미지 팬옵틱 세분화 예측으로 변환합니다. PyTorch만 지원합니다.

## OneFormerImageProcessorPil[[transformers.OneFormerImageProcessorPil]]

#### transformers.OneFormerImageProcessorPil[[transformers.OneFormerImageProcessorPil]]

```python
transformers.OneFormerImageProcessorPil(**kwargs: *<class 'transformers.models.oneformer.image_processing_pil_oneformer.OneFormerImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_pil_oneformer.py#L293)

**매개변수:**

do_convert_rgb (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 RGB로 변환할지 여부.

do_resize (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 리사이즈할지 여부.

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, 기본값 `{'shortest_edge' : 800, 'longest_edge': 1333}`): 모델에 입력되는 최대 차원을 설명합니다.

default_to_square (`bool`, *kwargs*, *선택 사항*, 기본값 `False`) : 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*, 기본값 `2`) : 이미지를 리사이즈할 때 사용할 리샘플링 필터입니다. 이는 `PILImageResampling` enum 중 하나일 수 있습니다. `do_resize`가 `True`로 설정된 경우에만 효과가 있습니다.

do_rescale (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 다시 스케일링할지 여부.

rescale_factor (`float`, *kwargs*, *선택 사항*, 기본값 `0.00392156862745098`) : `do_rescale`이 `True`로 설정된 경우 이미지를 재조정하는 데 사용되는 재조정 계수입니다.

do_normalize (`bool`, *kwargs*, *선택 사항*, 기본값 `True`) : 이미지를 정규화할지 여부.

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택 사항*, 기본값은 `[0.485, 0.456, 0.406]`) : 정규화에 사용할 이미지 평균입니다. `do_normalize`가 `True`로 설정된 경우에만 효과가 있습니다.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택 사항*, 기본값은 `[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*, *선택*) : 이미지를 중앙 크롭할지 여부.

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : `ChannelDimension.FIRST`만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.

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*, *선택*) : 이미지의 크기에 따른 그룹화를 비활성화하여 이미지를 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.

image_seq_length (`int`, *kwargs*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

repo_path (`str`, *kwargs*, *선택 사항*, 기본값은 `shi-labs/oneformer_demo`) : 모델 메타데이터를 포함하는 로컬 디렉터리 또는 HuggingFace Hub 저장소의 경로.

class_info_file (`str`, *kwargs*, *선택*) : 클래스 메타데이터를 포함하는 저장소 내 JSON 파일의 경로.

num_text (`int`, *kwargs*, *선택*) : 텍스트 인코더의 텍스트 쿼리 수로, 태스크 유도 프롬프트로 사용됩니다.

num_labels (`int`, *kwargs*, *선택 사항*) : 분할을 위한 의미론적 클래스의 수로, 출력 레이어의 크기를 결정합니다.

ignore_index (`int`, *kwargs*, *선택*) : 세그멘테이션 맵에서 무시할 레이블로, 패딩에 자주 사용됩니다.

do_reduce_labels (`bool`, *kwargs*, *선택 사항*, 기본값 `False`) : 모든 라벨 값을 1만큼 감소시켜 배경 클래스를 `ignore_index`로 매핑할지 여부.

OneFormerImageProcessor 이미지 프로세서를 생성합니다.

#### preprocess[[transformers.OneFormerImageProcessorPil.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']], task_inputs: list[str] | None = None, segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None, **kwargs: *<class 'transformers.models.oneformer.image_processing_pil_oneformer.OneFormerImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_pil_oneformer.py#L318)

**매개변수:**

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`로 설정하세요.

task_inputs (`list[str]`, *선택 사항*) : 배치의 각 이미지에 대한 작업 목록(`"panoptic"`, `"instance"`, `"semantic"`).

segmentation_maps (`ImageInput`, *선택 사항*) : 세그멘테이션 맵입니다.

instance_id_to_semantic_id (`Union[list[dict[int, int]], dict[int, int]]`, *선택*) : 인스턴스 ID에서 의미론적 ID로 매핑하는 딕셔너리.

do_convert_rgb (`bool`, *kwargs*, *선택*) : 이미지를 RGB로 변환할지 여부.

do_resize (`bool`, *kwargs*, *선택*) : 이미지를 리사이즈할지 여부.

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 모델의 최대 입력 차원을 설명합니다.

default_to_square (`bool`, *kwargs*, *선택*) : 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` enum 중 하나를 사용할 수 있습니다. `do_resize`가 `True`로 설정된 경우에만 효과가 있습니다.

do_rescale (`bool`, *kwargs*, *선택*) : 이미지를 다시 스케일링할지 여부.

rescale_factor (`float`, *kwargs*, *선택*) : `do_rescale`가 `True`로 설정된 경우 이미지를 재조정하는 데 사용되는 재조정 계수입니다.

do_normalize (`bool`, *kwargs*, *선택*) : 이미지를 정규화할지 여부.

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*) : 정규화에 사용할 이미지 평균값. `do_normalize`이 `True`로 설정된 경우에만 효과가 있습니다.

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *선택*) : 정규화에 사용할 이미지 표준 편차. `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*, *선택*) : 이미지를 중앙 크롭할지 여부.

data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *선택*) : `ChannelDimension.FIRST`만 지원됩니다. 느린 프로세서와의 호환성을 위해 추가되었습니다.

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*, *선택*) : 이미지의 크기에 따른 그룹화를 비활성화하여 이미지를 배치 대신 개별적으로 처리할지 여부입니다. None인 경우, 이미지가 CPU에 있으면 True, 그렇지 않으면 False로 설정됩니다. 이 선택은 https://github.com/huggingface/transformers/pull/38157에 자세히 설명된 경험적 관찰에 기반합니다.

image_seq_length (`int`, *kwargs*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

repo_path (`str`, *kwargs*, *선택 사항*, 기본값은 `shi-labs/oneformer_demo`) : 모델 메타데이터를 포함하는 로컬 디렉터리 또는 HuggingFace Hub 저장소의 경로.

class_info_file (`str`, *kwargs*, *선택*) : 클래스 메타데이터를 포함하는 저장소 내 JSON 파일의 경로.

num_text (`int`, *kwargs*, *선택*) : 텍스트 인코더의 텍스트 쿼리 수로, 태스크 유도 프롬프트로 사용됩니다.

num_labels (`int`, *kwargs*, *선택 사항*) : 분할을 위한 의미론적 클래스의 수로, 출력 레이어의 크기를 결정합니다.

ignore_index (`int`, *kwargs*, *선택*) : 세그멘테이션 맵에서 무시할 레이블로, 패딩에 자주 사용됩니다.

do_reduce_labels (`bool`, *kwargs*, *선택 사항*, 기본값 `False`) : 모든 라벨 값을 1만큼 감소시켜 배경 클래스를 `ignore_index`로 매핑할지 여부.

**반환값:** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- __call__ 메서드가 반환하는 리스트/배열/텐서 딕셔너리('pixel_values' 등).
- **tensor_type** (`Union[None, str, TensorType]`, *선택 사항*) -- 초기화 시 PyTorch/Numpy 텐서에서 정수 목록을 변환하려면 여기에 tensor_type을 지정할 수 있습니다.

#### post_process_semantic_segmentation[[transformers.OneFormerImageProcessorPil.post_process_semantic_segmentation]]

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

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_pil_oneformer.py#L746)

**매개변수:**

outputs ([OneFormerForUniversalSegmentation](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerForUniversalSegmentation)) : 모델의 원시 출력.

target_sizes (`list[tuple[int, int]]`, *선택 사항*) : (batch_size) 길이의 리스트로, 각 리스트 항목(`Tuple[int, int]]`)은 각 예측의 요청된 최종 크기(높이, 너비)에 해당합니다. None으로 두면 예측 결과가 리사이즈되지 않습니다.

return_segmentation_scores (`bool`, *선택 사항*, 기본값 `False`) : 분할 맵과 함께 분할 점수를 반환할지 여부입니다. `True`인 경우, 반환된 리스트의 각 요소는 `segmentation` 필드(클래스 ID, shape `(height, width)`)와 `segmentation_scores` 필드(shape `(num_classes, height, width)`)를 가진 `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_classes, height, width)` 모양) 필드를 가진 `SemanticSegmentationPostProcessorOutput` 리스트를 반환합니다. 두 경우 모두 `(height, width)`는 대상 크기(`target_sizes`가 지정된 경우)에 해당합니다.

[OneFormerForUniversalSegmentation](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerForUniversalSegmentation)의 출력을 의미 분할 맵으로 변환합니다. PyTorch만 지원합니다.

#### post_process_instance_segmentation[[transformers.OneFormerImageProcessorPil.post_process_instance_segmentation]]

```python
post_process_instance_segmentation(outputs, task_type: str = 'instance', is_demo: bool = True, threshold: float = 0.5, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, target_sizes: list[tuple[int, int]] | None = None, return_coco_annotation: bool | None = False)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_pil_oneformer.py#L820)

**매개변수:**

outputs (`OneFormerForUniversalSegmentationOutput`) : `OneFormerForUniversalSegmentationOutput`의 출력입니다.

task_type (`str`, *선택 사항*, 기본값 "instance") : 후처리는 태스크 토큰 입력에 따라 달라집니다. `task_type`가 "panoptic"인 경우, stuff 예측을 무시해야 합니다.

is_demo (`bool`, *선택 사항*, 기본값 `True`) : 모델이 데모 모드인지 여부입니다. 참인 경우, 임계값을 사용하여 최종 마스크를 예측합니다.

threshold (`float`, *선택 사항*, 기본값 0.5) : 예측된 인스턴스 마스크를 유지하기 위한 확률 점수 임계값입니다.

mask_threshold (`float`, *선택*, 기본값 0.5) : 예측된 마스크를 이진 값으로 변환할 때 사용할 임계값입니다.

overlap_mask_area_threshold (`float`, *선택 사항*, 기본값 0.8) : 각 바이너리 인스턴스 마스크 내에서 작은 분리된 부분을 병합하거나 제거하기 위한 오버랩 마스크 영역 임계값입니다.

target_sizes (`List[Tuple]`, *선택 사항*) : (batch_size) 길이의 리스트로, 각 리스트 항목(`Tuple[int, int]]`)은 배치 내 각 예측의 요청된 최종 크기(높이, 너비)에 해당합니다. None으로 두면 예측 결과가 리사이즈되지 않습니다.

return_coco_annotation (`bool`, *선택 사항*, 기본값 `False`) : COCO 형식으로 예측 결과를 반환할지 여부.

**반환값:** `List[Dict]`

이미지별로 하나씩 포함된 딕셔너리 목록이며, 각 딕셔너리에는 두 개의 키가 포함됩니다:
- **segmentation** -- 각 픽셀이 `segment_id`를 나타내는 `(height, width)` 형태의 텐서. `threshold`보다 높은 값이 발견되지 않으면 `None`으로 설정됩니다. `target_sizes`가 지정된 경우, segmentation은 해당 `target_sizes` 항목으로 리사이즈됩니다.
- **segments_info** -- 각 세그먼트에 대한 추가 정보를 포함하는 사전입니다.
  - **id** -- `segment_id`를 나타내는 정수입니다.
  - **label_id** -- `segment_id`에 해당하는 라벨/의미론적 클래스 ID를 나타내는 정수입니다.
  - **was_fused** -- `label_id`가 `label_ids_to_fuse`에 포함되어 있으면 `True`, 그렇지 않으면 `False`인 불리언 값. 동일한 클래스/라벨의 여러 인스턴스가 병합되어 단일 `segment_id`가 할당되었습니다.
  - **score** -- `segment_id`를 가진 세그먼트의 예측 점수.

`OneFormerForUniversalSegmentationOutput`의 출력을 이미지 인스턴스 분할 예측으로 변환합니다. PyTorch만 지원합니다.

#### post_process_panoptic_segmentation[[transformers.OneFormerImageProcessorPil.post_process_panoptic_segmentation]]

```python
post_process_panoptic_segmentation(outputs, threshold: float = 0.5, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, label_ids_to_fuse: set[int] | None = None, target_sizes: list[tuple[int, int]] | None = None)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/image_processing_pil_oneformer.py#L940)

**매개변수:**

outputs (`MaskFormerForInstanceSegmentationOutput`) : [MaskFormerForInstanceSegmentation](/docs/transformers/main/ko/model_doc/maskformer#transformers.MaskFormerForInstanceSegmentation)의 출력입니다.

threshold (`float`, *선택 사항*, 기본값 0.5) : 예측된 인스턴스 마스크를 유지하기 위한 확률 점수 임계값입니다.

mask_threshold (`float`, *선택*, 기본값 0.5) : 예측된 마스크를 이진 값으로 변환할 때 사용할 임계값입니다.

overlap_mask_area_threshold (`float`, *선택 사항*, 기본값 0.8) : 각 바이너리 인스턴스 마스크 내에서 작은 분리된 부분을 병합하거나 제거하기 위한 오버랩 마스크 영역 임계값입니다.

label_ids_to_fuse (`Set[int]`, *선택 사항*) : 이 상태의 라벨은 모든 인스턴스가 하나로 병합됩니다. 예를 들어 이미지에는 하늘이 하나만 있을 수 있지만 여러 명의 사람이 있을 수 있으므로, 하늘의 라벨 ID는 해당 세트에 포함되지만 사람의 라벨 ID는 포함되지 않습니다.

target_sizes (`list[Tuple]`, *선택 사항*) : (batch_size) 길이의 리스트로, 각 리스트 항목(`tuple[int, int]]`)은 배치 내 각 예측의 요청된 최종 크기(높이, 너비)에 해당합니다. None으로 두면 예측 결과가 리사이즈되지 않습니다.

**반환값:** `list[Dict]`

이미지별로 하나씩 포함된 딕셔너리 목록이며, 각 딕셔너리에는 두 개의 키가 포함됩니다:
- **segmentation** -- 각 픽셀이 `segment_id`를 나타내는 `(height, width)` 형태의 텐서. `threshold`보다 높은 값이 발견되지 않으면 `None`으로 설정됩니다. `target_sizes`가 지정된 경우, segmentation은 해당 `target_sizes` 항목으로 리사이즈됩니다.
- **segments_info** -- 각 세그먼트에 대한 추가 정보를 포함하는 사전입니다.
  - **id** -- `segment_id`를 나타내는 정수입니다.
  - **label_id** -- `segment_id`에 해당하는 라벨/의미론적 클래스 ID를 나타내는 정수입니다.
  - **was_fused** -- `label_id`가 `label_ids_to_fuse`에 포함되어 있으면 `True`, 그렇지 않으면 `False`인 불리언 값. 동일한 클래스/라벨의 여러 인스턴스가 병합되어 단일 `segment_id`가 할당되었습니다.
  - **score** -- `segment_id`를 가진 세그먼트의 예측 점수.

`MaskFormerForInstanceSegmentationOutput`의 출력을 이미지 팬옵틱 세분화 예측으로 변환합니다. PyTorch만 지원합니다.

## OneFormerProcessor[[transformers.OneFormerProcessor]]

#### transformers.OneFormerProcessor[[transformers.OneFormerProcessor]]

```python
transformers.OneFormerProcessor(image_processor = None, tokenizer = None, max_seq_length: int = 77, task_seq_length: int = 77, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/processing_oneformer.py#L27)

**매개변수:**

image_processor (`OneFormerImageProcessor`) : 이미지 프로세서가 필수 입력입니다.

tokenizer (`CLIPTokenizer`) : 토크나이저는 필수 입력입니다.

max_seq_length (`int`, *선택 사항*, 기본값 `77`) : 클래스 이름 및 텍스트 입력을 인코딩할 때의 최대 시퀀스 길이. 이 매개변수는 모델에 대한 클래스 이름 및 기타 텍스트 입력을 토큰화할 때 사용되는 최대 토큰 수를 제어합니다.

task_seq_length (`int`, *선택 사항*, 기본값 `77`) : 작업 설명 인코딩에 특화된 최대 시퀀스 길이입니다. 작업 설명(예: "the task is semantic")은 이 길이 제한으로 토큰화되며, 이는 일반 텍스트 시퀀스 길이와 다를 수 있습니다.

이미지 프로세서와 토크나이저를 단일 프로세서로 묶는 OneFormerProcessor를 생성합니다.

[OneFormerProcessor](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerProcessor)는 [OneFormerImageProcessor](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerImageProcessor)와 [CLIPTokenizer](/docs/transformers/main/ko/model_doc/clip#transformers.CLIPTokenizer)의 모든 기능을 제공합니다. 자세한 내용은 [~OneFormerImageProcessor](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerImageProcessor)와 [~CLIPTokenizer](/docs/transformers/main/ko/model_doc/clip#transformers.CLIPTokenizer)를 참고하세요.

#### __call__[[transformers.OneFormerProcessor.__call__]]

```python
__call__(images = None, task_inputs = None, segmentation_maps = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/processing_oneformer.py#L61)

**매개변수:**

images (``) : Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.

task_inputs (`str` 또는 `list[str]`, *required*) : 분할을 위한 작업 유형입니다. `"semantic"`, `"instance"`, `"panoptic"` 중 하나 이상이어야 합니다. 단일 이미지의 경우 단일 문자열, 배치 처리의 경우 문자열 목록(이미지당 하나)을 사용할 수 있습니다. 작업 유형은 모델이 입력 이미지에서 수행할 분할의 유형을 결정합니다.

segmentation_maps (`ImageInput`, *선택*) : 픽셀 단위 어노테이션이 포함된 해당 시맨틱 세그멘테이션 맵. (`bool`, *선택*, 기본값 `True`): 배치 내 가장 큰 이미지에 맞춰 이미지를 패딩하고 픽셀 마스크를 생성할지 여부. 기본값을 유지하면 다음과 같은 픽셀 마스크를 반환합니다: - 실제 픽셀(즉, **마스크되지 않은** 픽셀)은 1 - 패딩 픽셀(즉, **마스크된** 픽셀)은 0

return_tensors (`str` 또는 [TensorType](/docs/transformers/main/ko/internal/file_utils#transformers.TensorType), *optional*) : 설정된 경우, 특정 프레임워크의 텐서를 반환합니다. 허용되는 값은 다음과 같습니다:  - `'pt'`: PyTorch `torch.Tensor` 객체를 반환합니다. - `'np'`: NumPy `np.ndarray` 객체를 반환합니다.

**반환값:** [BatchFeature](/docs/transformers/main/ko/main_classes/feature_extractor#transformers.BatchFeature)

다음 필드를 가진 [BatchFeature](/docs/transformers/main/ko/main_classes/feature_extractor#transformers.BatchFeature):
- **task_inputs** -- 모델에 입력할 토큰 ID 목록. `text`가 `None`이 아닌 경우 반환됩니다.
- **pixel_values** -- 모델에 입력할 픽셀 값. `images`가 `None`이 아닌 경우 반환됩니다.

## OneFormerModel[[transformers.OneFormerModel]]

#### transformers.OneFormerModel[[transformers.OneFormerModel]]

```python
transformers.OneFormerModel(config: OneFormerConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/modeling_oneformer.py#L2855)

**매개변수:**

config ([OneFormerConfig](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerConfig)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

특정 헤드가 위에 없는 원시 hidden-states를 출력하는 기본 Oneformer Model입니다.

이 모델은 [PreTrainedModel](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.OneFormerModel.forward]]

```python
forward(pixel_values: Tensor, task_inputs: Tensor, text_inputs: typing.Optional[torch.Tensor] = None, pixel_mask: typing.Optional[torch.Tensor] = None, output_hidden_states: bool | None = None, output_attentions: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/modeling_oneformer.py#L2872)

**매개변수:**

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 [OneFormerImageProcessor](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerImageProcessor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [OneFormerImageProcessor.__call__()](/docs/transformers/main/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요 ([OneFormerProcessor](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerProcessor)는 이미지 처리에 [OneFormerImageProcessor](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerImageProcessor)를 사용합니다).

task_inputs (`torch.Tensor`, shape `(batch_size, sequence_length)`) : 태스크 입력값. [AutoImageProcessor](/docs/transformers/main/ko/model_doc/auto#transformers.AutoImageProcessor)를 사용하여 태스크 입력값을 얻을 수 있습니다. 자세한 내용은 [OneFormerProcessor.__call__()](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerProcessor.__call__)를 참조하세요.

text_inputs (`list[torch.Tensor]`, *선택 사항*) : 모델에 입력할 `(num_queries, sequence_length)` 형태의 텐서

pixel_mask (`torch.Tensor`, shape `(batch_size, height, width)`, *선택 사항*) : 패딩 픽셀 값에 대한 attention 수행을 방지하기 위한 마스크. `[0, 1]`에서 선택된 마스크 값: - 실제 픽셀(즉, **마스크되지 않은** 픽셀)은 1, - 패딩 픽셀(즉, **마스크된** 픽셀)은 0. [attention 마스크란 무엇인가요?](../glossary#attention-mask)

output_hidden_states (`bool`, *선택 사항*) : 모든 레이어의 hidden states를 반환할지 여부. 자세한 내용은 반환되는 텐서 중 `hidden_states` 항목을 참조하세요.

output_attentions (`bool`, *선택 사항*) : 모든 어텐션 레이어의 어텐션 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 `attentions`를 참조하세요.

return_dict (`bool`, *선택 사항*) : 일반 튜플 대신 [ModelOutput](/docs/transformers/main/ko/main_classes/output#transformers.utils.ModelOutput)를 반환할지 여부.

**반환값:** [OneFormerModelOutput](/docs/transformers/main/ko/model_doc/oneformer#transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput) 또는 `tuple(torch.Tensor)`

구성([OneFormerConfig](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerConfig))과 입력에 따라 다양한 요소를 포함하는 [OneFormerModelOutput](/docs/transformers/main/ko/model_doc/oneformer#transformers.models.oneformer.modeling_oneformer.OneFormerModelOutput) 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되거나 `config.return_dict=False`인 경우).

[OneFormerModel](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerModel)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(forward pass) 레시피를 이 함수 내에서 정의해야 하더라도 이후에는 이 함수 대신 `Module` 인스턴스를 호출해야 합니다.

- **encoder_hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(임베딩 출력 1개 + 각 단계의 출력 1개)로, 모양은 `(batch_size, num_channels, height, width)`입니다. 각 단계의 출력에서 인코더 모델의 히든 스테이트(피처 맵이라고도 함).
- **pixel_decoder_hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(임베딩 출력 1개 + 각 단계의 출력 1개)로, 모양은 `(batch_size, num_channels, height, width)`입니다. 각 단계의 출력에서 픽셀 디코더 모델의 히든 스테이트(피처 맵이라고도 함).
- **transformer_decoder_hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(임베딩 출력 1개 + 각 단계의 출력 1개)로, 모양은 `(batch_size, sequence_length, hidden_size)`입니다. 각 단계의 출력에서 transformer decoder의 hidden-states(또는 feature maps라고도 함).
- **transformer_decoder_object_queries** (`torch.Tensor`, shape `(batch_size, num_queries, hidden_dim)`) -- transformer decoder의 마지막 레이어에서 출력된 object queries입니다.
- **transformer_decoder_contrastive_queries** (`torch.Tensor`, shape `(batch_size, num_queries, hidden_dim)`) -- transformer decoder에서 생성된 contrastive queries입니다.
- **transformer_decoder_mask_predictions** (`torch.Tensor`, shape `(batch_size, num_queries, height, width)`) -- Transformer decoder의 마지막 레이어에서 생성된 마스크 예측 값입니다.
- **transformer_decoder_class_predictions** (`torch.Tensor`, shape `(batch_size, num_queries, num_classes+1)`) -- transformer decoder의 마지막 레이어에서 생성된 클래스 예측 값.
- **transformer_decoder_auxiliary_predictions** (`Tuple` of Dict of `str, torch.Tensor`, *optional*) -- Tuple of class and mask predictions from each layer of the transformer decoder.
- **text_queries** (`torch.Tensor`, *선택*, shape `(batch_size, num_queries, hidden_dim)`) -- 학습 중 대조적 손실을 계산하는 데 사용되는 입력 텍스트 목록에서 파생된 텍스트 쿼리.
- **task_token** (`torch.Tensor`, shape `(batch_size, hidden_dim)`) -- 쿼리를 조건화하기 위한 1차원 태스크 토큰.
- **attentions** (`tuple(tuple(torch.Tensor))`, *optional*, `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환) -- shape가 `(batch_size, num_heads, sequence_length, sequence_length)`인 `tuple(torch.Tensor)`의 Tuple (레이어당 하나). transformer decoder의 Self Attention과 Cross Attention 가중치입니다.

예:

```python
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from transformers import OneFormerProcessor, OneFormerModel

>>> # download test image
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> # load processor for preprocessing the inputs
>>> processor = OneFormerProcessor.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
>>> model = OneFormerModel.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
>>> inputs = processor(image, ["semantic"], return_tensors="pt")

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

>>> mask_predictions = outputs.transformer_decoder_mask_predictions
>>> class_predictions = outputs.transformer_decoder_class_predictions

>>> f"👉 Mask Predictions Shape: {list(mask_predictions.shape)}, Class Predictions Shape: {list(class_predictions.shape)}"
'👉 Mask Predictions Shape: [1, 150, 128, 171], Class Predictions Shape: [1, 150, 151]'
```

## OneFormerForUniversalSegmentation[[transformers.OneFormerForUniversalSegmentation]]

#### transformers.OneFormerForUniversalSegmentation[[transformers.OneFormerForUniversalSegmentation]]

```python
transformers.OneFormerForUniversalSegmentation(config: OneFormerConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/modeling_oneformer.py#L2991)

**매개변수:**

config ([OneFormerConfig](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerConfig)) : 모델의 모든 매개변수를 포함하는 모델 구성 클래스입니다. 구성 파일로 초기화하는 것은 모델과 관련된 가중치를 로드하지 않으며, 구성 정보만 로드합니다. 모델 가중치를 로드하려면 [from_pretrained()](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel.from_pretrained) 메서드를 확인하세요.

OneFormer 모델은 인스턴스, 시맨틱, 팬옵틱 이미지 분할을 수행합니다.

이 모델은 [PreTrainedModel](/docs/transformers/main/ko/main_classes/model#transformers.PreTrainedModel)에서 상속됩니다. 라이브러리가 모든 모델에 대해 구현하는 일반적 메서드(다운로드 또는 저장, 입력 임베딩 크기 조정, 헤드 프루닝 등)에 대해서는 상위 클래스 문서를 확인하세요.

이 모델은 또한 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)의 하위 클래스입니다. 일반적인 PyTorch Module처럼 사용하며, 일반적인 사용법과 동작에 관한 모든 사항은 PyTorch 문서를 참조하세요.

#### forward[[transformers.OneFormerForUniversalSegmentation.forward]]

```python
forward(pixel_values: Tensor, task_inputs: Tensor, text_inputs: typing.Optional[torch.Tensor] = None, mask_labels: list[torch.Tensor] | None = None, class_labels: list[torch.Tensor] | None = None, pixel_mask: typing.Optional[torch.Tensor] = None, output_auxiliary_logits: bool | None = None, output_hidden_states: bool | None = None, output_attentions: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/oneformer/modeling_oneformer.py#L3058)

**매개변수:**

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 [OneFormerImageProcessor](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerImageProcessor)를 사용하여 얻을 수 있습니다. 자세한 내용은 [OneFormerImageProcessor.__call__()](/docs/transformers/main/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)를 참조하세요 ([OneFormerProcessor](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerProcessor)는 이미지 처리에 [OneFormerImageProcessor](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerImageProcessor)를 사용합니다).

task_inputs (`torch.Tensor`, shape `(batch_size, sequence_length)`) : 태스크 입력값. [AutoImageProcessor](/docs/transformers/main/ko/model_doc/auto#transformers.AutoImageProcessor)를 사용하여 태스크 입력값을 얻을 수 있습니다. 자세한 내용은 [OneFormerProcessor.__call__()](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerProcessor.__call__)를 참조하세요.

text_inputs (`list[torch.Tensor]`, *선택 사항*) : 모델에 입력할 `(num_queries, sequence_length)` 형태의 텐서

mask_labels (`list[torch.Tensor]`, *선택 사항*) : 모델에 전달할 `(num_labels, height, width)` 모양의 마스크 라벨 목록

class_labels (`list[torch.LongTensor]`, *선택 사항*) : 모델에 전달할 `(num_labels, height, width)` 형식의 대상 클래스 라벨 목록입니다. `mask_labels`의 라벨을 식별하며, 예를 들어 `class_labels[i][j]`인 경우 `mask_labels[i][j]`의 라벨을 나타냅니다.

pixel_mask (`torch.Tensor`, shape `(batch_size, height, width)`, *선택 사항*) : 패딩 픽셀 값에 대한 attention 수행을 방지하기 위한 마스크. `[0, 1]`에서 선택된 마스크 값: - 실제 픽셀(즉, **마스크되지 않은** 픽셀)은 1, - 패딩 픽셀(즉, **마스크된** 픽셀)은 0. [attention 마스크란 무엇인가요?](../glossary#attention-mask)

output_auxiliary_logits (`bool`, *선택 사항*) : 보조 로짓(auxiliary logits)을 출력할지 여부.

output_hidden_states (`bool`, *선택 사항*) : 모든 레이어의 hidden states를 반환할지 여부. 자세한 내용은 반환되는 텐서 중 `hidden_states` 항목을 참조하세요.

output_attentions (`bool`, *선택 사항*) : 모든 어텐션 레이어의 어텐션 텐서를 반환할지 여부. 자세한 내용은 반환 텐서 섹션의 `attentions`를 참조하세요.

return_dict (`bool`, *선택 사항*) : 일반 튜플 대신 [ModelOutput](/docs/transformers/main/ko/main_classes/output#transformers.utils.ModelOutput)를 반환할지 여부.

**반환값:** [OneFormerForUniversalSegmentationOutput](/docs/transformers/main/ko/model_doc/oneformer#transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput) 또는 `tuple(torch.Tensor)`

[OneFormerForUniversalSegmentationOutput](/docs/transformers/main/ko/model_doc/oneformer#transformers.models.oneformer.modeling_oneformer.OneFormerForUniversalSegmentationOutput) 또는 `torch.Tensor`의 튜플(`return_dict=False`가 전달되었거나 `config.return_dict=False`인 경우)로, 구성([OneFormerConfig](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerConfig))과 입력에 따라 다양한 요소를 포함합니다.

[OneFormerForUniversalSegmentation](/docs/transformers/main/ko/model_doc/oneformer#transformers.OneFormerForUniversalSegmentation)의 forward 메서드는 `__call__` 특수 메서드를 오버라이드합니다.

`Module` 인스턴스는 전처리 및 후처리 단계를 실행하는 것을 처리하지만, 이 함수는 해당 단계를 조용히 무시하므로, 순전파(forward pass) 레시피를 이 함수 내에서 정의해야 하더라도 이후에는 이 함수 대신 `Module` 인스턴스를 호출해야 합니다.

- **loss** (`torch.Tensor`, *선택 사항*) -- 라벨이 존재할 때 반환되는 계산된 손실입니다.
- **class_queries_logits** (`torch.Tensor`, *선택*) -- 각 query에 대해 제안된 클래스를 나타내는 shape가 `(batch_size, num_queries, num_labels + 1)`인 텐서입니다. null 클래스를 포함하기 때문에 `+ 1`이 필요합니다.
- **masks_queries_logits** (`torch.Tensor`, *선택 사항*) -- 각 쿼리에 대한 제안된 마스크를 나타내는 `(batch_size, num_queries, height, width)` 형태의 텐서입니다.
- **auxiliary_predictions** (`List` of Dict of `str, torch.Tensor`, *optional*) -- List of class and mask predictions from each layer of the transformer decoder.
- **encoder_hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(임베딩 출력 1개 + 각 단계의 출력 1개)로, 모양은 `(batch_size, num_channels, height, width)`입니다. 각 단계의 출력에서 인코더 모델의 히든 스테이트(피처 맵이라고도 함).
- **pixel_decoder_hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(임베딩 출력 1개 + 각 단계의 출력 1개)로, 모양은 `(batch_size, num_channels, height, width)`입니다. 각 단계의 출력에서 픽셀 디코더 모델의 히든 스테이트(피처 맵이라고도 함).
- **transformer_decoder_hidden_states** (`tuple(torch.Tensor)`, *선택 사항*, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됨) -- `torch.Tensor`의 튜플(임베딩 출력 1개 + 각 단계의 출력 1개)로, 모양은 `(batch_size, sequence_length, hidden_size)`입니다. 각 단계의 출력에서 transformer decoder의 hidden-states(또는 feature maps라고도 함).
- **transformer_decoder_object_queries** (`torch.Tensor`, shape `(batch_size, num_queries, hidden_dim)`) -- transformer decoder의 마지막 레이어에서 출력된 object queries입니다.
- **transformer_decoder_contrastive_queries** (`torch.Tensor`, shape `(batch_size, num_queries, hidden_dim)`) -- transformer decoder에서 생성된 contrastive queries입니다.
- **transformer_decoder_mask_predictions** (`torch.Tensor`, shape `(batch_size, num_queries, height, width)`) -- Transformer decoder의 마지막 레이어에서 생성된 마스크 예측 값입니다.
- **transformer_decoder_class_predictions** (`torch.Tensor`, shape `(batch_size, num_queries, num_classes+1)`) -- transformer decoder의 마지막 레이어에서 생성된 클래스 예측 값.
- **transformer_decoder_auxiliary_predictions** (`List` of `str, torch.Tensor` Dict, *선택 사항*) -- transformer decoder의 각 레이어에서 생성된 클래스 및 마스크 예측 목록입니다.
- **text_queries** (`torch.Tensor`, *선택*, shape `(batch_size, num_queries, hidden_dim)`) -- 학습 중 대조적 손실을 계산하는 데 사용되는 입력 텍스트 목록에서 파생된 텍스트 쿼리.
- **task_token** (`torch.Tensor`, shape `(batch_size, hidden_dim)`) -- 쿼리를 조건화하기 위한 1차원 태스크 토큰.
- **attentions** (`tuple(tuple(torch.Tensor))`, *optional*, `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환) -- shape가 `(batch_size, num_heads, sequence_length, sequence_length)`인 `tuple(torch.Tensor)`의 Tuple (레이어당 하나). transformer decoder의 Self Attention과 Cross Attention 가중치입니다.

예:

범용 분할 예시:

```python
>>> from transformers import OneFormerProcessor, OneFormerForUniversalSegmentation
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> import torch

>>> # load OneFormer fine-tuned on ADE20k for universal segmentation
>>> processor = OneFormerProcessor.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
>>> model = OneFormerForUniversalSegmentation.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")

>>> url = (
...     "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"
... )
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> # Semantic Segmentation
>>> inputs = processor(image, ["semantic"], return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)
>>> # model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits

>>> # you can pass them to processor for semantic postprocessing
>>> predicted_semantic_map = processor.post_process_semantic_segmentation(
...     outputs, target_sizes=[(image.height, image.width)]
... )[0]
>>> f"👉 Semantic Predictions Shape: {list(predicted_semantic_map.shape)}"
'👉 Semantic Predictions Shape: [512, 683]'

>>> # Instance Segmentation
>>> inputs = processor(image, ["instance"], return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)
>>> # model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits

>>> # you can pass them to processor for instance postprocessing
>>> predicted_instance_map = processor.post_process_instance_segmentation(
...     outputs, target_sizes=[(image.height, image.width)]
... )[0]["segmentation"]
>>> f"👉 Instance Predictions Shape: {list(predicted_instance_map.shape)}"
'👉 Instance Predictions Shape: [512, 683]'

>>> # Panoptic Segmentation
>>> inputs = processor(image, ["panoptic"], return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)
>>> # model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits

>>> # you can pass them to processor for panoptic postprocessing
>>> predicted_panoptic_map = processor.post_process_panoptic_segmentation(
...     outputs, target_sizes=[(image.height, image.width)]
... )[0]["segmentation"]
>>> f"👉 Panoptic Predictions Shape: {list(predicted_panoptic_map.shape)}"
'👉 Panoptic Predictions Shape: [512, 683]'
```

