# EfficientLoFTR

[EfficientLoFTR](https://huggingface.co/papers/2403.04765)는 검출기 없이 동작하는 효율적인 로컬 특징 매칭 기법으로, 희소 매칭 수준의 속도로 이미지 간 반밀집(semi-dense) 매칭을 생성합니다. 기존 [LoFTR](https://huggingface.co/papers/2104.00680) 아키텍처를 기반으로 하되, 효율성과 정확도 모두에서 상당한 개선을 도입했습니다. 핵심 혁신은 적응형 토큰 선택을 결합한 집계된 어텐션 메커니즘으로, 이를 통해 LoFTR보다 약 2.5배 빠른 속도를 유지하면서 더 높은 정확도를 달성합니다. [SuperPoint](./superpoint) + [LightGlue](./lightglue)와 같은 최첨단 효율적 희소 매칭 파이프라인보다 속도 면에서 우월할 수 있어, 이미지 검색이나 3D 재구성처럼 대규모 또는 지연 시간(latency)에 민감한 애플리케이션에 적합합니다.

> [!TIP]
> 이 모델은 [stevenbucaille](https://huggingface.co/stevenbucaille)에 의해 기여되었습니다.
>
> 오른쪽 사이드바의 EfficientLoFTR 모델에 클릭하여 EfficientLoFTR을 다양한 컴퓨터 비전 작업에 적용하는 방법에 대한 추가 예제를 확인하세요.

아래 예제는 [Pipeline](/docs/transformers/main/ko/main_classes/pipelines#transformers.Pipeline) 또는 [AutoModel](/docs/transformers/main/ko/model_doc/auto#transformers.AutoModel) 클래스를 사용하여 두 이미지 간의 keypoint를 매칭하는 방법을 보여줍니다.

```python
from transformers import pipeline

keypoint_matcher = pipeline(task="keypoint-matching", model="zju-community/efficientloftr")

url_0 = "https://raw.githubusercontent.com/magicleap/SuperGluePretrainedNetwork/refs/heads/master/assets/phototourism_sample_images/united_states_capitol_98169888_3347710852.jpg"
url_1 = "https://raw.githubusercontent.com/magicleap/SuperGluePretrainedNetwork/refs/heads/master/assets/phototourism_sample_images/united_states_capitol_26757027_6717084061.jpg"

results = keypoint_matcher([url_0, url_1], threshold=0.9)
print(results[0])
# {'keypoint_image_0': {'x': ..., 'y': ...}, 'keypoint_image_1': {'x': ..., 'y': ...}, 'score': ...}
```

```python
import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, AutoModelForKeypointMatching

url_image1 = "https://raw.githubusercontent.com/magicleap/SuperGluePretrainedNetwork/refs/heads/master/assets/phototourism_sample_images/united_states_capitol_98169888_3347710852.jpg"
image1 = Image.open(requests.get(url_image1, stream=True).raw)
url_image2 = "https://raw.githubusercontent.com/magicleap/SuperGluePretrainedNetwork/refs/heads/master/assets/phototourism_sample_images/united_states_capitol_26757027_6717084061.jpg"
image2 = Image.open(requests.get(url_image2, stream=True).raw)

images = [image1, image2]

processor = AutoImageProcessor.from_pretrained("zju-community/efficientloftr")
model = AutoModelForKeypointMatching.from_pretrained("zju-community/efficientloftr", device_map="auto")

inputs = processor(images, return_tensors="pt").to(model.device)
with torch.inference_mode():
    outputs = model(**inputs)

# Post-process to get keypoints and matches
image_sizes = [[(image.height, image.width) for image in images]]
processed_outputs = processor.post_process_keypoint_matching(outputs, image_sizes, threshold=0.2)
```

## The input is a single word "Notes".

참고

- EfficientLoFTR는 높은 정확도를 유지하면서 효율성을 확보하도록 설계되었습니다. 기존 LoFTR에 비해 계산 부하를 줄이기 위해 적응형 토큰 선택이 적용된 집계된 attention 메커니즘을 사용합니다.

    ```py
    from transformers import AutoImageProcessor, AutoModelForKeypointMatching
    import torch
    from PIL import Image
    import requests
    
    processor = AutoImageProcessor.from_pretrained("zju-community/efficientloftr")
    model = AutoModelForKeypointMatching.from_pretrained("zju-community/efficientloftr", device_map="auto")
    
    # EfficientLoFTR requires pairs of images
    images = [image1, image2]
    inputs = processor(images, return_tensors="pt").to(model.device)
    with torch.inference_mode():
        outputs = model(**inputs)
    
    # Extract matching information
    keypoints = outputs.keypoints        # Keypoints in both images
    matches = outputs.matches            # Matching indices 
    matching_scores = outputs.matching_scores  # Confidence scores
    ```

- 모델은 반밀집(semi-dense) 매칭을 생성하여 매칭의 밀도와 계산 효율성 사이의 균형을 잘 맞춥니다. 큰 시점 변화와 질감이 부족한 시나리오를 처리하는 데 뛰어납니다.

- 더 나은 시각화와 분석을 위해 [post_process_keypoint_matching()](/docs/transformers/main/ko/model_doc/efficientloftr#transformers.EfficientLoFTRImageProcessor.post_process_keypoint_matching) 메서드를 사용하여 매칭 결과를 더 가독성 높은 형식으로 가져오세요.

    ```py
    # Process outputs for visualization
    image_sizes = [[(image.height, image.width) for image in images]]
    processed_outputs = processor.post_process_keypoint_matching(outputs, image_sizes, threshold=0.2)
    
    for i, output in enumerate(processed_outputs):
        print(f"For the image pair {i}")
        for keypoint0, keypoint1, matching_score in zip(
                output["keypoints0"], output["keypoints1"], output["matching_scores"]
        ):
            print(f"Keypoint at {keypoint0.numpy()} matches with keypoint at {keypoint1.numpy()} with score {matching_score}")
    ```

- 내장된 플롯팅 기능을 사용하여 이미지 간의 매칭을 시각화합니다.

    ```py
    # Easy visualization using the built-in plotting method
    visualized_images = processor.visualize_keypoint_matching(images, processed_outputs)
    ```

- EfficientLoFTR는 정밀한 서브픽셀 대응을 달성하는 새로운 2단계 상관 계층을 사용하여, 원래 LoFTR의 세부 상관 모듈을 개선합니다.

    

## 리소스

- 추가 예제 및 구현 세부 사항은 [EfficientLoFTR 원본 저장소](https://github.com/zju3dv/EfficientLoFTR)를 참조하세요.
- 인터랙티브 데모와 추가 정보를 제공하는 [EfficientLoFTR 프로젝트 페이지](https://zju3dv.github.io/efficientloftr/).

## EfficientLoFTRConfig[[transformers.EfficientLoFTRConfig]]

#### transformers.EfficientLoFTRConfig[[transformers.EfficientLoFTRConfig]]

```python
transformers.EfficientLoFTRConfig(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, stage_num_blocks: list[int] | None = None, out_features: list[int] | None = None, stage_stride: list[int] | None = None, hidden_size: int = 256, activation_function: str = 'relu', q_aggregation_kernel_size: int = 4, kv_aggregation_kernel_size: int = 4, q_aggregation_stride: int = 4, kv_aggregation_stride: int = 4, num_attention_layers: int = 4, num_attention_heads: int = 8, attention_dropout: float | int = 0.0, attention_bias: bool = False, mlp_activation_function: str = 'leaky_relu', coarse_matching_skip_softmax: bool = False, coarse_matching_threshold: float = 0.2, coarse_matching_temperature: float = 0.1, coarse_matching_border_removal: int = 2, fine_kernel_size: int = 8, batch_norm_eps: float = 1e-05, rope_parameters: dict | None = None, fine_matching_slice_dim: int = 8, fine_matching_regress_temperature: float = 10.0, initializer_range: float = 0.02)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientloftr/configuration_efficientloftr.py#L24)

**매개변수:**

stage_num_blocks (`List`, *선택 사항*, 기본값 [1, 2, 4, 14]) : 각 단계의 블록 수

out_features (`list[int]`, *선택 사항*) : backbone에서 반환할 중간 hidden states(피처 맵)의 이름. `"stem"`, `"stage1"`, `"stage2"` 등 중 하나입니다.

stage_stride (`List`, *선택 사항*, 기본값 [2, 1, 2, 2]) : 각 단계에서 사용되는 스트라이드

hidden_size (`int`, *선택 사항*, 기본값 `256`) : 숨겨진 표현의 차원.

activation_function (`str`, *선택 사항*, 기본값 `relu`) : 디코더의 비선형 활성화 함수(함수 또는 문자열). 예를 들어, `"gelu"`, `"relu"`, `"silu"` 등.

q_aggregation_kernel_size (`int`, *선택 사항*, 기본값 4) : fusion network에서 query states를 집계할 때 사용하는 커널 크기

kv_aggregation_kernel_size (`int`, *선택 사항*, 기본값 4) : fusion network에서 key와 value 상태의 집계(aggregation)에 사용되는 커널 크기

q_aggregation_stride (`int`, *선택 사항*, 기본값 4) : fusion network에서 query states를 집계할 때 사용하는 stride

kv_aggregation_stride (`int`, *선택 사항*, 기본값 4) : fusion network에서 key와 value state를 집계할 때 사용하는 stride

num_attention_layers (`int`, *선택 사항*, 기본값 4) : LocalFeatureTransformer의 attention 레이어 수

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

attention_dropout (`Union[float, int]`, *선택 사항*, 기본값 `0.0`) : attention 확률에 적용할 dropout 비율입니다.

attention_bias (`bool`, *선택 사항*, 기본값 `False`) : self-attention에서 query, key, value 및 output projection layer에 bias를 사용할지 여부.

mlp_activation_function (`str`, *선택 사항*, 기본값 `"leaky_relu"`) : attention mlp 레이어에서 사용되는 활성화 함수.

coarse_matching_skip_softmax (`bool`, *선택 사항*, 기본값 `False`) : coarse matching 단계에서 softmax를 건너뛸지 여부.

coarse_matching_threshold (`float`, *선택 사항*, 기본값 0.2) : 매칭에 필요한 최소 점수의 임계값입니다.

coarse_matching_temperature (`float`, *선택 사항*, 기본값 0.1) : 거친 유사도 행렬에 적용할 온도

coarse_matching_border_removal (`int`, *선택 사항*, 기본값 2) : 거친 매칭 과정에서 제거할 경계의 크기

fine_kernel_size (`int`, *선택 사항*, 기본값 8) : 정밀한 특징 매칭에 사용되는 커널 크기

batch_norm_eps (`float`, *선택 사항*, 기본값 1e-05) : 배치 정규화 레이어에서 사용되는 epsilon

rope_parameters (`dict`, *선택*) : RoPE 임베딩의 구성 매개변수를 포함하는 사전입니다. 사전에는 `rope_theta` 값이 포함되어야 하며, 더 긴 `max_position_embeddings`로 RoPE를 사용하려는 경우 스케일링에 사용되는 매개변수를 선택적으로 포함할 수 있습니다.

fine_matching_slice_dim (`int`, *선택 사항*, 기본값 8) : 1단계 및 2단계 정밀 매칭 단계에서 정밀 특징을 분할하는 데 사용되는 슬라이스의 크기입니다.

fine_matching_regress_temperature (`float`, *선택 사항*, 기본값 10.0) : 미세 유사도 행렬에 적용할 온도

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

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

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 EfficientLoFTRConfig, EfficientLoFTRForKeypointMatching

>>> # Initializing a EfficientLoFTR configuration
>>> configuration = EfficientLoFTRConfig()

>>> # Initializing a model from the EfficientLoFTR configuration
>>> model = EfficientLoFTRForKeypointMatching(configuration)

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

## EfficientLoFTRImageProcessor[[transformers.EfficientLoFTRImageProcessor]]

#### transformers.EfficientLoFTRImageProcessor[[transformers.EfficientLoFTRImageProcessor]]

```python
transformers.EfficientLoFTRImageProcessor(**kwargs: *<class 'transformers.models.efficientloftr.image_processing_efficientloftr.EfficientLoFTRImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientloftr/image_processing_efficientloftr.py#L110)

**매개변수:**

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

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

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

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*, *선택 사항*, 기본값 `None`) : 이미지를 정규화할지 여부.

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*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

do_grayscale (`bool`, *kwargs*, *선택 사항*, 기본값은 `self.do_grayscale`) : 이미지를 흑백으로 변환할지 여부입니다. `preprocess` 메서드의 `do_grayscale`로 재정의할 수 있습니다.

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

#### preprocess[[transformers.EfficientLoFTRImageProcessor.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']], **kwargs: *<class 'transformers.models.efficientloftr.image_processing_efficientloftr.EfficientLoFTRImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientloftr/image_processing_efficientloftr.py#L124)

**매개변수:**

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

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*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

do_grayscale (`bool`, *kwargs*, *선택 사항*, 기본값은 `self.do_grayscale`) : 이미지를 흑백으로 변환할지 여부입니다. `preprocess` 메서드의 `do_grayscale`로 재정의할 수 있습니다.

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

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

#### post_process_keypoint_matching[[transformers.EfficientLoFTRImageProcessor.post_process_keypoint_matching]]

```python
post_process_keypoint_matching(outputs: EfficientLoFTRKeypointMatchingOutput, target_sizes: transformers.utils.generic.TensorType | list[tuple], threshold: float = 0.0)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientloftr/image_processing_efficientloftr.py#L180)

**매개변수:**

outputs (`EfficientLoFTRKeypointMatchingOutput`) : 모델의 원시 출력입니다.

target_sizes (`torch.Tensor` 또는 `List[Tuple[Tuple[int, int]]]`, *선택 사항*) : 배치 내 각 이미지의 대상 크기 `(height, width)`를 포함하는 `(batch_size, 2, 2)` 모양의 Tensor 또는 튜플의 튜플(`Tuple[int, int]`) 목록입니다. 이는 모든 처리를 수행하기 전의 원본 이미지 크기여야 합니다.

threshold (`float`, *선택 사항*, 기본값 0.0) : 점수가 낮은 매칭을 필터링하기 위한 임계값.

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

각 사전에 쌍의 첫 번째 및 두 번째 이미지의 keypoints, 매칭 점수, 매칭 인덱스가 포함된 사전 목록입니다.

`EfficientLoFTRKeypointMatchingOutput`의 원시 출력을 원래 이미지 크기에 대한 절대 좌표를 가진 키포인트, 점수 및 기술자 목록으로 변환합니다.

#### visualize_keypoint_matching[[transformers.EfficientLoFTRImageProcessor.visualize_keypoint_matching]]

```python
visualize_keypoint_matching(images, keypoint_matching_output: list)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientloftr/image_processing_efficientloftr.py#L239)

**매개변수:**

images : 플롯할 이미지 쌍. `EfficientLoFTRImageProcessor.preprocess`와 동일합니다. 픽셀 값이 0에서 255 범위로 이루어진 2개의 이미지 목록 또는 2개의 이미지 목록의 목록을 기대합니다.

keypoint_matching_output List[Dict[str, torch.Tensor]] : 후처리된 keypoint matching 출력

**반환값:** `List[PIL.Image.Image]`

각 이미지가 감지된 키포인트와 그들 간의 매칭을 포함하여 이미지 쌍을 나란히 포함하는 PIL 이미지 목록입니다.

감지된 키포인트와 그들 간의 매칭을 포함하여 이미지 쌍을 나란히 플롯합니다.

## EfficientLoFTRImageProcessorPil[[transformers.EfficientLoFTRImageProcessorPil]]

#### transformers.EfficientLoFTRImageProcessorPil[[transformers.EfficientLoFTRImageProcessorPil]]

```python
transformers.EfficientLoFTRImageProcessorPil(**kwargs: *<class 'transformers.models.efficientloftr.image_processing_pil_efficientloftr.EfficientLoFTRImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientloftr/image_processing_pil_efficientloftr.py#L108)

**매개변수:**

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

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

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

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*, *선택 사항*, 기본값 `None`) : 이미지를 정규화할지 여부.

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*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

do_grayscale (`bool`, *kwargs*, *선택 사항*, 기본값은 `self.do_grayscale`) : 이미지를 흑백으로 변환할지 여부입니다. `preprocess` 메서드의 `do_grayscale`로 재정의할 수 있습니다.

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

#### preprocess[[transformers.EfficientLoFTRImageProcessorPil.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']], **kwargs: *<class 'transformers.models.efficientloftr.image_processing_pil_efficientloftr.EfficientLoFTRImageProcessorKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientloftr/image_processing_pil_efficientloftr.py#L122)

**매개변수:**

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

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*, *선택*) : 입력의 각 이미지에 사용할 이미지 토큰의 수입니다. 하위 호환성을 위해 추가되었지만, 향후 모델에서는 프로세서 속성으로 설정해야 합니다.

do_grayscale (`bool`, *kwargs*, *선택 사항*, 기본값은 `self.do_grayscale`) : 이미지를 흑백으로 변환할지 여부입니다. `preprocess` 메서드의 `do_grayscale`로 재정의할 수 있습니다.

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

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

#### post_process_keypoint_matching[[transformers.EfficientLoFTRImageProcessorPil.post_process_keypoint_matching]]

```python
post_process_keypoint_matching(outputs: EfficientLoFTRKeypointMatchingOutput, target_sizes: transformers.utils.generic.TensorType | list[tuple], threshold: float = 0.0)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientloftr/image_processing_pil_efficientloftr.py#L163)

**매개변수:**

outputs (`EfficientLoFTRKeypointMatchingOutput`) : 모델의 원시 출력입니다.

target_sizes (`torch.Tensor` 또는 `List[Tuple[Tuple[int, int]]]`, *선택 사항*) : 배치 내 각 이미지의 대상 크기 `(height, width)`를 포함하는 `(batch_size, 2, 2)` 모양의 Tensor 또는 튜플의 튜플(`Tuple[int, int]`) 목록입니다. 이는 모든 처리를 수행하기 전의 원본 이미지 크기여야 합니다.

threshold (`float`, *선택 사항*, 기본값 0.0) : 점수가 낮은 매칭을 필터링하기 위한 임계값.

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

각 사전에 쌍의 첫 번째 및 두 번째 이미지의 keypoints, 매칭 점수, 매칭 인덱스가 포함된 사전 목록입니다.

`EfficientLoFTRKeypointMatchingOutput`의 원시 출력을 원래 이미지 크기에 대한 절대 좌표를 가진 키포인트, 점수 및 기술자 목록으로 변환합니다.

#### visualize_keypoint_matching[[transformers.EfficientLoFTRImageProcessorPil.visualize_keypoint_matching]]

```python
visualize_keypoint_matching(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], keypoint_matching_output: list)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientloftr/image_processing_pil_efficientloftr.py#L225)

**매개변수:**

images (`ImageInput`) : 플롯할 이미지 쌍. `EfficientLoFTRImageProcessor.preprocess`와 동일합니다. 픽셀 값이 0에서 255 범위로 이루어진 2개의 이미지 목록 또는 2개의 이미지 목록의 목록을 기대합니다.

keypoint_matching_output List[Dict[str, torch.Tensor]] : 후처리된 keypoint matching 출력

**반환값:** `List[PIL.Image.Image]`

각 이미지가 감지된 키포인트와 그들 간의 매칭을 포함하여 이미지 쌍을 나란히 포함하는 PIL 이미지 목록입니다.

감지된 키포인트와 그들 간의 매칭을 포함하여 이미지 쌍을 나란히 플롯합니다.

## EfficientLoFTRModel[[transformers.EfficientLoFTRModel]]

#### transformers.EfficientLoFTRModel[[transformers.EfficientLoFTRModel]]

```python
transformers.EfficientLoFTRModel(config: EfficientLoFTRConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientloftr/modeling_efficientloftr.py#L691)

**매개변수:**

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

이미지를 입력으로 받아 해당 이미지의 특징을 출력하는 EfficientLoFTR 모델.

이 모델은 [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.EfficientLoFTRModel.forward]]

```python
forward(pixel_values: Tensor, labels: typing.Optional[torch.LongTensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientloftr/modeling_efficientloftr.py#L702)

**매개변수:**

pixel_values (`torch.Tensor` of shape `(batch_size, num_channels, image_size, image_size)`) : The tensors corresponding to the input images. Pixel values can be obtained using [EfficientLoFTRImageProcessor](/docs/transformers/main/ko/model_doc/efficientloftr#transformers.EfficientLoFTRImageProcessor). See [EfficientLoFTRImageProcessor.__call__()](/docs/transformers/main/ko/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) for details (`processor_class` uses [EfficientLoFTRImageProcessor](/docs/transformers/main/ko/model_doc/efficientloftr#transformers.EfficientLoFTRImageProcessor) for processing images).

labels (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : masked language modeling loss를 계산하기 위한 라벨. 인덱스는 `[0, ..., config.vocab_size]` 범위 내이거나 -100이어야 합니다(`input_ids` docstring 참조). 인덱스가 `-100`으로 설정된 토큰은 무시(마스크)되며, loss는 `[0, ..., config.vocab_size]` 범위의 라벨을 가진 토큰에 대해서만 계산됩니다.

**반환값:** `BackboneOutput` 또는 `tuple(torch.Tensor)`

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

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

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

- **feature_maps** (`tuple(torch.Tensor)`, shape `(batch_size, num_channels, height, width)`) -- 각 단계의 feature maps.
- **hidden_states** (`tuple(torch.Tensor)`, *선택*, `output_hidden_states=True`가 전달되거나 `config.output_hidden_states=True`인 경우 반환) -- 백본에 따라 shape가 `(batch_size, sequence_length, hidden_size)` 또는 `(batch_size, num_channels, height, width)`인 `torch.Tensor` 튜플 (임베딩 출력 1개 + 각 레이어 출력 1개)

  각 단계의 출력에서 모델의 Hidden-states와 초기 임베딩 출력을 포함합니다.
- **attentions** (`tuple(torch.Tensor)`, *선택*, `output_attentions=True`가 전달되거나 `config.output_attentions=True`인 경우 반환) -- 각 레이어당 하나씩, shape가 `(batch_size, num_heads, sequence_length, sequence_length)`인 `torch.Tensor`의 튜플. backbone이 attention을 사용하는 경우에만 적용됩니다.

  self-attention 헤드에서 가중 평균을 계산하는 데 사용되는 attention softmax 이후의 attention 가중치입니다.

예:

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

>>> url = "https://github.com/magicleap/SuperGluePretrainedNetwork/blob/master/assets/phototourism_sample_images/london_bridge_78916675_4568141288.jpg?raw=true"
>>> with httpx.stream("GET", url) as response:
...     image1 = Image.open(BytesIO(response.read()))

>>> url = "https://github.com/magicleap/SuperGluePretrainedNetwork/blob/master/assets/phototourism_sample_images/london_bridge_19481797_2295892421.jpg?raw=true"
>>> with httpx.stream("GET", url) as response:
...     image2 = Image.open(BytesIO(response.read()))

>>> images = [image1, image2]

>>> processor = AutoImageProcessor.from_pretrained("zju-community/efficient_loftr")
>>> model = AutoModel.from_pretrained("zju-community/efficient_loftr")

>>> with torch.no_grad():
>>>     inputs = processor(images, return_tensors="pt")
>>>     outputs = model(**inputs)
```

## EfficientLoFTRForKeypointMatching[[transformers.EfficientLoFTRForKeypointMatching]]

#### transformers.EfficientLoFTRForKeypointMatching[[transformers.EfficientLoFTRForKeypointMatching]]

```python
transformers.EfficientLoFTRForKeypointMatching(config: EfficientLoFTRConfig)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientloftr/modeling_efficientloftr.py#L914)

**매개변수:**

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

이미지를 입력으로 받아 매칭 결과를 출력하는 EfficientLoFTR 모델.

이 모델은 [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.EfficientLoFTRForKeypointMatching.forward]]

```python
forward(pixel_values: Tensor, labels: typing.Optional[torch.LongTensor] = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[소스](https://github.com/huggingface/transformers/blob/main/src/transformers/models/efficientloftr/modeling_efficientloftr.py#L1279)

**매개변수:**

pixel_values (`torch.Tensor`, shape `(batch_size, num_channels, image_size, image_size)`) : 입력 이미지에 해당하는 텐서입니다. 픽셀 값은 `image_processor_class`를 사용하여 얻을 수 있습니다. 자세한 내용은 `image_processor_class.__call__`를 참조하세요 (`processor_class`는 이미지 처리에 `image_processor_class`를 사용합니다).

labels (`torch.LongTensor`, shape `(batch_size, sequence_length)`, *선택 사항*) : masked language modeling loss를 계산하기 위한 라벨. 인덱스는 `[0, ..., config.vocab_size]` 범위 내이거나 -100이어야 합니다(`input_ids` docstring 참조). 인덱스가 `-100`으로 설정된 토큰은 무시(마스크)되며, loss는 `[0, ..., config.vocab_size]` 범위의 라벨을 가진 토큰에 대해서만 계산됩니다.

**반환값:** `EfficientLoFTRKeypointMatchingOutput` 또는 `tuple(torch.Tensor)`

`EfficientLoFTRKeypointMatchingOutput` 또는 `torch.Tensor`의 튜플(`return_dict=False`이 전달되었거나 `config.return_dict=False`인 경우)로, 구성(`None`) 및 입력에 따라 다양한 요소를 포함합니다.

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

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

- **loss** (`torch.Tensor`, shape `(1,)`, *선택 사항*) -- 학습 중에 계산된 손실.
- **matches** (shape `(batch_size, 2, num_matches)`의 `torch.Tensor`) -- 다른 이미지에서 매칭된 keypoint의 인덱스.
- **matching_scores** (`torch.Tensor`, shape `(batch_size, 2, num_matches)`) -- 예측된 매치의 점수입니다.
- **keypoints** (`torch.Tensor`, shape `(batch_size, num_keypoints, 2)`) -- 주어진 이미지에서 예측된 keypoints의 절대 (x, y) 좌표.
- **hidden_states** (`tuple[torch.Tensor, ...]`, *선택*) -- 각 단계의 출력에 하나씩 포함된 `torch.Tensor` 튜플로, shape이 `(batch_size, 2, num_channels, num_keypoints)`이며, `output_hidden_states=True`가 전달되었거나 `config.output_hidden_states=True`인 경우 반환됩니다
- **attentions** (`tuple[torch.Tensor, ...]`, *선택 사항*) -- 각 레이어에 해당하는 `torch.Tensor` 튜플로, shape는 `(batch_size, 2, num_heads, num_keypoints, num_keypoints)`입니다. `output_attentions=True`가 전달되었거나 `config.output_attentions=True`인 경우 반환됩니다.

예:

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

>>> url = "https://github.com/magicleap/SuperGluePretrainedNetwork/blob/master/assets/phototourism_sample_images/london_bridge_78916675_4568141288.jpg?raw=true"
>>> with httpx.stream("GET", url) as response:
...     image1 = Image.open(BytesIO(response.read()))

>>> url = "https://github.com/magicleap/SuperGluePretrainedNetwork/blob/master/assets/phototourism_sample_images/london_bridge_19481797_2295892421.jpg?raw=true"
>>> with httpx.stream("GET", url) as response:
...     image2 = Image.open(BytesIO(response.read()))

>>> images = [image1, image2]

>>> processor = AutoImageProcessor.from_pretrained("zju-community/efficient_loftr")
>>> model = AutoModel.from_pretrained("zju-community/efficient_loftr")

>>> with torch.no_grad():
>>>     inputs = processor(images, return_tensors="pt")
>>>     outputs = model(**inputs)
```

