Transformers 文件
LightGlue
並獲得增強的文件體驗
開始使用
LightGlue
概述
LightGlue 模型由 Philipp Lindenberger、Paul-Edouard Sarlin 和 Marc Pollefeys 在 LightGlue: Local Feature Matching at Light Speed 中提出。
與 SuperGlue 類似,該模型包含匹配從兩幅影像中提取的兩組區域性特徵,其目標是比 SuperGlue 更快。與 SuperPoint 模型 結合使用時,它可以用於匹配兩幅影像並估計它們之間的姿態。該模型適用於影像匹配、單應性估計等任務。
論文摘要如下:
我們引入了 LightGlue,一個學習跨影像匹配區域性特徵的深度神經網路。我們重新審視了稀疏匹配領域最先進的 SuperGlue 的多項設計決策,並推匯出了簡單但有效的改進。這些改進共同使得 LightGlue 在記憶體和計算方面更高效,更準確,並且更容易訓練。一個關鍵特性是 LightGlue 能夠適應問題的難度:對於直觀上更容易匹配的影像對(例如,由於較大的視覺重疊或有限的外觀變化),推理速度會快得多。這為在 3D 重建等對延遲敏感的應用中部署深度匹配器開闢了令人興奮的前景。程式碼和訓練好的模型可在 此 URL 公開獲取。
如何使用
以下是使用該模型的一個快速示例。由於該模型是一個影像匹配模型,它需要成對的影像進行匹配。原始輸出包含關鍵點檢測器檢測到的關鍵點列表以及匹配及其相應的匹配分數列表。
from transformers import AutoImageProcessor, AutoModel
import torch
from PIL import Image
import requests
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("ETH-CVG/lightglue_superpoint")
model = AutoModel.from_pretrained("ETH-CVG/lightglue_superpoint")
inputs = processor(images, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
您可以使用 `LightGlueImageProcessor` 中的 `post_process_keypoint_matching` 方法以可讀格式獲取關鍵點和匹配。
image_sizes = [[(image.height, image.width) for image in images]]
outputs = processor.post_process_keypoint_matching(outputs, image_sizes, threshold=0.2)
for i, output in enumerate(outputs):
print("For the image pair", i)
for keypoint0, keypoint1, matching_score in zip(
output["keypoints0"], output["keypoints1"], output["matching_scores"]
):
print(
f"Keypoint at coordinate {keypoint0.numpy()} in the first image matches with keypoint at coordinate {keypoint1.numpy()} in the second image with a score of {matching_score}."
)
您可以透過向此方法提供原始影像和輸出,來視覺化影像之間的匹配。
processor.plot_keypoint_matching(images, outputs)
該模型由 stevenbucaille 貢獻。原始程式碼可以在這裡找到。
LightGlueConfig
class transformers.LightGlueConfig
< 源 >( 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 **kwargs )
引數
- keypoint_detector_config (
Union[AutoConfig, dict]
, 可選, 預設為SuperPointConfig
) — 關鍵點檢測器的配置物件或字典。 - descriptor_dim (
int
, 可選, 預設為 256) — 描述符的維度。 - num_hidden_layers (
int
, 可選, 預設為 9) — 自注意力和交叉注意力層的數量。 - num_attention_heads (
int
, 可選, 預設為 4) — 多頭注意力中的頭數。 - num_key_value_heads (
int
, 可選) — 用於實現分組查詢注意力的鍵值頭數量。如果num_key_value_heads=num_attention_heads
,模型將使用多頭注意力 (MHA);如果num_key_value_heads=1
,模型將使用多查詢注意力 (MQA),否則使用 GQA。當將多頭檢查點轉換為 GQA 檢查點時,每個分組鍵和值頭應透過對其組內的所有原始頭進行平均池化來構建。更多詳情請參閱此論文。如果未指定,將預設為num_attention_heads
。 - 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 (
float
, 可選, 預設為 0.0) — 注意力機率的 dropout 比率。 - attention_bias (
bool
, 可選, 預設為True
) — 在自注意力過程中,是否在查詢、鍵、值和輸出投影層中使用偏置。
這是用於儲存 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.config
LightGlueImageProcessor
class transformers.LightGlueImageProcessor
< 源 >( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: float = 0.00392156862745098 do_grayscale: bool = True **kwargs )
引數
- do_resize (
bool
, 可選, 預設為True
) — 控制是否將影像的 (height, width) 尺寸調整為指定的size
。可在preprocess
方法中透過do_resize
覆蓋。 - size (
dict[str, int]
可選, 預設為{"height" -- 480, "width": 640}
): 應用resize
後輸出影像的解析度。僅在do_resize
設定為True
時有效。可在preprocess
方法中透過size
覆蓋。 - resample (
PILImageResampling
, 可選, 預設為Resampling.BILINEAR
) — 如果調整影像大小,則使用的重取樣濾波器。可在preprocess
方法中透過resample
覆蓋。 - do_rescale (
bool
, 可選, 預設為True
) — 是否透過指定的rescale_factor
重新縮放影像。可在preprocess
方法中透過do_rescale
覆蓋。 - rescale_factor (
int
或float
, 可選, 預設為1/255
) — 如果重新縮放影像,則使用的縮放因子。可在preprocess
方法中透過rescale_factor
覆蓋。 - do_grayscale (
bool
, 可選, 預設為True
) — 是否將影像轉換為灰度。可在preprocess
方法中透過do_grayscale
覆蓋。
構建 LightGlue 影像處理器。
plot_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: LightGlueKeypointMatchingOutput )
將影像對與檢測到的關鍵點以及它們之間的匹配並排繪製出來。需要安裝 matplotlib。
post_process_keypoint_matching
< 源 >( outputs: LightGlueKeypointMatchingOutput target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple]] threshold: float = 0.0 ) → list[Dict]
引數
- outputs (
KeypointMatchingOutput
) — 模型的原始輸出。 - target_sizes (
torch.Tensor
或list[tuple[tuple[int, int]]]
, 可選) — 形狀為(batch_size, 2, 2)
的張量或包含批次中每張影像的目標尺寸(height, width)
的元組列表(tuple[int, int]
)。這必須是原始影像尺寸(在任何處理之前)。 - threshold (
float
, 可選, 預設為 0.0) — 過濾掉低分匹配的閾值。
返回
list[Dict]
字典列表,每個字典包含影像對中第一張和第二張影像的關鍵點、匹配分數和匹配索引。
將 KeypointMatchingOutput
的原始輸出轉換為關鍵點、分數和描述符的列表,其座標相對於原始影像尺寸。
preprocess
< 源 >( images do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample: Resampling = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_grayscale: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs )
引數
- images (
ImageInput
) — 要預處理的影像對。期望是包含 2 張影像的列表或包含 2 張影像列表的列表,畫素值範圍為 0 到 255。如果傳入的影像畫素值在 0 到 1 之間,請設定do_rescale=False
。 - do_resize (
bool
, 可選, 預設為self.do_resize
) — 是否調整影像大小。 - size (
dict[str, int]
, 可選, 預設為self.size
) — 應用resize
後輸出影像的尺寸。如果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
, 可選, 預設為self.resample
) — 如果調整影像大小,要使用的重取樣濾鏡。可以是PILImageResampling
的一種濾鏡。僅當do_resize
設定為True
時有效。 - do_rescale (
bool
, 可選, 預設為self.do_rescale
) — 是否將影像值縮放到 [0 - 1] 之間。 - rescale_factor (
float
, 可選, 預設為self.rescale_factor
) — 如果do_rescale
設定為True
,用於縮放影像的縮放因子。 - do_grayscale (
bool
, 可選, 預設為self.do_grayscale
) — 是否將影像轉換為灰度。 - return_tensors (
str
或TensorType
, 可選) — 要返回的張量型別。可以是以下之一:- 未設定:返回
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
:返回tf.Tensor
型別的批次。TensorType.PYTORCH
或'pt'
:返回torch.Tensor
型別的批次。TensorType.NUMPY
或'np'
:返回np.ndarray
型別的批次。TensorType.JAX
或'jax'
:返回jax.numpy.ndarray
型別的批次。
- 未設定:返回
- data_format (
ChannelDimension
或str
, 可選, 預設為ChannelDimension.FIRST
) — 輸出影像的通道維度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:影像格式為 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:影像格式為 (height, width, num_channels)。- 未設定:使用輸入影像的通道維度格式。
- input_data_format (
ChannelDimension
或str
, 可選) — 輸入影像的通道維度格式。如果未設定,將從輸入影像推斷通道維度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:影像格式為 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:影像格式為 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:影像格式為 (height, width)。
預處理一張或一批影像。
resize
< 來源 >( image: ndarray size: dict data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs )
引數
- image (
np.ndarray
) — 要調整大小的影像。 - size (
dict[str, int]
) — 形式為{"height": int, "width": int}
的字典,指定輸出影像的大小。 - data_format (
ChannelDimension
或str
, 可選) — 輸出影像的通道維度格式。如果未提供,將從輸入影像推斷。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:影像格式為 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:影像格式為 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:影像格式為 (height, width)。
- input_data_format (
ChannelDimension
或str
, 可選) — 輸入影像的通道維度格式。如果未設定,將從輸入影像推斷通道維度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:影像格式為 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:影像格式為 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:影像格式為 (height, width)。
調整影像大小。
- preprocess
- post_process_keypoint_matching
- plot_keypoint_matching
LightGlueForKeypointMatching
class transformers.LightGlueForKeypointMatching
< 來源 >( config: LightGlueConfig )
引數
- config (LightGlueConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化不載入與模型關聯的權重,只加載配置。請檢視 from_pretrained() 方法載入模型權重。
LightGlue 模型,以影像為輸入,輸出它們的匹配。
此模型繼承自 PreTrainedModel。請檢視超類文件,瞭解庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭等)。
此模型也是 PyTorch torch.nn.Module 子類。將其用作常規 PyTorch 模組,並參閱 PyTorch 文件以瞭解所有與一般使用和行為相關的事項。
forward
< 來源 >( pixel_values: FloatTensor labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None ) → transformers.models.lightglue.modeling_lightglue.LightGlueKeypointMatchingOutput
或 tuple(torch.FloatTensor)
引數
- pixel_values (形狀為
(batch_size, num_channels, image_size, image_size)
的torch.FloatTensor
) — 對應於輸入影像的張量。畫素值可以透過{image_processor_class}
獲取。有關詳細資訊,請參閱{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
處理影像)。 - labels (形狀為
(batch_size, sequence_length)
的torch.LongTensor
, 可選) — 用於計算掩碼語言模型損失的標籤。索引應在[0, ..., config.vocab_size]
或 -100 之間(請參閱input_ids
文件字串)。索引設定為-100
的標記將被忽略(掩碼),損失僅針對標籤在[0, ..., config.vocab_size]
中的標記計算。 - output_attentions (
bool
, 可選) — 是否返回所有注意力層的注意力張量。更多詳細資訊請參閱返回張量中的attentions
。 - output_hidden_states (
bool
, 可選) — 是否返回所有層的隱藏狀態。更多詳細資訊請參閱返回張量中的hidden_states
。
返回
transformers.models.lightglue.modeling_lightglue.LightGlueKeypointMatchingOutput
或 tuple(torch.FloatTensor)
transformers.models.lightglue.modeling_lightglue.LightGlueKeypointMatchingOutput
或 torch.FloatTensor
的元組(如果傳入 return_dict=False
或 config.return_dict=False
時),包含根據配置(LightGlueConfig)和輸入的不同元素。
- loss (形狀為
(1,)
的torch.FloatTensor
,可選) — 訓練期間計算的損失。 - matches (形狀為
(batch_size, 2, num_matches)
的torch.FloatTensor
) — 在另一影像中匹配的關鍵點索引。 - matching_scores (形狀為
(batch_size, 2, num_matches)
的torch.FloatTensor
) — 預測匹配的分數。 - keypoints (形狀為
(batch_size, num_keypoints, 2)
的torch.FloatTensor
) — 給定影像中預測關鍵點的絕對 (x, y) 座標。 - prune (形狀為
(batch_size, num_keypoints)
的torch.IntTensor
) — 剪枝掩碼,指示哪些關鍵點被移除以及在哪個層被移除。 - mask (形狀為
(batch_size, num_keypoints)
的torch.BoolTensor
) — 掩碼,指示匹配、匹配分數、關鍵點和剪枝中的哪些值是關鍵點匹配資訊。 - hidden_states (
Tuple[torch.FloatTensor, ...]
, 可選) —torch.FloatTensor
的元組(每個階段的輸出一個),形狀為(batch_size, 2, num_channels, num_keypoints)
,當傳入output_hidden_states=True
或config.output_hidden_states=True
時返回。 - attentions (
Tuple[torch.FloatTensor, ...]
, 可選) —torch.FloatTensor
的元組(每層一個),形狀為(batch_size, 2, num_heads, num_keypoints, num_keypoints)
,當傳入output_attentions=True
或config.output_attentions=True
時返回。
LightGlueForKeypointMatching forward 方法,覆蓋了 __call__
特殊方法。
儘管前向傳播的配方需要在此函式中定義,但此後應呼叫 Module
例項而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則默默地忽略它們。
- forward