Transformers 文档
SuperPoint
并获得增强的文档体验
开始使用
SuperPoint
概述
SuperPoint 模型在 Daniel DeTone、Tomasz Malisiewicz 和 Andrew Rabinovich 的 SuperPoint: 自监督兴趣点检测与描述 中被提出。
该模型是全卷积网络自监督训练的结果,用于兴趣点检测和描述。该模型能够检测在同应变换下可重复的兴趣点,并为每个点提供描述符。该模型的独立使用有限,但可作为特征提取器用于其他任务,如单应性估计、图像匹配等。
论文摘要如下:
本文提出了一种自监督框架,用于训练适用于计算机视觉中大量多视图几何问题的兴趣点检测器和描述符。与基于补丁的神经网络不同,我们的全卷积模型在全尺寸图像上操作,并在一次前向传播中联合计算像素级兴趣点位置和相关描述符。我们引入了 Homographic Adaptation,一种多尺度、多单应性方法,用于提高兴趣点检测的可重复性并执行跨域适应(例如,从合成到真实)。我们的模型在 MS-COCO 通用图像数据集上使用 Homographic Adaptation 进行训练时,能够比初始预适应的深度模型和任何其他传统角点检测器更重复地检测出更丰富的兴趣点集。最终系统在 HPatches 上与 LIFT、SIFT 和 ORB 相比,实现了最先进的单应性估计结果。

使用提示
下面是使用模型检测图像中兴趣点的快速示例:
from transformers import AutoImageProcessor, SuperPointForKeypointDetection
import torch
from PIL import Image
import requests
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
processor = AutoImageProcessor.from_pretrained("magic-leap-community/superpoint")
model = SuperPointForKeypointDetection.from_pretrained("magic-leap-community/superpoint")
inputs = processor(image, return_tensors="pt")
outputs = model(**inputs)
输出包含关键点坐标列表及其相应的分数和描述(一个 256 长的向量)。
您还可以向模型输入多张图像。由于 SuperPoint 的特性,要输出动态数量的关键点,您需要使用 mask 属性来检索相应的信息。
from transformers import AutoImageProcessor, SuperPointForKeypointDetection
import torch
from PIL import Image
import requests
url_image_1 = "http://images.cocodataset.org/val2017/000000039769.jpg"
image_1 = Image.open(requests.get(url_image_1, stream=True).raw)
url_image_2 = "http://images.cocodataset.org/test-stuff2017/000000000568.jpg"
image_2 = Image.open(requests.get(url_image_2, stream=True).raw)
images = [image_1, image_2]
processor = AutoImageProcessor.from_pretrained("magic-leap-community/superpoint")
model = SuperPointForKeypointDetection.from_pretrained("magic-leap-community/superpoint")
inputs = processor(images, return_tensors="pt")
outputs = model(**inputs)
image_sizes = [(image.height, image.width) for image in images]
outputs = processor.post_process_keypoint_detection(outputs, image_sizes)
for output in outputs:
for keypoints, scores, descriptors in zip(output["keypoints"], output["scores"], output["descriptors"]):
print(f"Keypoints: {keypoints}")
print(f"Scores: {scores}")
print(f"Descriptors: {descriptors}")
然后,您可以在您选择的图像上打印关键点以可视化结果。
import matplotlib.pyplot as plt
plt.axis("off")
plt.imshow(image_1)
plt.scatter(
outputs[0]["keypoints"][:, 0],
outputs[0]["keypoints"][:, 1],
c=outputs[0]["scores"] * 100,
s=outputs[0]["scores"] * 50,
alpha=0.8
)
plt.savefig(f"output_image.png")
此模型由 stevenbucaille 贡献。原始代码可以在此处找到。
资源
Hugging Face 官方和社区(由 🌎 指示)资源列表,可帮助您开始使用 SuperPoint。如果您有兴趣提交要包含在此处的资源,请随时打开拉取请求,我们将对其进行审核!资源应理想地展示新内容,而不是复制现有资源。
- 一个展示 SuperPoint 推理和可视化的笔记本可以在此处找到。🌎
SuperPointConfig
class transformers.SuperPointConfig
< source >( encoder_hidden_sizes: list = [64, 64, 128, 128] decoder_hidden_size: int = 256 keypoint_decoder_dim: int = 65 descriptor_decoder_dim: int = 256 keypoint_threshold: float = 0.005 max_keypoints: int = -1 nms_radius: int = 4 border_removal_distance: int = 4 initializer_range = 0.02 **kwargs )
参数
- encoder_hidden_sizes (
List
, 可选, 默认为[64, 64, 128, 128]
) — 编码器中每个卷积层的通道数。 - decoder_hidden_size (
int
, 可选, 默认为 256) — 解码器的隐藏大小。 - keypoint_decoder_dim (
int
, 可选, 默认为 65) — 关键点解码器的输出维度。 - descriptor_decoder_dim (
int
, 可选, 默认为 256) — 描述符解码器的输出维度。 - keypoint_threshold (
float
, 可选, 默认为 0.005) — 用于提取关键点的阈值。 - max_keypoints (
int
, 可选, 默认为 -1) — 要提取的最大关键点数。如果为-1
,则提取所有关键点。 - nms_radius (
int
, 可选, 默认为 4) — 非极大值抑制的半径。 - border_removal_distance (
int
, 可选, 默认为 4) — 移除关键点与边界的距离。 - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
这是用于存储 SuperPointForKeypointDetection 配置的配置类。它用于根据指定的参数实例化 SuperPoint 模型,定义模型架构。实例化默认配置将生成与 SuperPoint magic-leap-community/superpoint 架构相似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PretrainedConfig 的文档。
示例
>>> from transformers import SuperPointConfig, SuperPointForKeypointDetection
>>> # Initializing a SuperPoint superpoint style configuration
>>> configuration = SuperPointConfig()
>>> # Initializing a model from the superpoint style configuration
>>> model = SuperPointForKeypointDetection(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
SuperPointImageProcessor
class transformers.SuperPointImageProcessor
< source >( do_resize: bool = True size: typing.Optional[dict[str, int]] = None do_rescale: bool = True rescale_factor: float = 0.00392156862745098 do_grayscale: bool = False **kwargs )
参数
- do_resize (
bool
, 可选, 默认为True
) — 控制是否将图像的(高、宽)维度调整为指定的size
。可以通过preprocess
方法中的do_resize
覆盖。 - size (
dict[str, int]
可选, 默认为{"height" -- 480, "width": 640}
):应用resize
后输出图像的分辨率。仅在do_resize
设置为True
时有效。可以通过preprocess
方法中的size
覆盖。 - do_rescale (
bool
, 可选, 默认为True
) — 是否按指定的比例rescale_factor
缩放图像。可以通过preprocess
方法中的do_rescale
覆盖。 - rescale_factor (
int
或float
, 可选, 默认为1/255
) — 如果do_rescale
设置为True
,则用于缩放图像的比例因子。可以通过preprocess
方法中的rescale_factor
覆盖。 - do_grayscale (
bool
, 可选, 默认为False
) — 是否将图像转换为灰度。可以通过preprocess
方法中的do_grayscale
覆盖。
构造一个 SuperPoint 图像处理器。
post_process_keypoint_detection
< source >( outputs: SuperPointKeypointDescriptionOutput target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple]] ) → list[Dict]
将 SuperPointForKeypointDetection 的原始输出转换为关键点列表、分数和描述符,其坐标相对于原始图像大小。
预处理
< source >( images do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = 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
) — 要预处理的图像。期望单个或批量图像,像素值范围为 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
时有效。 - 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
< source >( 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)。
调整图像大小。
- 预处理
- post_process_keypoint_detection
用于关键点检测的 SuperPoint
class transformers.SuperPointForKeypointDetection
< source >( config: SuperPointConfig )
参数
- config (SuperPointConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不加载与模型关联的权重,只加载配置。请查看 from_pretrained() 方法以加载模型权重。
SuperPoint 模型输出关键点和描述符。
此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解所有与一般用法和行为相关的事项。
前向传播
< source >( pixel_values: FloatTensor labels: typing.Optional[torch.LongTensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.superpoint.modeling_superpoint.SuperPointKeypointDescriptionOutput
或 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_hidden_states (
bool
,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是纯元组。
返回
transformers.models.superpoint.modeling_superpoint.SuperPointKeypointDescriptionOutput
或 tuple(torch.FloatTensor)
一个 transformers.models.superpoint.modeling_superpoint.SuperPointKeypointDescriptionOutput
或一个 torch.FloatTensor
的元组(如果传入 return_dict=False
或当 config.return_dict=False
时),根据配置(SuperPointConfig)和输入包含各种元素。
- loss (形状为
(1,)
的torch.FloatTensor
,可选) — 训练期间计算的损失。 - keypoints (形状为
(batch_size, num_keypoints, 2)
的torch.FloatTensor
) — 给定图像中预测关键点的相对 (x, y) 坐标。 - scores (形状为
(batch_size, num_keypoints)
的torch.FloatTensor
) — 预测关键点的得分。 - descriptors (形状为
(batch_size, num_keypoints, descriptor_size)
的torch.FloatTensor
) — 预测关键点的描述符。 - mask (形状为
(batch_size, num_keypoints)
的torch.BoolTensor
) — 指示关键点、得分和描述符中哪些值是关键点信息的掩码。 - hidden_states (
tuple(torch.FloatTensor)
,可选,当传入output_hidden_states=True
时返回,或者 - 当
config.output_hidden_states=True
) — 形状为(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每个阶段的输出)。模型在每个阶段输出的隐藏状态(也称为特征图)。
SuperPointForKeypointDetection 的 forward 方法,覆盖了 __call__
特殊方法。
尽管前向传播的配方需要在此函数中定义,但应在此之后调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, SuperPointForKeypointDetection
>>> import torch
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> processor = AutoImageProcessor.from_pretrained("magic-leap-community/superpoint")
>>> model = SuperPointForKeypointDetection.from_pretrained("magic-leap-community/superpoint")
>>> inputs = processor(image, return_tensors="pt")
>>> outputs = model(**inputs)
- 前向传播