Transformers 文档

EfficientLoFTR

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2024 年 3 月 7 日在 HF 论文中发布,并于 2025 年 7 月 22 日贡献给 Hugging Face Transformers。

PyTorch

EfficientLoFTR

EfficientLoFTR 是一种高效的无检测器局部特征匹配方法,它能以类似稀疏匹配的速度产生半稠密(semi-dense)的图像匹配结果。它基于原始的 LoFTR 架构构建,但在效率和准确性方面进行了重大改进。其核心创新在于一种具有自适应 Token 选择机制的聚合注意力机制,使得该模型比 LoFTR 快约 2.5 倍,同时达到了更高的准确率。EfficientLoFTR 在速度上甚至可以超越 SuperPoint + LightGlue 等先进的高效稀疏匹配流程,因此非常适合大规模或对延迟敏感的应用场景,如图像检索和三维重建。

该模型由 stevenbucaille 贡献。

点击右侧边栏中的 EfficientLoFTR 模型,查看更多将 EfficientLoFTR 应用于不同计算机视觉任务的示例。

下方的示例演示了如何使用 PipelineAutoModel 类在两张图像之间匹配关键点。

流水线
自动模型
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': ...}

注意事项

  • EfficientLoFTR 在保持高精度的同时追求极致效率。它使用了一种带有自适应 Token 选择的聚合注意力机制,相比原始 LoFTR 降低了计算开销。

    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() 方法,以更易读的格式获取匹配结果。

    # 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}")
  • 使用内置的绘图功能可视化图像之间的匹配。

    # Easy visualization using the built-in plotting method
    visualized_images = processor.visualize_keypoint_matching(images, processed_outputs)
  • EfficientLoFTR 使用了一种新型的两阶段相关层,实现了精确的亚像素对应关系,改进了原始 LoFTR 的精细相关模块。

资源

EfficientLoFTRConfig

class transformers.EfficientLoFTRConfig

< >

( transformers_version: str | None = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = 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: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = 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 )

参数

  • stage_num_blocks (List, 可选,默认为 [1, 2, 4, 14]) — 每个阶段的块数。
  • out_features (list[int], 可选) — 从骨干网络返回的中间隐藏状态(特征图)的名称。可以是 "stem", "stage1", "stage2" 等中的一个。
  • stage_stride (List, 可选,默认为 [2, 1, 2, 2]) — 每个阶段使用的步幅(stride)。
  • hidden_size (int, 可选,默认为 256) — 隐藏表示的维度。
  • activation_function (str, 可选,默认为 relu) — 解码器中的非线性激活函数(函数或字符串)。例如:"gelu", "relu", "silu" 等。
  • q_aggregation_kernel_size (int, 可选,默认为 4) — 融合网络中查询(query)状态聚合的卷积核大小。
  • kv_aggregation_kernel_size (int, 可选,默认为 4) — 融合网络中键(key)和值(value)状态聚合的卷积核大小。
  • q_aggregation_stride (int, 可选,默认为 4) — 融合网络中查询(query)状态聚合的步幅。
  • kv_aggregation_stride (int, 可选,默认为 4) — 融合网络中键(key)和值(value)状态聚合的步幅。
  • num_attention_layers (int, 可选,默认为 4) — LocalFeatureTransformer 中的注意力层数量。
  • num_attention_heads (int, 可选,默认为 8) — Transformer 解码器中每个注意力层的注意力头数。
  • attention_dropout (Union[float, int], 可选,默认为 0.0) — 注意力概率的 Dropout 比率。
  • attention_bias (bool, 可选,默认为 False) — 是否在自注意力过程中的查询(query)、键(key)、值(value)和输出投影层中使用偏置(bias)。
  • 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) — 应用于粗相似度矩阵的温度(temperature)参数。
  • 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 时进行缩放所可选的参数。
  • 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 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。阅读 PreTrainedConfig 的文档以获取更多信息。

示例

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

class transformers.EfficientLoFTRImageProcessor

< >

( **kwargs: typing_extensions.Unpack[transformers.models.efficientloftr.image_processing_efficientloftr.EfficientLoFTRImageProcessorKwargs] )

参数

  • do_grayscale (bool, kwargs, 可选, 默认值为 self.do_grayscale) — 是否将图像转换为灰度。可以在 preprocess 方法中通过 do_grayscale 参数覆盖。
  • **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。上述已列出模型特定的 kwargs;有关支持参数的完整列表,请参见 TypedDict 类。

构造一个 EfficientLoFTRImageProcessor 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] **kwargs: typing_extensions.Unpack[transformers.models.efficientloftr.image_processing_efficientloftr.EfficientLoFTRImageProcessorKwargs] ) ~image_processing_base.BatchFeature

参数

  • 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_grayscale (bool, kwargs, 可选, 默认值为 self.do_grayscale) — 是否将图像转换为灰度。可以在 preprocess 方法中通过 do_grayscale 参数覆盖。
  • return_tensors (strTensorType, 可选) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。上述已列出模型特定的 kwargs;有关支持参数的完整列表,请参见 TypedDict 类。

返回

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。

post_process_keypoint_matching

< >

( outputs: EfficientLoFTRKeypointMatchingOutput target_sizes: transformers.utils.generic.TensorType | list[tuple] threshold: float = 0.0 ) List[Dict]

参数

  • outputs (EfficientLoFTRKeypointMatchingOutput) — 模型的原始输出。
  • target_sizes (torch.TensorList[Tuple[Tuple[int, int]]], 可选) — 形状为 (batch_size, 2, 2) 的张量,或者包含批中每张图像目标大小 (height, width) 的元组列表 (Tuple[int, int])。这必须是原始图像大小(在任何处理之前)。
  • threshold (float, 可选, 默认值为 0.0) — 用于过滤掉低分匹配的阈值。

返回

List[Dict]

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

EfficientLoFTRKeypointMatchingOutput 的原始输出转换为关键点、分数和描述符列表,且坐标相对于原始图像大小是绝对的。

visualize_keypoint_matching

< >

( images keypoint_matching_output: list ) List[PIL.Image.Image]

参数

  • images — 待绘图的图像对。与 EfficientLoFTRImageProcessor.preprocess 相同。期望输入 2 张图像的列表,或 2 张图像组成的列表的列表,像素值范围在 0 到 255 之间。
  • keypoint_matching_output (List[Dict[str, torch.Tensor]]) — 经过后处理的关键点匹配输出。

返回

List[PIL.Image.Image]

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

并排绘制图像对,以及检测到的关键点和它们之间的匹配。

EfficientLoFTRImageProcessorPil

class transformers.EfficientLoFTRImageProcessorPil

< >

( **kwargs: typing_extensions.Unpack[transformers.models.efficientloftr.image_processing_pil_efficientloftr.EfficientLoFTRImageProcessorKwargs] )

参数

  • do_grayscale (bool, kwargs, optional, defaults to self.do_grayscale) — 是否将图像转换为灰度。可以通过 preprocess 方法中的 do_grayscale 参数进行覆盖。
  • **kwargs (ImagesKwargs, optional) — 其他图像预处理选项。模型特定的 kwargs 在上面列出;请参阅 TypedDict 类以获取支持参数的完整列表。

构造一个 EfficientLoFTRImageProcessor 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] **kwargs: typing_extensions.Unpack[transformers.models.efficientloftr.image_processing_pil_efficientloftr.EfficientLoFTRImageProcessorKwargs] ) ~image_processing_base.BatchFeature

参数

  • 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_grayscale (bool, kwargs, optional, defaults to self.do_grayscale) — 是否将图像转换为灰度。可以通过 preprocess 方法中的 do_grayscale 参数进行覆盖。
  • return_tensors (strTensorType, optional) — 如果设置为 'pt',则返回堆叠的张量;否则返回张量列表。
  • **kwargs (ImagesKwargs, optional) — 其他图像预处理选项。模型特定的 kwargs 在上面列出;请参阅 TypedDict 类以获取支持参数的完整列表。

返回

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。

post_process_keypoint_matching

< >

( outputs: EfficientLoFTRKeypointMatchingOutput target_sizes: transformers.utils.generic.TensorType | list[tuple] threshold: float = 0.0 ) List[Dict]

参数

  • outputs (EfficientLoFTRKeypointMatchingOutput) — 模型的原始输出。
  • target_sizes (torch.TensorList[Tuple[Tuple[int, int]]], optional) — 包含批次中每张图像目标尺寸 (高度, 宽度) 的张量(形状为 (batch_size, 2, 2))或元组列表。这必须是原始图像尺寸(在进行任何处理之前)。
  • threshold (float, optional, defaults to 0.0) — 用于过滤低分匹配项的阈值。

返回

List[Dict]

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

EfficientLoFTRKeypointMatchingOutput 的原始输出转换为关键点、分数和描述符列表,且坐标相对于原始图像大小是绝对的。

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 ) List[PIL.Image.Image]

参数

  • images (ImageInput) — 待绘制的图像对。与 EfficientLoFTRImageProcessor.preprocess 相同。期望输入一个包含 2 张图像的列表,或者一个包含多个“包含 2 张图像的列表”的列表,且像素值范围为 0 到 255。
  • keypoint_matching_output (List[Dict[str, torch.Tensor]]) — 经过后处理的关键点匹配输出。

返回

List[PIL.Image.Image]

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

并排绘制图像对,以及检测到的关键点和它们之间的匹配。

EfficientLoFTRModel

class transformers.EfficientLoFTRModel

< >

( config: EfficientLoFTRConfig )

参数

  • config (EfficientLoFTRConfig) — 具有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

EfficientLoFTR 模型,接收图像作为输入,并输出图像的特征。

该模型继承自 PreTrainedModel。请查看超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: FloatTensor labels: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) BackboneOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。像素值可以使用 EfficientLoFTRImageProcessor 获取。详细信息请参阅 EfficientLoFTRImageProcessor.__call__()processor_class 使用 EfficientLoFTRImageProcessor 来处理图像)。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length), optional) — 用于计算掩码语言模型损失的标签。索引应在 [0, ..., config.vocab_size] 范围内,或为 -100(请参阅 input_ids 文档字符串)。索引设置为 -100 的标记将被忽略(掩码),损失仅针对标签在 [0, ..., config.vocab_size] 范围内的标记进行计算。

返回

BackboneOutputtuple(torch.FloatTensor)

BackboneOutputtorch.FloatTensor 的元组(如果传入 return_dict=False 或当 config.return_dict=False 时),根据配置(EfficientLoFTRConfig)和输入,包含不同的元素。

EfficientLoFTRModel 的 forward 方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

  • feature_maps (tuple(torch.FloatTensor) of shape (batch_size, num_channels, height, width)) — 阶段的特征图。

  • hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — torch.FloatTensor 元组(一个用于嵌入输出 + 每个层输出一个)的形状为 (batch_size, sequence_length, hidden_size)(batch_size, num_channels, height, width),具体取决于主干网络。

    模型在每个阶段输出的隐藏状态以及初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — torch.FloatTensor 元组(每个层一个)的形状为 (batch_size, num_heads, sequence_length, sequence_length)。仅当主干网络使用注意力时适用。

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

示例

>>> from transformers import AutoImageProcessor, AutoModel
>>> import torch
>>> from PIL import Image
>>> 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

class transformers.EfficientLoFTRForKeypointMatching

< >

( config: EfficientLoFTRConfig )

参数

  • config (EfficientLoFTRConfig) — 具有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

EfficientLoFTR 模型,接收图像作为输入,并输出它们的匹配结果。

该模型继承自 PreTrainedModel。请查看超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: FloatTensor labels: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) EfficientLoFTRKeypointMatchingOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (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 的标记将被忽略(掩码),损失仅对标签在 [0, ..., config.vocab_size] 范围内的标记进行计算。

返回

EfficientLoFTRKeypointMatchingOutputtuple(torch.FloatTensor)

一个 EfficientLoFTRKeypointMatchingOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),根据配置 (None) 和输入包含各种元素。

EfficientLoFTRForKeypointMatching 前向传播方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

  • loss (形状为 (1,)torch.FloatTensor可选) — 训练期间计算的损失。
  • matches (torch.FloatTensor,形状为 (batch_size, 2, num_matches)) — 另一张图像中匹配的关键点的索引。
  • matching_scores (torch.FloatTensor,形状为 (batch_size, 2, num_matches)) — 预测匹配的分数。
  • keypoints (torch.FloatTensor,形状为 (batch_size, num_keypoints, 2)) — 给定图像中预测关键点的绝对 (x, y) 坐标。
  • hidden_states (tuple[torch.FloatTensor, ...]可选) — torch.FloatTensor 元组(每个阶段的输出各一个),形状为 (batch_size, 2, num_channels, num_keypoints),当传递 output_hidden_states=Trueconfig.output_hidden_states=True 时返回。
  • attentions (tuple[torch.FloatTensor, ...]可选) — torch.FloatTensor 元组(每个层各一个),形状为 (batch_size, 2, num_heads, num_keypoints, num_keypoints),当传递 output_attentions=Trueconfig.output_attentions=True 时返回。

示例

>>> from transformers import AutoImageProcessor, AutoModel
>>> import torch
>>> from PIL import Image
>>> 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)
在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.