Transformers documentation

LightGlue

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2023-06-23 在 HF papers 上发布,并于 2025-06-17 贡献至 Hugging Face Transformers。

PyTorch

LightGlue

LightGlue 是一种深度神经网络,用于学习跨图像匹配局部特征。它重新审视了 SuperGlue 中的多项设计决策,并推导出了简单但有效的改进。这些改进的累积效果使 LightGlue 在内存和计算方面更加高效,精度更高,且训练起来容易得多。与 SuperGlue 类似,该模型通过匹配从两张图像中提取的两组局部特征来工作,目标是比 SuperGlue 更快。配合 SuperPoint 模型,它可以用于匹配两张图像并估计它们之间的位姿。

您可以在 ETH-CVG 组织下找到所有原始的 LightGlue 检查点。

该模型由 stevenbucaille 贡献。

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

以下示例演示了如何使用 Pipeline 或 AutoModel 类在两张图像之间匹配关键点。

Pipeline
AutoModel
from transformers import pipeline


keypoint_matcher = pipeline(task="keypoint-matching", model="ETH-CVG/lightglue_superpoint")

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': ...}

备注

  • LightGlue 能够根据任务难度进行自适应调整。对于直观上易于匹配的图片对(例如,由于具有更大的视觉重叠或有限的外观变化),其推理速度会快得多。

    from transformers import AutoImageProcessor, AutoModel
    import torch
    from PIL import Image
    import requests
    
    processor = AutoImageProcessor.from_pretrained("ETH-CVG/lightglue_superpoint")
    model = AutoModel.from_pretrained("ETH-CVG/lightglue_superpoint", device_map="auto")
    
    # LightGlue 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
  • 模型会为每个匹配输出对应的索引、关键点以及置信度分数,与 SuperGlue 类似,但效率更高。

  • 为了获得更好的可视化和分析效果,请使用 LightGlueImageProcessor.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
    processor.visualize_keypoint_matching(images, processed_outputs)

资源

LightGlueConfig

class transformers.LightGlueConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonekeypoint_detector_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonedescriptor_dim: int = 256num_hidden_layers: int = 9num_attention_heads: int = 4num_key_value_heads: int | None = Nonedepth_confidence: float = 0.95width_confidence: float = 0.99filter_threshold: float = 0.1initializer_range: float = 0.02hidden_act: str = 'gelu'attention_dropout: float | int = 0.0attention_bias: bool = True )

参数

  • keypoint_detector_config (Union[AutoConfig, dict],可选,默认为 SuperPointConfig) — 关键点检测器的配置对象或字典。
  • descriptor_dim (int,可选,默认为 256) — 描述符的维度。
  • num_hidden_layers (int,可选,默认为 9) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 4) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_key_value_heads (int, 可选) — 这是用于实现 Grouped Query Attention 的 key_value 头数。如果 num_key_value_heads=num_attention_heads,模型将使用 Multi Head Attention (MHA);如果 num_key_value_heads=1,模型将使用 Multi Query Attention (MQA);否则使用 GQA。在将多头检查点转换为 GQA 检查点时,每个组的 key 和 value 头应通过对该组内所有原始头进行平均池化来构建。更多详情请参阅 这篇论文。如果未指定,则默认为 num_attention_heads。
  • depth_confidence (float,可选,默认值为 0.95) — 用于执行提前停止的置信度阈值
  • width_confidence (float,可选,默认值为 0.99) — 用于剪枝点的置信度阈值
  • filter_threshold (float,可选,默认值为 0.1) — 用于过滤匹配项的置信度阈值
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • attention_bias (bool,可选,默认为 True) — 在自注意力机制中,是否在查询、键、值以及输出投影层中使用偏置。

这是用于存储 LightGlueForKeypointMatching 配置的类。它根据指定的参数实例化 Lightglue 模型,并定义模型架构。使用默认值实例化配置,将得到与 ETH-CVG/lightglue_superpoint 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。

示例:

>>> from transformers import LightGlueConfig, LightGlueForKeypointMatching

>>> # Initializing a LightGlue style configuration
>>> configuration = LightGlueConfig()

>>> # Initializing a model from the LightGlue style configuration
>>> model = LightGlueForKeypointMatching(configuration)

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

LightGlueImageProcessor

class transformers.LightGlueImageProcessor

< >

( **kwargs: *<class 'transformers.models.lightglue.image_processing_lightglue.LightGlueImageProcessorKwargs'> )

参数

  • 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 中的一个值。仅当 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 进行覆盖。

构建一个 LightGlueImageProcessor 图像处理器。

预处理

< >

( 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.lightglue.image_processing_lightglue.LightGlueImageProcessorKwargs'> ) → ~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_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 为整数时,是否在调整大小时默认使用正方形图像。
  • 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

< >

( outputs: LightGlueKeypointMatchingOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple]threshold: float = 0.0 ) → list[Dict]

参数

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

返回值

list[Dict]

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

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

visualize_keypoint_matching

< >

( imageskeypoint_matching_output: list[dict[str, torch.Tensor]] ) → List[PIL.Image.Image]

参数

  • images — 要绘制的图像对。与 EfficientLoFTRImageProcessor.preprocess 相同。期望输入为包含 2 张图像的列表,或包含 2 张图像列表的列表,像素值范围为 0 到 255。
  • keypoint_matching_output (List[Dict[str, torch.Tensor]]) — 经过后处理的特征点匹配输出

返回值

List[PIL.Image.Image]

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

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

LightGlueImageProcessorPil

class transformers.LightGlueImageProcessorPil

< >

( **kwargs: *<class 'transformers.models.lightglue.image_processing_pil_lightglue.LightGlueImageProcessorKwargs'> )

参数

  • 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 中的一个值。仅当 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 进行覆盖。

构建一个 LightGlueImageProcessor 图像处理器。

预处理

< >

( 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.lightglue.image_processing_pil_lightglue.LightGlueImageProcessorKwargs'> ) → ~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_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 为整数时,是否在调整大小时默认使用正方形图像。
  • 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

< >

( outputs: LightGlueKeypointMatchingOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple]threshold: float = 0.0 ) → list[Dict]

参数

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

返回值

list[Dict]

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

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

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

参数

  • images (ImageInput) — 要绘制的图像对。与 LightGlueImageProcessor.preprocess 相同。期望输入为包含 2 张图像的列表,或包含 2 张图像列表的列表,像素值范围为 0 到 255。
  • keypoint_matching_output (List[Dict[str, torch.Tensor]]) — 经过后处理的特征点匹配输出

返回值

List[PIL.Image.Image]

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

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

LightGlueForKeypointMatching

class transformers.LightGlueForKeypointMatching

< >

( config: LightGlueConfig )

参数

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

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

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: Tensorlabels: typing.Optional[torch.LongTensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = None**kwargs ) → LightGlueKeypointMatchingOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 LightGlueImageProcessor 获取像素值。有关详细信息,请参阅 LightGlueImageProcessor.call()(processor_class 使用 LightGlueImageProcessor 处理图像)。
  • 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。

返回值

LightGlueKeypointMatchingOutput 或 tuple(torch.Tensor)

LightGlueKeypointMatchingOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(LightGlueConfig)和输入。

LightGlueForKeypointMatching 的 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) 坐标。
  • prune(形状为 (batch_size, num_keypoints) 的 torch.IntTensor)— 剪枝掩码,指示哪些关键点被移除以及在第几层移除。
  • mask(形状为 (batch_size, num_keypoints) 的 torch.BoolTensor)— 指示 matches、matching_scores、keypoints 和 prune 中哪些值属于关键点匹配信息的掩码。
  • hidden_states (Tuple[torch.Tensor, ...], 可选) — 当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回的 torch.Tensor 元组(每个阶段一个输出),形状为 (batch_size, 2, num_channels, num_keypoints)
  • attentions (Tuple[torch.Tensor, ...],可选) — 当传入 output_attentions=True 或 config.output_attentions=True 时返回的 torch.Tensor 元组(每层一个),形状为 (batch_size, 2, num_heads, num_keypoints, num_keypoints)
Update on GitHub