Transformers 文档

SuperPoint

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2017-12-20 发布在 HF 论文中,并于 2024-03-19 贡献给 Hugging Face Transformers。

PyTorch

SuperPoint

SuperPoint 是对用于特征点检测和描述的全卷积网络进行自监督训练的结果。该模型能够检测在单应性变换下具有重复性的特征点,并为每个点提供描述符。虽然其独立用途有限,但它可以用作单应性估计和图像匹配等其他任务的特征提取器。

drawing

您可以在 Magic Leap Community 组织下找到所有原始的 SuperPoint 检查点。

该模型由 stevenbucaille 贡献。

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

下面的示例演示了如何使用 AutoModel 类检测图像中的特征点。

自动模型
import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, SuperPointForKeypointDetection


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", device_map="auto")

inputs = processor(image, return_tensors="pt").to(model.device)
with torch.no_grad():
    outputs = model(**inputs)

# Post-process to get keypoints, scores, and descriptors
image_size = (image.height, image.width)
processed_outputs = processor.post_process_keypoint_detection(outputs, [image_size])

注意事项

  • SuperPoint 为每张图像输出动态数量的关键点,这使其适用于需要变长特征表示的任务。

    from transformers import AutoImageProcessor, SuperPointForKeypointDetection
    import torch
    from PIL import Image
    import requests
    processor = AutoImageProcessor.from_pretrained("magic-leap-community/superpoint")
    model = SuperPointForKeypointDetection.from_pretrained("magic-leap-community/superpoint", device_map="auto")
    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]
    inputs = processor(images, return_tensors="pt").to(model.device)
    # Example of handling dynamic keypoint output
    outputs = model(**inputs)
    keypoints = outputs.keypoints  # Shape varies per image
    scores = outputs.scores        # Confidence scores for each keypoint
    descriptors = outputs.descriptors  # 256-dimensional descriptors
    mask = outputs.mask # Value of 1 corresponds to a keypoint detection
  • 该模型在单次前向传播中同时提供关键点坐标及其相应的描述符(256 维向量)。

  • 对于多张图像的批量处理,您需要使用 mask 属性来检索每张图像的相应信息。您可以使用 SuperPointImageProcessor 中的 post_process_keypoint_detection 来检索每张图像的信息。

    # Batch processing example
    images = [image1, image2, image3]
    inputs = processor(images, return_tensors="pt").to(model.device)
    outputs = model(**inputs)
    image_sizes = [(img.height, img.width) for img in images]
    processed_outputs = processor.post_process_keypoint_detection(outputs, image_sizes)
  • 然后,您可以将关键点打印在所选的图像上以使结果可视化

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

资源

  • 有关推理和可视化示例,请参阅此 notebook

SuperPointConfig

class transformers.SuperPointConfig

< >

( transformers_version: str | None = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None chunk_size_feed_forward: int = 0 is_encoder_decoder: bool = False id2label: dict[int, str] | dict[str, str] | None = None label2id: dict[str, int] | dict[str, str] | None = None problem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = None encoder_hidden_sizes: list[int] | tuple[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: float = 0.02 )

参数

  • 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 的标准差。

这是用于存储 SuperpointModel 配置的配置类。它用于根据指定的参数实例化 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

< >

( **kwargs: typing_extensions.Unpack[transformers.models.superpoint.image_processing_superpoint.SuperPointImageProcessorKwargs] )

参数

  • do_grayscale (bool, kwargs, 可选, 默认为 self.do_grayscale) — 是否将图像转换为灰度图。可以通过 preprocess 方法中的 do_grayscale 参数覆盖。
  • **kwargs (ImagesKwargs, 可选) — 其他图像预处理选项。上面列出了特定于模型的关键字参数;完整支持的参数列表请参阅 TypedDict 类。

构造一个 SuperPointImageProcessor 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] *args **kwargs: typing_extensions.Unpack[transformers.processing_utils.ImagesKwargs] ) ~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
  • return_tensors (strTensorType, 可选) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • **kwargs (ImagesKwargs, 可选) — 其他图像预处理选项。上面列出了特定于模型的关键字参数;完整支持的参数列表请参阅 TypedDict 类。

返回

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。

SuperPointImageProcessorPil

class transformers.SuperPointImageProcessorPil

< >

( **kwargs: typing_extensions.Unpack[transformers.models.superpoint.image_processing_pil_superpoint.SuperPointImageProcessorKwargs] )

参数

  • do_grayscale (bool, kwargs, 可选, 默认为 self.do_grayscale) — 是否将图像转换为灰度图。可以通过 preprocess 方法中的 do_grayscale 参数覆盖。
  • **kwargs (ImagesKwargs, 可选) — 其他图像预处理选项。上面列出了特定于模型的关键字参数;完整支持的参数列表请参阅 TypedDict 类。

构造一个 SuperPointImageProcessor 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] *args **kwargs: typing_extensions.Unpack[transformers.processing_utils.ImagesKwargs] ) ~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
  • return_tensors (strTensorType, 可选) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • **kwargs (ImagesKwargs, 可选) — 其他图像预处理选项。上面列出了特定于模型的关键字参数;完整支持的参数列表请参阅 TypedDict 类。

返回

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。

post_process_keypoint_detection

< >

( outputs: SuperPointKeypointDescriptionOutput target_sizes: transformers.utils.generic.TensorType | list[tuple] ) list[Dict]

参数

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

返回

list[Dict]

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

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

SuperPointForKeypointDetection

class transformers.SuperPointForKeypointDetection

< >

( config: SuperPointConfig )

参数

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

SuperPoint 模型,输出关键点和描述符。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: FloatTensor labels: torch.LongTensor | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) SuperPointKeypointDescriptionOutputtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor) — 与输入图像相对应的张量。可以使用 SuperPointImageProcessor 获取像素值。详情请参阅 SuperPointImageProcessor.__call__()processor_class 使用 SuperPointImageProcessor 处理图像)。
  • 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 而不是普通元组。

返回

SuperPointKeypointDescriptionOutputtuple(torch.FloatTensor)

一个 SuperPointKeypointDescriptionOutputtorch.FloatTensor 元组(如果传递了 return_dict=Falseconfig.return_dict=False 时),包含根据配置 (SuperPointConfig) 和输入而定的各种元素。

SuperPointForKeypointDetection 前向传播方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

  • 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), optional, 当传入 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor 元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 每个阶段的输出)。模型在每个阶段输出的隐藏状态(也称为特征图)。

示例

>>> from transformers import AutoImageProcessor, SuperPointForKeypointDetection
>>> import torch
>>> from PIL import Image
>>> import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> 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)
在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.