# EfficientLoFTR

[EfficientLoFTR](https://huggingface.co/papers/2403.04765) 是一种高效的无检测器局部特征匹配方法，能够以接近稀疏匹配的速度在图像间生成半稠密匹配。它在原始 [LoFTR](https://huggingface.co/papers/2104.00680) 架构的基础上，针对效率和精度进行了显著改进。其核心创新在于一种结合自适应 token 选择的聚合注意力机制，使模型速度比 LoFTR 快约 2.5 倍，同时实现了更高的精度。EfficientLoFTR 在速度上甚至能够超越 [SuperPoint](./superpoint) + [LightGlue](./lightglue) 等最先进的高效稀疏匹配流水线，因此适用于图像检索和 3D 重建等大规模或对延迟敏感的应用场景。

> [!TIP]
> 该模型由 [stevenbucaille](https://huggingface.co/stevenbucaille) 贡献。
>
> 点击右侧边栏中的 EfficientLoFTR 模型，以查看将 EfficientLoFTR 应用于不同计算机视觉任务的更多示例。

以下示例演示了如何使用 [Pipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.Pipeline) 或 [AutoModel](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoModel) 类在两张图像之间匹配关键点。

```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)
```

## 备注

- EfficientLoFTR 旨在保持高精度的同时提升效率。它采用聚合注意力机制与自适应 token 选择，相较于原始 LoFTR 降低了计算开销。

    ```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
    ```

- 该模型生成半稠密匹配，在匹配密度与计算效率之间取得了良好的平衡。它在处理大视角变化和纹理匮乏的场景方面表现出色。

- 为了更直观地可视化和分析，请使用 [post_process_keypoint_matching()](/docs/transformers/v5.23.0/zh/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 采用了一种新颖的两阶段相关性层，以实现精确的亚像素对应，从而改进了原始 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/v5.23.0/src/transformers/models/efficientloftr/configuration_efficientloftr.py#L24)

**参数：**

stage_num_blocks (`List`, *可选*, 默认为 [1, 2, 4, 14]) : 每个阶段中的块数

out_features (`list[int]`, *可选*) : 要从主干网络返回的中间隐藏状态（特征图）的名称。可以是 `"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)：融合网络中查询状态聚合的核大小

kv_aggregation_kernel_size (`int`, *可选*，默认为 4)：融合网络中键和值状态聚合的核大小

q_aggregation_stride (`int`, *可选*，默认为 4)：融合网络中查询状态聚合的步长

kv_aggregation_stride (`int`，*可选*，默认为 4)：融合网络中键和值状态聚合的步长

num_attention_layers (`int`，*可选*，默认为 4)：LocalFeatureTransformer 中注意力层的数量

num_attention_heads (`int`，*可选*，默认为 `8`)：Transformer 解码器中每个注意力层的注意力头数量。

attention_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：注意力概率的 dropout 比率。

attention_bias (`bool`，*可选*，默认为 `False`)：在自注意力机制中，是否在查询、键、值和输出投影层中使用偏置。

mlp_activation_function (`str`, *可选*, 默认为 `"leaky_relu"`) : 注意力 mlp 层中使用的激活函数。

coarse_matching_skip_softmax (`bool`, *可选*, 默认为 `False`) : 是否在粗匹配步骤中跳过 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)：用于在第一和第二精细匹配阶段划分精细特征的切片大小。

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) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/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/v5.23.0/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 为整数时，是否在调整大小时默认使用正方形图像。

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` 中的一个值。仅当 `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*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

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/v5.23.0/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` 中的一个值。仅当 `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*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

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]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

#### 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/v5.23.0/src/transformers/models/efficientloftr/image_processing_efficientloftr.py#L180)

**参数：**

outputs (`EfficientLoFTRKeypointMatchingOutput`)：模型的原始输出。

target_sizes (`torch.Tensor` 或 `List[Tuple[Tuple[int, int]]]`，*可选*)：形状为 `(batch_size, 2, 2)` 的张量，或包含元组列表（`Tuple[int, int]`），其中包含批次中每张图片的目标尺寸 `(height, width)`。这必须是原始图像尺寸（在任何处理之前）。

threshold (`float`, *可选*，默认为 0.0)：用于过滤低分匹配的阈值。

**返回：** `List[Dict]`

一个字典列表，每个字典包含该图像对中第一张和第二张图像的关键点、匹配分数以及匹配索引。

将 `EfficientLoFTRKeypointMatchingOutput` 的原始输出转换为关键点、分数和描述符列表，其坐标为相对于原始图像尺寸的绝对坐标。

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

```python
visualize_keypoint_matching(images, keypoint_matching_output: list[dict[str, torch.Tensor]])
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/efficientloftr/image_processing_efficientloftr.py#L239)

**参数：**

images : 要绘制的图像对。与 `EfficientLoFTRImageProcessor.preprocess` 相同。期望输入为包含 2 张图像的列表，或包含 2 个图像列表的列表，像素值范围为 0 到 255。

keypoint_matching_output (List[Dict[str, torch.Tensor]]]) : 后处理的关键点匹配输出

**返回：** `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/v5.23.0/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 为整数时，是否在调整大小时默认使用正方形图像。

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` 中的一个值。仅当 `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*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

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/v5.23.0/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` 中的一个值。仅当 `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*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

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]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

#### 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/v5.23.0/src/transformers/models/efficientloftr/image_processing_pil_efficientloftr.py#L163)

**参数：**

outputs (`EfficientLoFTRKeypointMatchingOutput`)：模型的原始输出。

target_sizes (`torch.Tensor` 或 `List[Tuple[Tuple[int, int]]]`，*可选*)：形状为 `(batch_size, 2, 2)` 的张量，或包含元组列表（`Tuple[int, int]`），其中包含批次中每张图片的目标尺寸 `(height, width)`。这必须是原始图像尺寸（在任何处理之前）。

threshold (`float`, *可选*，默认为 0.0)：用于过滤低分匹配的阈值。

**返回：** `List[Dict]`

一个字典列表，每个字典包含该图像对中第一张和第二张图像的关键点、匹配分数以及匹配索引。

将 `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[dict[str, 'torch.Tensor']])
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/efficientloftr/image_processing_pil_efficientloftr.py#L225)

**参数：**

images (`ImageInput`) : 要绘制的图像对。与 `EfficientLoFTRImageProcessor.preprocess` 相同。期望输入为包含 2 张图像的列表，或包含 2 张图像列表的列表，像素值范围为 0 到 255。

keypoint_matching_output (List[Dict[str, torch.Tensor]]]) : 后处理的关键点匹配输出

**返回：** `List[PIL.Image.Image]`

一个 PIL 图像列表，每个图像并排显示图像对，并包含检测到的关键点以及它们之间的匹配关系。

并排绘制图像对，同时显示检测到的关键点以及它们之间的匹配关系。

## EfficientLoFTRModel[[transformers.EfficientLoFTRModel]]

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

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

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/efficientloftr/modeling_efficientloftr.py#L691)

**参数：**

config ([EfficientLoFTRConfig](/docs/transformers/v5.23.0/zh/model_doc/efficientloftr#transformers.EfficientLoFTRConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化并不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

EfficientLoFTR 模型以图像作为输入，并输出图像的特征。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/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/v5.23.0/src/transformers/models/efficientloftr/modeling_efficientloftr.py#L702)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 [EfficientLoFTRImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/efficientloftr#transformers.EfficientLoFTRImageProcessor) 获取像素值。有关详细信息，请参阅 [EfficientLoFTRImageProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [EfficientLoFTRImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/efficientloftr#transformers.EfficientLoFTRImageProcessor) 处理图像）。

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于计算掩码语言建模损失的标签。索引值应在 `[0, ..., config.vocab_size]` 范围内，或为 -100（参见 `input_ids` 的文档字符串）。索引值设为 `-100` 的 token 将被忽略（即被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。

**返回：** `BackboneOutput` 或 `tuple(torch.Tensor)`

`BackboneOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[EfficientLoFTRConfig](/docs/transformers/v5.23.0/zh/model_doc/efficientloftr#transformers.EfficientLoFTRConfig)）和输入。

[EfficientLoFTRModel](/docs/transformers/v5.23.0/zh/model_doc/efficientloftr#transformers.EfficientLoFTRModel) 的 forward 方法会重写 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **feature_maps**（形状为 `(batch_size, num_channels, height, width)` 的 `tuple(torch.Tensor)`）-- 各阶段的特征图。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（包含嵌入层的输出以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)` 或 `(batch_size, num_channels, height, width)`，具体取决于骨干网络。

  模型在每个阶段输出处的隐藏状态，以及初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。仅当主干网络使用注意力机制时适用。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```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/v5.23.0/src/transformers/models/efficientloftr/modeling_efficientloftr.py#L914)

**参数：**

config ([EfficientLoFTRConfig](/docs/transformers/v5.23.0/zh/model_doc/efficientloftr#transformers.EfficientLoFTRConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化并不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

EfficientLoFTR 模型以图像作为输入，并输出它们之间的匹配结果。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/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/v5.23.0/src/transformers/models/efficientloftr/modeling_efficientloftr.py#L1279)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（`processor_class` 使用 `image_processor_class` 处理图像）。

labels (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于计算掩码语言建模损失的标签。索引值应在 `[0, ..., config.vocab_size]` 范围内，或为 -100（参见 `input_ids` 的文档字符串）。索引值设为 `-100` 的 token 将被忽略（即被掩码），损失仅针对标签在 `[0, ..., config.vocab_size]` 范围内的 token 进行计算。

**返回：** `EfficientLoFTRKeypointMatchingOutput` 或 `tuple(torch.Tensor)`

`EfficientLoFTRKeypointMatchingOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），包含根据配置（`None`）和输入而定的各种元素。

[EfficientLoFTRForKeypointMatching](/docs/transformers/v5.23.0/zh/model_doc/efficientloftr#transformers.EfficientLoFTRForKeypointMatching) 的 forward 方法重写了 `__call__` 特殊方法。

尽管前向传播的实现需要在此函数中定义，但之后应调用 `Module` 实例，而不是直接调用此函数，因为前者会负责执行预处理和后处理步骤，而后者会静默地忽略这些步骤。

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*) -- 训练期间计算的损失。
- **matches**（形状为 `(batch_size, 2, num_matches)` 的 `torch.Tensor`）-- 在另一张图像中匹配到的关键点索引。
- **matching_scores**（形状为 `(batch_size, 2, num_matches)` 的 `torch.Tensor`）-- 预测匹配项的分数。
- **keypoints**（形状为 `(batch_size, num_keypoints, 2)` 的 `torch.Tensor`）-- 给定图像中预测关键点（keypoints）的绝对 (x, y) 坐标。
- **hidden_states** (`tuple[torch.Tensor, ...]`, *可选*) -- 形状为 `(batch_size, 2, num_channels, num_keypoints)` 的 `torch.Tensor` 元组（每个阶段一个输出），在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回
- **attentions** (`tuple[torch.Tensor, ...]`，*可选*) -- 形状为 `(batch_size, 2, num_heads, num_keypoints, num_keypoints)` 的 `torch.Tensor` 元组（每层一个），在传入 `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)
```

