Transformers 文档
LightGlue
并获得增强的文档体验
开始使用
该模型于 2023-06-23 发布,并于 2025-06-17 添加到 Hugging Face Transformers。
LightGlue
LightGlue 是一种深度神经网络,可学习跨图像匹配局部特征。它重新审视了 SuperGlue 的多项设计决策,并进行了简单但有效的改进。总的来说,这些改进使得 LightGlue 在内存和计算方面都更高效,更准确,并且训练起来更容易。与 SuperGlue 类似,该模型由匹配从两张图像提取的两组局部特征组成,目标是比 SuperGlue 更快。与 SuperPoint 模型配合使用,它可以用于匹配两张图像并估计它们之间的姿态。
您可以在 ETH-CVG 组织下找到所有原始 LightGlue 检查点。
该模型由 stevenbucaille 贡献。
点击右侧边栏中的 LightGlue 模型,了解更多关于如何将 LightGlue 应用于不同计算机视觉任务的示例。
下面的示例演示了如何使用 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") # LightGlue requires pairs of images images = [image1, image2] inputs = processor(images, return_tensors="pt") 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)

资源
- 有关更多示例和实现细节,请参阅 原始 LightGlue 存储库。
LightGlueConfig
class transformers.LightGlueConfig
< source >( keypoint_detector_config: SuperPointConfig = None descriptor_dim: int = 256 num_hidden_layers: int = 9 num_attention_heads: int = 4 num_key_value_heads = None depth_confidence: float = 0.95 width_confidence: float = 0.99 filter_threshold: float = 0.1 initializer_range: float = 0.02 hidden_act: str = 'gelu' attention_dropout = 0.0 attention_bias = True trust_remote_code: bool = False **kwargs )
参数
- keypoint_detector_config (
Union[AutoConfig, dict], optional, defaults toSuperPointConfig) — 关键点检测器的配置对象或字典。 - descriptor_dim (
int, optional, defaults to 256) — 描述符的维度。 - num_hidden_layers (
int, optional, defaults to 9) — 自注意和交叉注意层的数量。 - num_attention_heads (
int, optional, defaults to 4) — 多头注意力中的头数。 - num_key_value_heads (
int, optional) — 这是实现分组查询注意力 (Grouped Query Attention) 所需的 key_value 头数。如果num_key_value_heads=num_attention_heads,则模型将使用多头注意力 (MHA);如果num_key_value_heads=1,则模型将使用多查询注意力 (MQA);否则使用 GQA。在将多头检查点转换为 GQA 检查点时,每个分组的键和值头应通过对该分组内的所有原始头进行平均池化来构造。有关更多详细信息,请参阅 此论文。如果未指定,将默认为num_attention_heads。 - depth_confidence (
float, optional, defaults to 0.95) — 用于执行提前停止的置信度阈值。 - width_confidence (
float, optional, defaults to 0.99) — 用于剪枝点的置信度阈值。 - filter_threshold (
float, optional, defaults to 0.1) — 用于过滤匹配的置信度阈值。 - initializer_range (
float, optional, defaults to 0.02) — 初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - hidden_act (
str, optional, defaults to"gelu") — 隐藏层中要使用的激活函数。 - attention_dropout (
float, optional, defaults to 0.0) — 注意力概率的 dropout 比率。 - attention_bias (
bool, optional, defaults toTrue) — 是否在自注意力期间使用查询、键、值和输出投影层的偏置。 - trust_remote_code (
bool, optional, defaults toFalse) — 在使用 SuperPoint 以外的模型作为关键点检测器时,是否信任远程代码。
这是用于存储 LightGlueForKeypointMatching 配置的配置类。它用于根据指定的参数实例化 LightGlue 模型,定义模型架构。使用默认值实例化配置将生成与 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.configLightGlueImageProcessor
class transformers.LightGlueImageProcessor
< source >( do_resize: bool = True size: dict[str, int] | None = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: float = 0.00392156862745098 do_grayscale: bool = True **kwargs )
参数
- do_resize (
bool, optional, defaults toTrue) — Controls whether to resize the image’s (height, width) dimensions to the specifiedsize. Can be overridden bydo_resizein thepreprocessmethod. - size (
dict[str, int]optional, defaults to{"height" -- 480, "width": 640}): Resolution of the output image afterresizeis applied. Only has an effect ifdo_resizeis set toTrue. Can be overridden bysizein thepreprocessmethod. - resample (
PILImageResampling, optional, defaults toResampling.BILINEAR) — Resampling filter to use if resizing the image. Can be overridden byresamplein thepreprocessmethod. - do_rescale (
bool, optional, defaults toTrue) — Whether to rescale the image by the specified scalerescale_factor. Can be overridden bydo_rescalein thepreprocessmethod. - rescale_factor (
intorfloat, optional, defaults to1/255) — Scale factor to use if rescaling the image. Can be overridden byrescale_factorin thepreprocessmethod. - do_grayscale (
bool, optional, defaults toTrue) — Whether to convert the image to grayscale. Can be overridden bydo_grayscalein thepreprocessmethod.
构建一个 LightGlue 图像处理器。
preprocess
< source >( images do_resize: bool | None = None size: dict[str, int] | None = None resample: PIL.Image.Resampling | None = None do_rescale: bool | None = None rescale_factor: float | None = None do_grayscale: bool | None = None return_tensors: str | transformers.utils.generic.TensorType | None = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: str | transformers.image_utils.ChannelDimension | None = None **kwargs )
参数
- images (
ImageInput) — 要预处理的图像对。期望值为包含 2 个图像的列表,或包含 2 个图像的列表的列表,像素值范围为 0 到 255。如果输入像素值在 0 到 1 之间,请将do_rescale设置为False。 - do_resize (
bool, optional, defaults toself.do_resize) — 是否调整图像大小。 - size (
dict[str, int], optional, defaults toself.size) — 调整大小后的输出图像尺寸。如果size["shortest_edge"]>= 384,则图像将调整为(size["shortest_edge"], size["shortest_edge"])。否则,图像的较短边将匹配到int(size["shortest_edge"]/ crop_pct),然后图像将被裁剪为(size["shortest_edge"], size["shortest_edge"])。仅在do_resize设置为True时生效。 - resample (
PILImageResampling, optional, defaults toself.resample) — 调整图像大小时使用的重采样滤波器。可以是PILImageResampling、filters中的一个。仅在do_resize设置为True时生效。 - do_rescale (
bool, optional, defaults toself.do_rescale) — 是否将图像值重新缩放到 [0 - 1] 之间。 - rescale_factor (
float, optional, defaults toself.rescale_factor) — 如果设置do_rescale为True,则用于缩放图像的缩放因子。 - do_grayscale (
bool, optional, defaults toself.do_grayscale) — 是否将图像转换为灰度。 - return_tensors (
strorTensorType, optional) — 要返回的张量类型。可以是以下之一:- 未设置:返回
np.ndarray列表。 TensorType.PYTORCH或'pt':返回torch.Tensor类型的批次。TensorType.NUMPY或'np':返回np.ndarray类型的批次。
- 未设置:返回
- data_format (
ChannelDimensionorstr, optional, defaults toChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。"channels_last"或ChannelDimension.LAST:图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimensionorstr, optional) — 输入图像的通道维度格式。如果未设置,则通道维度格式将从输入图像推断。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。"channels_last"或ChannelDimension.LAST:图像格式为 (height, width, num_channels)。"none"或ChannelDimension.NONE:图像格式为 (height, width)。
预处理一张或一批图像。
post_process_keypoint_matching
< source >( outputs: LightGlueKeypointMatchingOutput target_sizes: transformers.utils.generic.TensorType | list[tuple] threshold: float = 0.0 ) → list[Dict]
参数
- outputs (
LightGlueKeypointMatchingOutput) — 模型的原始输出。 - target_sizes (
torch.Tensororlist[tuple[tuple[int, int]]], optional) — 形状为(batch_size, 2, 2)的张量或元组列表 (tuple[int, int]),其中包含批次中每个图像的目标尺寸(height, width)。这必须是原始图像尺寸(在任何处理之前)。 - threshold (
float, optional, defaults to 0.0) — 用于过滤掉得分低的匹配项的阈值。
返回
list[Dict]
一个字典列表,每个字典包含第一张和第二张图像中的关键点、匹配分数和匹配索引。
将 LightGlueKeypointMatchingOutput 的原始输出转换为以原始图像尺寸为绝对坐标的关键点、得分和描述符列表。
visualize_keypoint_matching
< source >( 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]
并排绘制图像对,以及检测到的关键点和它们之间的匹配。
LightGlueImageProcessorFast
class transformers.LightGlueImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.models.lightglue.image_processing_lightglue.LightGlueImageProcessorKwargs] )
构建一个快速的Lightglue图像处理器。
preprocess
< source >( 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.lightglue.image_processing_lightglue.LightGlueImageProcessorKwargs] ) → <class 'transformers.image_processing_base.BatchFeature'>
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list, list, list]) — 要预处理的图像。期望是单个图像或图像批次,像素值范围为 0 到 255。如果传入的像素值范围在 0 到 1 之间,请将do_rescale设置为False。 - do_convert_rgb (
bool | None.do_convert_rgb) — 是否将图像转换为 RGB。 - do_resize (
bool | None.do_resize) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 描述模型的最大输入尺寸。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 应用center_crop后输出图像的大小。 - resample (
Annotated[Union[PILImageResampling, int, NoneType], None]) — 调整图像大小时使用的重采样过滤器。它可以是PILImageResampling枚举之一。仅当do_resize设置为True时才有效。 - do_rescale (
bool | None.do_rescale) — 是否重新缩放图像。 - rescale_factor (
float | None.rescale_factor) — 如果设置了do_rescale=True,则用于重新缩放图像的缩放因子。 - do_normalize (
bool | None.do_normalize) — 是否进行归一化。 - image_mean (
float | list[float] | tuple[float, ...] | None.image_mean) — 用于归一化的图像均值。仅当do_normalize设置为True时有效。 - image_std (
float | list[float] | tuple[float, ...] | None.image_std) — 用于归一化的图像标准差。仅当do_normalize设置为True时有效。 - do_pad (
bool | None.do_pad) — 是否填充图像。填充是针对批次中最大的尺寸进行的,或者对每个图像进行固定大小的方形填充。确切的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 将图像填充到的大小({"height": int, "width" int})。必须大于预处理所提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True时应用。 - do_center_crop (
bool | None.do_center_crop) — 是否中心裁剪图像。 - data_format (
str | ~image_utils.ChannelDimension | None.data_format) — 只支持ChannelDimension.FIRST。为与慢速处理器兼容而添加。 - input_data_format (
str | ~image_utils.ChannelDimension | None.input_data_format) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"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]) — 用于处理图像的设备。如果未设置,则从输入图像推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None]) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool | None.disable_grouping) — 是否禁用按大小对图像进行分组,以便单独处理而非批处理。如果为 None,则当图像在 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,如下所述:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int | None.image_seq_length) — 用于每个图像的图像 token 数量。为向后兼容而添加,但应在未来模型中设置为处理器属性。 - do_grayscale (
bool, optional, defaults toTrue) — 是否将图像转换为灰度。可以通过preprocess方法中的do_grayscale覆盖。
返回
<class 'transformers.image_processing_base.BatchFeature'>
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。 - tensor_type (
Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。
post_process_keypoint_matching
< source >( outputs: LightGlueKeypointMatchingOutput target_sizes: transformers.utils.generic.TensorType | list[tuple] threshold: float = 0.0 ) → list[Dict]
参数
- outputs (
LightGlueKeypointMatchingOutput) — 模型的原始输出。 - target_sizes (
torch.Tensororlist[tuple[tuple[int, int]]], optional) — 形状为(batch_size, 2, 2)的张量或形状为 (height, width) 的目标大小元组列表(tuple[int, int])。这必须是原始图像大小(在任何处理之前)。 - threshold (
float, optional, defaults to 0.0) — 用于过滤低分匹配的阈值。
返回
list[Dict]
一个字典列表,每个字典包含第一张和第二张图像中的关键点、匹配分数和匹配索引。
将 LightGlueKeypointMatchingOutput 的原始输出转换为以原始图像尺寸为绝对坐标的关键点、得分和描述符列表。
visualize_keypoint_matching
< 源 >( images keypoint_matching_output: list ) → List[PIL.Image.Image]
并排绘制图像对,以及检测到的关键点和它们之间的匹配。
LightGlueForKeypointMatching
class transformers.LightGlueForKeypointMatching
< 源 >( config: LightGlueConfig )
参数
- config (LightGlueConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只加载配置。有关详细信息,请查看 `from_pretrained()` 方法以加载模型权重。
LightGlue 模型,接收图像作为输入并输出它们的匹配结果。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< 源 >( pixel_values: FloatTensor labels: torch.LongTensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None **kwargs )
参数
- pixel_values (
torch.FloatTensor, 形状为(batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。像素值可以使用 LightGlueImageProcessorFast 获得。有关详细信息,请参阅 LightGlueImageProcessorFast.call()(processor_class使用 LightGlueImageProcessorFast 处理图像)。 - 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。
LightGlueForKeypointMatching 的前向方法,覆盖 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。