Transformers documentation

SuperGlue

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

このモデルは2019年11月26日にHF papersで公開され、2025年1月20日にHugging Face Transformersに貢献されました。

PyTorch

SuperGlue

SuperGlueは、対応関係の探索とマッチング不可能な点の棄却を同時に行うことで、2つの局所特徴の集合をマッチングするニューラルネットワークです。アサインメントは、グラフニューラルネットワークによってコストが予測される微分可能な最適輸送問題を解くことで推定されます。SuperGlueはアテンションに基づく柔軟なコンテキスト集約メカニズムを導入し、基礎となる3Dシーンと特徴アサインメントを同時に推論することを可能にしています。SuperPointモデルと組み合わせることで、2つの画像をマッチングし、それらの間のポーズを推定できます。このモデルは、画像マッチングやホモグラフィ推定などのタスクに有用です。

すべての SuperGlue 元のチェックポイントは、Magic Leap Community 組織の下で確認できます。

このモデルは stevenbucaille によって提供されました。

右側のサイドバーにあるSuperGlueモデルをクリックすると、SuperGlueをさまざまなコンピュータビジョンタスクに適用する方法の追加例を確認できます。

以下の例では、PipelineまたはAutoModelクラスを使用して、2つの画像間でキーポイントを一致させる方法を示しています。

パイプライン
AutoModel
from transformers import pipeline


keypoint_matcher = pipeline(task="keypoint-matching", model="magic-leap-community/superglue_outdoor")

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': ...}

注記

  • SuperGlue は、2つの画像間の特徴点マッチングを同時に実行し、入力として画像のペアを必要とします。

    from transformers import AutoImageProcessor, AutoModel
    import torch
    from PIL import Image
    import requests
    
    processor = AutoImageProcessor.from_pretrained("magic-leap-community/superglue_outdoor")
    model = AutoModel.from_pretrained("magic-leap-community/superglue_outdoor", device_map="auto")
    
    # SuperGlue requires pairs of images
    images = [image1, image2]
    inputs = processor(images, return_tensors="pt").to(model.device)
    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
  • モデルは、各マッチに対して一致するインデックス、キーポイント、信頼度スコアを出力します。

  • より良い可視化と分析のために、SuperGlueImageProcessor.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)

リソース

SuperGlueConfig

class transformers.SuperGlueConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonekeypoint_detector_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonehidden_size: int = 256keypoint_encoder_sizes: list[int] | None = Nonegnn_layers_types: list[str] | None = Nonenum_attention_heads: int = 4sinkhorn_iterations: int = 100matching_threshold: float = 0.0initializer_range: float = 0.02is_decoder: bool = Falseattention_probs_dropout_prob: int | float = 0.0 )

パラメータ

  • keypoint_detector_config (Union[AutoConfig, dict]、任意、デフォルトは SuperPointConfig) — キーポイント検出器の設定オブジェクトまたは辞書です。
  • hidden_size (int、任意、デフォルトは 256) — 隠れ表現の次元数。
  • keypoint_encoder_sizes (list[int]、任意、デフォルトは [32, 64, 128, 256]) — キーポイントエンコーダの各層のサイズです。
  • gnn_layers_types (list[str]、任意、デフォルトは ['self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross']) — GNN レイヤーの種類です。‘self’ または ‘cross’ のいずれかである必要があります。
  • num_attention_heads (int、任意、デフォルトは 4) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。
  • sinkhorn_iterations (int, 任意、デフォルト値は 100) — Sinkhorn 反復の回数です。
  • matching_threshold (float、任意、デフォルトは 0.0) — マッチングの閾値です。
  • initializer_range (float、任意、デフォルトは 0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。
  • is_decoder (bool、任意、デフォルトは False) — モデルがデコーダーとして使用されるかどうかを示します。False の場合、モデルはエンコーダーとして使用されます。
  • attention_probs_dropout_prob (Union[int, float]、任意、デフォルトは 0.0) — アテンション確率のドロップアウト率です。

これは SuperglueModel の設定を保存するための設定クラスです。指定された引数に基づいて Superglue モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、magic-leap-community/superglue_indoor と同様の設定が得られます。

設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。

例:

>>> from transformers import SuperGlueConfig, SuperGlueModel

>>> # Initializing a SuperGlue superglue style configuration
>>> configuration = SuperGlueConfig()

>>> # Initializing a model from the superglue style configuration
>>> model = SuperGlueModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

SuperGlueImageProcessor

class transformers.SuperGlueImageProcessor

< >

( **kwargs: *<class 'transformers.models.superglue.image_processing_superglue.SuperGlueImageProcessorKwargs'> )

パラメータ

  • do_convert_rgb (bool、kwargs、任意) — 画像を RGB に変換するかどうかを指定します。
  • do_resize (bool、kwargs、任意、デフォルトはTrue) — 画像をリサイズするかどうか。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs、デフォルトは {'height' -- 480, 'width': 640}): モデルへの最大入力サイズを指定します。
  • default_to_square (bool、kwargs、任意、デフォルトは False) — size が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop を適用した後の出力画像のサイズ。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, デフォルトは 2) — 画像のリサイズ時に使用するリサンプリングフィルタです。PILImageResampling の列挙型のいずれかを使用できます。do_resize が True に設定されている場合のみ、効果が現れます。
  • do_rescale (bool、kwargs、任意、デフォルトはTrue) — 画像をリスケールするかどうかを指定します。
  • rescale_factor (float、kwargs、任意、デフォルト値は 0.00392156862745098) — do_rescale が True に設定されている場合、画像をリスケールするための係数です。
  • do_normalize (bool、kwargs、optional、デフォルトはNone) — 画像を正規化するかどうかを指定します。
  • image_mean (Union[float, list[float], tuple[float, ...]]、kwargs、optional) — 正規化に使用する画像の平均値。do_normalize が True に設定されている場合のみ有効です。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, optional) — 正規化に使用する画像の標準偏差。do_normalize が True に設定されている場合のみ有効です。
  • do_pad (bool, kwargs, optional) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 画像をパディングする {"height": int, "width" int} のサイズです。前処理に提供されるすべての画像サイズより大きくなければなりません。pad_size が指定されない場合、バッチ内の最大の幅と高さにパディングされます。do_pad=True. の場合のみ適用されます。
  • do_center_crop (bool, kwargs, optional) — 画像を中央クロップするかどうかを指定します。
  • data_format (Union[str, ~image_utils.ChannelDimension]、kwargs、任意) — サポートされているのは ChannelDimension.FIRST のみです。slow processors との互換性のために追加されました。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 省略可) — 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推測されます。次のいずれかになります:
    • "channels_first" または ChannelDimension.FIRST: (num_channels, height, width) 形式の画像。
    • "channels_last" または ChannelDimension.LAST: (高さ, 幅, チャネル数) 形式の画像。
    • "none" または ChannelDimension.NONE: (height, width) 形式の画像。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt' に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。
  • disable_grouping (bool、kwargs、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている経験則に基づいています。
  • image_seq_length (int、kwargs、任意) — 入力内の各画像に使用される画像トークンの数です。 後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。
  • do_grayscale (bool、kwargs、optional、デフォルトは self.do_grayscale) — 画像をグレースケールに変換するかどうか。preprocess メソッド内の do_grayscale で上書きできます。

SuperGlueImageProcessor 画像プロセッサを構築します。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.superglue.image_processing_superglue.SuperGlueImageProcessorKwargs'> ) → ~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 を設定してください。
  • do_convert_rgb (bool、kwargs、任意) — 画像を RGB に変換するかどうかを指定します。
  • do_resize (bool、kwargs、optional) — 画像をリサイズするかどうか。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — モデルへの最大入力次元を記述します。
  • default_to_square (bool、kwargs、任意) — サイズが整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop を適用した後の出力画像のサイズ。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 画像のリサイズ時に使用するリサンプリングフィルタ。PILImageResampling の列挙型のいずれかを使用できます。do_resize が True に設定されている場合のみ有効です。
  • do_rescale (bool、kwargs、optional) — 画像をリスケールするかどうかを指定します。
  • rescale_factor (float、kwargs、任意) — do_rescale が True に設定されている場合、画像をリスケールするための係数。
  • do_normalize (bool, kwargs, optional) — 画像を正規化するかどうかを指定します。
  • image_mean (Union[float, list[float], tuple[float, ...]]、kwargs、optional) — 正規化に使用する画像の平均値。do_normalize が True に設定されている場合のみ有効です。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, optional) — 正規化に使用する画像の標準偏差。do_normalize が True に設定されている場合のみ有効です。
  • do_pad (bool, kwargs, optional) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 画像をパディングする {"height": int, "width" int} のサイズです。前処理に提供されるすべての画像サイズより大きくなければなりません。pad_size が指定されない場合、バッチ内の最大の幅と高さにパディングされます。do_pad=True. の場合のみ適用されます。
  • do_center_crop (bool, kwargs, optional) — 画像を中央クロップするかどうかを指定します。
  • data_format (Union[str, ~image_utils.ChannelDimension]、kwargs、任意) — サポートされているのは ChannelDimension.FIRST のみです。slow processors との互換性のために追加されました。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 省略可) — 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推測されます。次のいずれかになります:
    • "channels_first" または ChannelDimension.FIRST: (num_channels, height, width) 形式の画像。
    • "channels_last" または ChannelDimension.LAST: (高さ, 幅, チャネル数) 形式の画像。
    • "none" または ChannelDimension.NONE: (height, width) 形式の画像。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt' に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。
  • disable_grouping (bool、kwargs、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている経験則に基づいています。
  • image_seq_length (int、kwargs、任意) — 入力内の各画像に使用される画像トークンの数です。 後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。
  • do_grayscale (bool、kwargs、optional、デフォルトは self.do_grayscale) — 画像をグレースケールに変換するかどうか。preprocess メソッド内の do_grayscale で上書きできます。

戻り値

~image_processing_base.BatchFeature

  • data (dict) — call メソッド(‘pixel_values’ など)によって返される、リスト/配列/テンソルの辞書。
  • tensor_type (Union[None, str, TensorType]、省略可) — 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

post_process_keypoint_matching

< >

( outputs: SuperGlueKeypointMatchingOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple]threshold: float = 0.0 ) → list[Dict]

パラメータ

  • outputs (SuperGlueKeypointMatchingOutput) — モデルの生出力です。
  • target_sizes (torch.Tensor または list[tuple[tuple[int, int]]]、任意) — (batch_size, 2, 2) の形状を持つテンソル、または各画像のターゲットサイズ (height, width) を含むタプルのタプルのリスト(tuple[int, int])です。これは、処理前の元の画像サイズである必要があります。
  • threshold (float、任意、デフォルトは 0.0) — スコアが低いマッチングを除外するための閾値。

戻り値

list[Dict]

ペアの1枚目と2枚目の画像におけるキーポイント、マッチングスコア、およびマッチングインデックスをそれぞれ含む辞書のリスト

SuperGlueKeypointMatchingOutputの生出力を、キーポイント、スコア、記述子のリストに変換し、座標は元の画像サイズに対する絶対座標として返します。

visualize_keypoint_matching

< >

( imageskeypoint_matching_output: list ) → List[PIL.Image.Image]

パラメータ

  • images — プロットする画像ペア。EfficientLoFTRImageProcessor.preprocess と同じです。ピクセル値が 0 から 255 の範囲である 2 枚の画像のリスト、または 2 枚の画像のリストのリストを期待します。
  • keypoint_matching_output (List[Dict[str, torch.Tensor]]) — 後処理が適用されたキーポイントマッチングの出力

戻り値

List[PIL.Image.Image]

検出されたキーポイントとそれらの間の対応付けを、画像ペアが横並びで表示されたPIL画像のリスト。

検出されたキーポイントおよびそれらの間の対応付けとともに、画像ペアを並べてプロットします。

SuperGlueImageProcessorPil

class transformers.SuperGlueImageProcessorPil

< >

( **kwargs: *<class 'transformers.models.superglue.image_processing_pil_superglue.SuperGlueImageProcessorKwargs'> )

パラメータ

  • do_convert_rgb (bool、kwargs、任意) — 画像を RGB に変換するかどうかを指定します。
  • do_resize (bool、kwargs、任意、デフォルトはTrue) — 画像をリサイズするかどうか。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs、デフォルトは {'height' -- 480, 'width': 640}): モデルへの最大入力サイズを指定します。
  • default_to_square (bool、kwargs、任意、デフォルトは False) — size が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop を適用した後の出力画像のサイズ。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs, デフォルトは 2) — 画像のリサイズ時に使用するリサンプリングフィルタです。PILImageResampling の列挙型のいずれかを使用できます。do_resize が True に設定されている場合のみ、効果が現れます。
  • do_rescale (bool、kwargs、任意、デフォルトはTrue) — 画像をリスケールするかどうかを指定します。
  • rescale_factor (float、kwargs、任意、デフォルト値は 0.00392156862745098) — do_rescale が True に設定されている場合、画像をリスケールするための係数です。
  • do_normalize (bool、kwargs、optional、デフォルトはNone) — 画像を正規化するかどうかを指定します。
  • image_mean (Union[float, list[float], tuple[float, ...]]、kwargs、optional) — 正規化に使用する画像の平均値。do_normalize が True に設定されている場合のみ有効です。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, optional) — 正規化に使用する画像の標準偏差。do_normalize が True に設定されている場合のみ有効です。
  • do_pad (bool, kwargs, optional) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 画像をパディングする {"height": int, "width" int} のサイズです。前処理に提供されるすべての画像サイズより大きくなければなりません。pad_size が指定されない場合、バッチ内の最大の幅と高さにパディングされます。do_pad=True. の場合のみ適用されます。
  • do_center_crop (bool, kwargs, optional) — 画像を中央クロップするかどうかを指定します。
  • data_format (Union[str, ~image_utils.ChannelDimension]、kwargs、任意) — サポートされているのは ChannelDimension.FIRST のみです。slow processors との互換性のために追加されました。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 省略可) — 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推測されます。次のいずれかになります:
    • "channels_first" または ChannelDimension.FIRST: (num_channels, height, width) 形式の画像。
    • "channels_last" または ChannelDimension.LAST: (高さ, 幅, チャネル数) 形式の画像。
    • "none" または ChannelDimension.NONE: (height, width) 形式の画像。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt' に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。
  • disable_grouping (bool、kwargs、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている経験則に基づいています。
  • image_seq_length (int、kwargs、任意) — 入力内の各画像に使用される画像トークンの数です。 後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。
  • do_grayscale (bool、kwargs、optional、デフォルトは self.do_grayscale) — 画像をグレースケールに変換するかどうか。preprocess メソッド内の do_grayscale で上書きできます。

SuperGlueImageProcessor 画像プロセッサを構築します。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.superglue.image_processing_pil_superglue.SuperGlueImageProcessorKwargs'> ) → ~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 を設定してください。
  • do_convert_rgb (bool、kwargs、任意) — 画像を RGB に変換するかどうかを指定します。
  • do_resize (bool、kwargs、optional) — 画像をリサイズするかどうか。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — モデルへの最大入力次元を記述します。
  • default_to_square (bool、kwargs、任意) — サイズが整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — center_crop を適用した後の出力画像のサイズ。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 画像のリサイズ時に使用するリサンプリングフィルタ。PILImageResampling の列挙型のいずれかを使用できます。do_resize が True に設定されている場合のみ有効です。
  • do_rescale (bool、kwargs、optional) — 画像をリスケールするかどうかを指定します。
  • rescale_factor (float、kwargs、任意) — do_rescale が True に設定されている場合、画像をリスケールするための係数。
  • do_normalize (bool, kwargs, optional) — 画像を正規化するかどうかを指定します。
  • image_mean (Union[float, list[float], tuple[float, ...]]、kwargs、optional) — 正規化に使用する画像の平均値。do_normalize が True に設定されている場合のみ有効です。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, optional) — 正規化に使用する画像の標準偏差。do_normalize が True に設定されている場合のみ有効です。
  • do_pad (bool, kwargs, optional) — 画像をパディングするかどうかを指定します。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。具体的なパディング戦略はモデルによって異なります。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 画像をパディングする {"height": int, "width" int} のサイズです。前処理に提供されるすべての画像サイズより大きくなければなりません。pad_size が指定されない場合、バッチ内の最大の幅と高さにパディングされます。do_pad=True. の場合のみ適用されます。
  • do_center_crop (bool, kwargs, optional) — 画像を中央クロップするかどうかを指定します。
  • data_format (Union[str, ~image_utils.ChannelDimension]、kwargs、任意) — サポートされているのは ChannelDimension.FIRST のみです。slow processors との互換性のために追加されました。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 省略可) — 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推測されます。次のいずれかになります:
    • "channels_first" または ChannelDimension.FIRST: (num_channels, height, width) 形式の画像。
    • "channels_last" または ChannelDimension.LAST: (高さ, 幅, チャネル数) 形式の画像。
    • "none" または ChannelDimension.NONE: (height, width) 形式の画像。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 'pt' に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。
  • disable_grouping (bool、kwargs、任意) — サイズごとに画像をグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうか。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている経験則に基づいています。
  • image_seq_length (int、kwargs、任意) — 入力内の各画像に使用される画像トークンの数です。 後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。
  • do_grayscale (bool、kwargs、optional、デフォルトは self.do_grayscale) — 画像をグレースケールに変換するかどうか。preprocess メソッド内の do_grayscale で上書きできます。

戻り値

~image_processing_base.BatchFeature

  • data (dict) — call メソッド(‘pixel_values’ など)によって返される、リスト/配列/テンソルの辞書。
  • tensor_type (Union[None, str, TensorType]、省略可) — 初期化時に PyTorch/Numpy の Tensor 内の整数リストを変換するために、ここで tensor_type を指定できます。

post_process_keypoint_matching

< >

( outputs: SuperGlueKeypointMatchingOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple]threshold: float = 0.0 ) → list[Dict]

パラメータ

  • outputs (SuperGlueKeypointMatchingOutput) — モデルの生出力です。
  • target_sizes (torch.Tensor または list[tuple[tuple[int, int]]]、任意) — (batch_size, 2, 2) の形状を持つテンソル、または各画像のターゲットサイズ (height, width) を含むタプルのタプルのリスト(tuple[int, int])です。これは、処理前の元の画像サイズである必要があります。
  • threshold (float、任意、デフォルトは 0.0) — スコアが低いマッチングを除外するための閾値。

戻り値

list[Dict]

ペアの1枚目と2枚目の画像におけるキーポイント、マッチングスコア、およびマッチングインデックスをそれぞれ含む辞書のリスト

SuperGlueKeypointMatchingOutputの生出力を、キーポイント、スコア、記述子のリストに変換し、座標は元の画像サイズに対する絶対座標として返します。

visualize_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: list ) → List[PIL.Image.Image]

パラメータ

  • images (ImageInput) — プロットする画像のペア。SuperGlueImageProcessor.preprocess と同じです。ピクセル値が 0 から 255 の範囲である 2 枚の画像のリスト、または 2 枚の画像のリストのリストを期待します。
  • keypoint_matching_output (List[Dict[str, torch.Tensor]]) — 後処理が適用されたキーポイントマッチングの出力

戻り値

List[PIL.Image.Image]

検出されたキーポイントとそれらの間の対応付けを、画像ペアが横並びで表示されたPIL画像のリスト。

検出されたキーポイントおよびそれらの間の対応付けとともに、画像ペアを並べてプロットします。

SuperGlueForKeypointMatching

クラス transformers.SuperGlueForKeypointMatching

< >

( config: SuperGlueConfig )

パラメータ

  • config (SuperGlueConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。

画像を入力として受け取り、それらのマッチングを出力するSuperGlueモデル。

このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

forward

< >

( pixel_values: FloatTensorlabels: typing.Optional[torch.LongTensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → SuperGlueKeypointMatchingOutput or tuple(torch.FloatTensor)

パラメータ

  • pixel_values (torch.FloatTensor、shape (batch_size, num_channels, image_size, image_size)) — 入力画像に対応するテンソルです。ピクセル値は SuperGlueImageProcessor を使用して取得できます。詳細は SuperGlueImageProcessor.call() を参照してください(processor_class は画像の処理に SuperGlueImageProcessor を使用します)。
  • labels (torch.LongTensor、shape (batch_size, sequence_length)、任意) — マスク言語モデリング損失を計算するためのラベルです。インデックスは [0, ..., config.vocab_size] の範囲内であるか、-100 である必要があります(input_ids の docstring を参照)。インデックスが -100 に設定されたトークンは無視(マスク)され、損失は [0, ..., config.vocab_size] の範囲内のラベルを持つトークンに対してのみ計算されます。
  • output_attentions (bool, 省略可) — すべてのアテンション層のアテンションテンソルを返すかどうかを指定します。詳細は、返されるテンソルの attentions を参照してください。
  • output_hidden_states (bool, 省略可) — すべての層の hidden states を返すかどうかを指定します。詳細は、返されるテンソルの hidden_states を参照してください。
  • return_dict (bool, 任意) — プレーンなタプルではなく ModelOutput を返すかどうか。

戻り値

SuperGlueKeypointMatchingOutput または tuple(torch.FloatTensor)

SuperGlueKeypointMatchingOutput、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(SuperGlueConfig)や入力に応じて、さまざまな要素で構成されます。

SuperGlueForKeypointMatching の forward メソッドは、__call__ という特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなくModuleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。

  • loss (torch.FloatTensor、shape (1,)、optional) — 学習中に計算される損失。
  • matches (torch.FloatTensor、shape (batch_size, 2, num_matches)) — 他方の画像でマッチしたキーポイントのインデックス。
  • matching_scores (torch.FloatTensor、shape (batch_size, 2, num_matches)) — 予測されたマッチのスコア。
  • keypoints(torch.FloatTensor、形状 (batch_size, num_keypoints, 2))— 対象画像内で予測されたキーポイントの絶対座標 (x, y)。
  • mask (torch.IntTensor、shape (batch_size, num_keypoints)) — matches と matching_scores のどの値がキーポイントマッチング情報であるかを示すマスク。
  • hidden_states (tuple[torch.FloatTensor, ...]、任意) — output_hidden_states=True が渡された場合、または config.output_hidden_states=True の場合に返される、各ステージの出力に対応する torch.FloatTensor のタプルで、形状は (batch_size, 2, num_channels, num_keypoints) です。
  • attentions (tuple[torch.FloatTensor, ...]、optional) — output_attentions=True が渡された場合、または config.output_attentions=True の場合に返される、torch.FloatTensor のタプル(レイヤーごとに1つ、形状は (batch_size, 2, num_heads, num_keypoints, num_keypoints))

例:

>>> from transformers import AutoImageProcessor, AutoModel
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "https://github.com/magicleap/SuperGluePretrainedNetwork/blob/master/assets/phototourism_sample_images/london_bridge_78916675_4568141288.jpg?raw=true"
>>> with httpx.stream("GET", url) as response:
...     image_1 = Image.open(BytesIO(response.read()))

>>> url = "https://github.com/magicleap/SuperGluePretrainedNetwork/blob/master/assets/phototourism_sample_images/london_bridge_19481797_2295892421.jpg?raw=true"
>>> with httpx.stream("GET", url) as response:
...     image_2 = Image.open(BytesIO(response.read()))

>>> images = [image_1, image_2]

>>> processor = AutoImageProcessor.from_pretrained("magic-leap-community/superglue_outdoor")
>>> model = AutoModel.from_pretrained("magic-leap-community/superglue_outdoor")

>>> with torch.no_grad():
>>>     inputs = processor(images, return_tensors="pt")
>>>     outputs = model(**inputs)
Update on GitHub