Transformers 文档

SuperPoint

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

to get started

SuperPoint

PyTorch

概述

SuperPoint 模型由 Daniel DeTone、Tomasz Malisiewicz 和 Andrew Rabinovich 在 SuperPoint: Self-Supervised Interest Point Detection and Description 中提出。

此模型是自监督训练的完全卷积网络的结果,用于兴趣点检测和描述。该模型能够检测在单应变换下可重复的兴趣点,并为每个点提供描述符。该模型自身的用途有限,但可以用作其他任务(如单应性估计、图像匹配等)的特征提取器。

论文摘要如下:

本文提出了一个自监督框架,用于训练兴趣点检测器和描述符,适用于计算机视觉中大量的多视图几何问题。与基于补丁的神经网络相反,我们的全卷积模型在全尺寸图像上运行,并在一次前向传递中联合计算像素级兴趣点位置和相关的描述符。我们引入了单应性自适应,这是一种多尺度、多单应性的方法,用于提高兴趣点检测的可重复性并执行跨域自适应(例如,合成到真实)。我们的模型在使用单应性自适应在 MS-COCO 通用图像数据集上训练时,能够比初始预自适应深度模型和任何其他传统角点检测器重复检测到更丰富的兴趣点集。与 LIFT、SIFT 和 ORB 相比,最终系统在 HPatches 上给出了最先进的单应性估计结果。

drawing SuperPoint 概述。摘自原始论文。

使用技巧

这是一个使用该模型检测图像中兴趣点的快速示例

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

image/png

此模型由 stevenbucaille 贡献。原始代码可以在这里找到。

资源

以下是 Hugging Face 官方和社区 (🌎 表示) 资源列表,可帮助您开始使用 SuperPoint。如果您有兴趣提交资源并在此处收录,请随时打开 Pull Request,我们将进行审核!理想情况下,资源应展示一些新的内容,而不是重复现有资源。

  • 可以在这里找到一个展示使用 SuperPoint 进行推理和可视化的 notebook。 🌎

SuperPointConfig

class transformers.SuperPointConfig

< >

( encoder_hidden_sizes: typing.List[int] = [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

< >

( do_resize: bool = True size: typing.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 (intfloat, 可选, 默认为 1/255) — 如果要缩放图像,则使用的缩放因子。 可以通过 preprocess 方法中的 rescale_factor 覆盖。
  • do_grayscale (bool, 可选, 默认为 False) — 是否将图像转换为灰度。 可以通过 preprocess 方法中的 do_grayscale 覆盖。

构建 SuperPoint 图像处理器。

post_process_keypoint_detection

< >

( outputs: SuperPointKeypointDescriptionOutput target_sizes: typing.Union[transformers.utils.generic.TensorType, typing.List[typing.Tuple]] ) List[Dict]

参数

  • outputs (SuperPointKeypointDescriptionOutput) — 模型的原始输出,包含相对 (x, y) 格式的关键点,以及分数和描述符。
  • target_sizes (torch.TensorList[Tuple[int, int]]) — 形状为 (batch_size, 2) 的张量或元组列表 (Tuple[int, int]),其中包含批次中每个图像的目标大小 (height, width)。 这必须是原始图像大小(在任何处理之前)。

返回值

List[Dict]

字典列表,每个字典包含根据 target_sizes 的绝对格式的关键点、分数和描述符,用于模型预测的批次中的图像。

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

preprocess

< >

( images do_resize: bool = None size: typing.Dict[str, int] = None do_rescale: bool = None rescale_factor: float = None do_grayscale: 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 (strTensorType, 可选) — 要返回的张量类型。 可以是以下之一:
    • Unset:返回 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 (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。 可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:(num_channels, height, width) 格式的图像。
    • "channels_last"ChannelDimension.LAST:(height, width, num_channels) 格式的图像。
    • Unset:使用输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。 如果未设置,则从输入图像推断通道维度格式。 可以是以下之一:
    • "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: typing.Dict[str, int] 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 (ChannelDimensionstr, 可选) — 输出图像的通道维度格式。 如果未提供,将从输入图像推断。 可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:(num_channels, height, width) 格式的图像。
    • "channels_last"ChannelDimension.LAST:(height, width, num_channels) 格式的图像。
    • "none"ChannelDimension.NONE:(height, width) 格式的图像。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则通道维度格式将从输入图像中推断。可以是以下之一:
    • "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_detection

SuperPointForKeypointDetection

class transformers.SuperPointForKeypointDetection

< >

( config: SuperPointConfig )

参数

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

SuperPoint 模型输出关键点和描述符。此模型是 PyTorch torch.nn.Module 子类。可将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。

SuperPoint 模型。它由 SuperPointEncoder、SuperPointInterestPointDecoder 和 SuperPointDescriptorDecoder 组成。SuperPoint 在 SuperPoint: Self-Supervised Interest Point Detection and Description <https://arxiv.org/abs/1712.07629>__ 中提出,作者是 Daniel DeTone、Tomasz Malisiewicz 和 Andrew Rabinovich。它是一个完全卷积神经网络,可从图像中提取关键点和描述符。它以自监督方式进行训练,结合了光度损失和基于关键点单应性自适应的损失。它由卷积编码器和两个解码器组成:一个用于关键点,另一个用于描述符。

forward

< >

( pixel_values: FloatTensor labels: typing.Optional[torch.LongTensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None )

参数

  • pixel_values (形状为 (batch_size, num_channels, height, width)torch.FloatTensor) — 像素值。像素值可以使用 SuperPointImageProcessor 获得。有关详细信息,请参阅 SuperPointImageProcessor.call()
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

    示例:

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

尽管 forward 传递的配方需要在该函数内定义,但应该在此之后调用 Module 实例,而不是调用此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

  • forward
< > 在 GitHub 上更新