# SuperGlue

[SuperGlue](https://huggingface.co/papers/1911.11763) 是一种神经网络，通过联合寻找对应关系并剔除无法匹配的点，来匹配两组局部特征。其分配结果通过求解一个可微的最优传输问题来估计，该问题的代价由图神经网络预测。SuperGlue 引入了一种基于注意力的灵活上下文聚合机制，使其能够联合推理底层的 3D 场景和特征分配。与 [SuperPoint 模型](https://huggingface.co/magic-leap-community/superpoint) 配合使用时，它可以用于匹配两张图像并估计它们之间的位姿。该模型适用于图像匹配、单应性估计等任务。

您可以在 [Magic Leap Community](https://huggingface.co/magic-leap-community) 组织下找到所有原始的 SuperGlue 检查点。

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

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

```python
from transformers import pipeline

keypoint_matcher = pipeline(task="keypoint-matching", model="magic-leap-community/superglue_outdoor")

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, AutoModel

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("magic-leap-community/superglue_outdoor")
model = AutoModel.from_pretrained("magic-leap-community/superglue_outdoor", 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)
```

## 备注

- SuperGlue 同时对两张图像执行特征匹配，需要以图像对作为输入。

    ```python
    from transformers import AutoImageProcessor, AutoModel
    import torch
    from PIL import Image
    import requests

    processor = AutoImageProcessor.from_pretrained("magic-leap-community/superglue_outdoor")
    model = AutoModel.from_pretrained("magic-leap-community/superglue_outdoor", device_map="auto")

    # SuperGlue 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
    keypoints0 = outputs.keypoints0  # Keypoints in first image
    keypoints1 = outputs.keypoints1  # Keypoints in second image
    matches = outputs.matches        # Matching indices
    matching_scores = outputs.matching_scores  # Confidence scores
    ```

- 模型会为每个匹配输出对应的索引、关键点以及置信度分数。
- 为了更直观地可视化和分析，请使用 [SuperGlueImageProcessor.post_process_keypoint_matching()](/docs/transformers/main/zh/model_doc/superglue#transformers.SuperGlueImageProcessor.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
    processor.visualize_keypoint_matching(images, processed_outputs)
    ```

    

## 资源

- 有关更多示例和实现细节，请参阅 [SuperGlue 原始仓库](https://github.com/magicleap/SuperGluePretrainedNetwork)。

## SuperGlueConfig[[transformers.SuperGlueConfig]]

#### transformers.SuperGlueConfig[[transformers.SuperGlueConfig]]

```python
transformers.SuperGlueConfig(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, keypoint_detector_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, hidden_size: int = 256, keypoint_encoder_sizes: list[int] | None = None, gnn_layers_types: list[str] | None = None, num_attention_heads: int = 4, sinkhorn_iterations: int = 100, matching_threshold: float = 0.0, initializer_range: float = 0.02, is_decoder: bool = False, attention_probs_dropout_prob: int | float = 0.0)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/superglue/configuration_superglue.py#L24)

**参数：**

keypoint_detector_config (`Union[AutoConfig, dict]`，*可选*，默认为 `SuperPointConfig`)：关键点检测器的配置对象或字典。

hidden_size (`int`，*可选*，默认为 `256`)：隐藏表示的维度。

keypoint_encoder_sizes (`list[int]`, *可选*, 默认为 `[32, 64, 128, 256]`) : 关键点编码器层的尺寸。

gnn_layers_types (`list[str]`, *可选*, 默认为 `['self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross']`) : GNN 层的类型。必须是 'self' 或 'cross'。

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

sinkhorn_iterations (`int`，*可选*，默认为 100)：Sinkhorn 迭代的次数。

matching_threshold (`float`, *可选*, 默认值为 0.0) : 匹配阈值。

initializer_range (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

is_decoder (`bool`，*可选*，默认为 `False`)：模型是否用作解码器。如果为 `False`，则模型用作编码器。

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

这是用于存储 SuperglueModel 配置的类。它根据指定的参数实例化 Superglue 模型，并定义模型架构。使用默认值实例化配置，将得到与 [magic-leap-community/superglue_indoor](https://huggingface.co/magic-leap-community/superglue_indoor) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/main/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：
```python
>>> from transformers import SuperGlueConfig, SuperGlueModel

>>> # Initializing a SuperGlue superglue style configuration
>>> configuration = SuperGlueConfig()

>>> # Initializing a model from the superglue style configuration
>>> model = SuperGlueModel(configuration)

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

## SuperGlueImageProcessor[[transformers.SuperGlueImageProcessor]]

#### transformers.SuperGlueImageProcessor[[transformers.SuperGlueImageProcessor]]

```python
transformers.SuperGlueImageProcessor(**kwargs: *<class 'transformers.models.superglue.image_processing_superglue.SuperGlueImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/superglue/image_processing_superglue.py#L124)

**参数：**

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` 进行覆盖。

构建一个 SuperGlueImageProcessor 图像处理器。

#### preprocess[[transformers.SuperGlueImageProcessor.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.superglue.image_processing_superglue.SuperGlueImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/superglue/image_processing_superglue.py#L138)

**参数：**

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.SuperGlueImageProcessor.post_process_keypoint_matching]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/superglue/image_processing_superglue.py#L194)

**参数：**

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

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

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

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

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

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

#### visualize_keypoint_matching[[transformers.SuperGlueImageProcessor.visualize_keypoint_matching]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/superglue/image_processing_superglue.py#L262)

**参数：**

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

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

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

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

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

## SuperGlueImageProcessorPil[[transformers.SuperGlueImageProcessorPil]]

#### transformers.SuperGlueImageProcessorPil[[transformers.SuperGlueImageProcessorPil]]

```python
transformers.SuperGlueImageProcessorPil(**kwargs: *<class 'transformers.models.superglue.image_processing_pil_superglue.SuperGlueImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/superglue/image_processing_pil_superglue.py#L117)

**参数：**

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` 进行覆盖。

构建一个 SuperGlueImageProcessor 图像处理器。

#### preprocess[[transformers.SuperGlueImageProcessorPil.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.superglue.image_processing_pil_superglue.SuperGlueImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/superglue/image_processing_pil_superglue.py#L131)

**参数：**

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.SuperGlueImageProcessorPil.post_process_keypoint_matching]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/superglue/image_processing_pil_superglue.py#L172)

**参数：**

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

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

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

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

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

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

#### visualize_keypoint_matching[[transformers.SuperGlueImageProcessorPil.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/superglue/image_processing_pil_superglue.py#L243)

**参数：**

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

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

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

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

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

## SuperGlueForKeypointMatching[[transformers.SuperGlueForKeypointMatching]]

#### transformers.SuperGlueForKeypointMatching[[transformers.SuperGlueForKeypointMatching]]

```python
transformers.SuperGlueForKeypointMatching(config: SuperGlueConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/superglue/modeling_superglue.py#L486)

**参数：**

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

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

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.SuperGlueForKeypointMatching.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/superglue/modeling_superglue.py#L665)

**参数：**

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

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

output_attentions (`bool`, *可选*) : 是否返回所有注意力层的注意力张量。有关更多详细信息，请参阅返回张量中的 `attentions`。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

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

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

[SuperGlueForKeypointMatching](/docs/transformers/main/zh/model_doc/superglue#transformers.SuperGlueForKeypointMatching) 的 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) 坐标。
- **mask**（形状为 `(batch_size, num_keypoints)` 的 `torch.IntTensor`）-- 指示 matches 和 matching_scores 中哪些值是关键点匹配信息的掩码。
- **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:
...     image_1 = 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:
...     image_2 = Image.open(BytesIO(response.read()))

>>> images = [image_1, image_2]

>>> processor = AutoImageProcessor.from_pretrained("magic-leap-community/superglue_outdoor")
>>> model = AutoModel.from_pretrained("magic-leap-community/superglue_outdoor")

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

