Transformers documentation
EfficientLoFTR
このモデルは2024年3月7日にHF papersで公開され、2025年7月22日にHugging Face Transformersに貢献されました。
EfficientLoFTR
EfficientLoFTRは、検出器を必要としない効率的な局所特徴マッチング手法であり、スパースな速度で画像間の半稠密なマッチングを生成します。元のLoFTRアーキテクチャを基盤としつつ、効率性と精度の両方に大幅な改善をもたらしています。その核心的な革新は、適応的なトークン選択を備えた集約型アテンション機構であり、これによりモデルはLoFTRより約2.5倍高速化されると同時に、より高い精度を実現します。EfficientLoFTRは、SuperPoint + LightGlueのような最先端の効率的なスパースマッチングパイプラインすら速度面で上回ることがあり、画像検索や3D再構成など、大規模またはレイテンシに敏感なアプリケーションに適しています。
このモデルは stevenbucaille によって提供されました。
右側のサイドバーにあるEfficientLoFTRモデルをクリックすると、EfficientLoFTRをさまざまなコンピュータビジョンタスクに適用する方法の例をさらに確認できます。
以下の例では、PipelineまたはAutoModelクラスを使用して、2つの画像間でキーポイントを一致させる方法を示しています。
from transformers import pipeline
keypoint_matcher = pipeline(task="keypoint-matching", model="zju-community/efficientloftr")
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': ...}import requests
import torch
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForKeypointMatching
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("zju-community/efficientloftr")
model = AutoModelForKeypointMatching.from_pretrained("zju-community/efficientloftr", device_map="auto")
inputs = processor(images, return_tensors="pt").to(model.device)
with torch.inference_mode():
outputs = model(**inputs)
# Post-process to get keypoints and matches
image_sizes = [[(image.height, image.width) for image in images]]
processed_outputs = processor.post_process_keypoint_matching(outputs, image_sizes, threshold=0.2)注記
EfficientLoFTRは、高い精度を維持しながら効率性を高めることを目的として設計されています。元のLoFTRと比較して計算負荷を軽減するため、適応型トークン選択を備えた集約型アテンション機構を使用しています。
from transformers import AutoImageProcessor, AutoModelForKeypointMatching import torch from PIL import Image import requests processor = AutoImageProcessor.from_pretrained("zju-community/efficientloftr") model = AutoModelForKeypointMatching.from_pretrained("zju-community/efficientloftr", device_map="auto") # EfficientLoFTR 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 keypoints = outputs.keypoints # Keypoints in both images matches = outputs.matches # Matching indices matching_scores = outputs.matching_scores # Confidence scoresモデルは半稠密なマッチングを生成し、マッチングの密度と計算効率の間に優れたバランスを提供します。大きな視点の変化や、テクスチャが乏しいシナリオの処理に特に優れています。
より良い可視化と分析のために、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 visualized_images = processor.visualize_keypoint_matching(images, processed_outputs)EfficientLoFTRは、新しい2段階の相関層を使用し、元のLoFTRのファイン相関モジュールを改善した、正確なサブピクセル対応を実現します。

リソース
- EfficientLoFTRの元のリポジトリを参照して、より多くの例や実装の詳細を確認してください。
- インタラクティブなデモや追加情報を含むEfficientLoFTRプロジェクトページ。
EfficientLoFTRConfig
class transformers.EfficientLoFTRConfig
< source >( 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 = Nonestage_num_blocks: list[int] | None = Noneout_features: list[int] | None = Nonestage_stride: list[int] | None = Nonehidden_size: int = 256activation_function: str = 'relu'q_aggregation_kernel_size: int = 4kv_aggregation_kernel_size: int = 4q_aggregation_stride: int = 4kv_aggregation_stride: int = 4num_attention_layers: int = 4num_attention_heads: int = 8attention_dropout: float | int = 0.0attention_bias: bool = Falsemlp_activation_function: str = 'leaky_relu'coarse_matching_skip_softmax: bool = Falsecoarse_matching_threshold: float = 0.2coarse_matching_temperature: float = 0.1coarse_matching_border_removal: int = 2fine_kernel_size: int = 8batch_norm_eps: float = 1e-05rope_parameters: dict | None = Nonefine_matching_slice_dim: int = 8fine_matching_regress_temperature: float = 10.0initializer_range: float = 0.02 )
パラメータ
- stage_num_blocks (
List、任意、デフォルトは [1, 2, 4, 14]) — 各ステージのブロック数 - out_features (
list[int]、省略可) — バックボーンから返す中間の隠れ状態(特徴マップ)の名前。"stem"、"stage1"、"stage2"などのいずれかです。 - stage_stride (
List、任意、デフォルトは [2, 1, 2, 2]) — 各ステージで使用するストライドです。 - hidden_size (
int、任意、デフォルトは256) — 隠れ表現の次元数。 - activation_function (
str、任意、デフォルトはrelu) — デコーダーで使用する非線形活性化関数(関数または文字列)。例えば、"gelu"、"relu"、"silu"など。 - q_aggregation_kernel_size (
int、任意、デフォルトは 4) — フュージョンネットワークにおけるクエリ状態の集約に使用されるカーネルサイズ - kv_aggregation_kernel_size (
int、任意、デフォルト値は 4) — 融合ネットワークにおけるキー状態とバリュー状態の集約に使用されるカーネルサイズ - q_aggregation_stride (
int、任意、デフォルトは 4) — 融合ネットワークにおけるクエリ状態の集約のストライド - kv_aggregation_stride (
int、任意、デフォルトは 4) — フュージョンネットワークにおけるキー状態とバリュー状態の集約のストライド - num_attention_layers (
int、任意、デフォルトは 4)— LocalFeatureTransformer におけるアテンション層の数 - num_attention_heads (
int、任意、デフォルトは8) — Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。 - attention_dropout (
Union[float, int]、任意、デフォルトは0.0) — アテンション確率のドロップアウト率です。 - attention_bias (
bool、任意、デフォルトはFalse) — 自己注意機構において、クエリ、キー、バリュー、出力の投影層にバイアスを使用するかどうかを指定します。 - mlp_activation_function (
str、任意、デフォルトは"leaky_relu") — アテンション MLP 層で使用する活性化関数。 - coarse_matching_skip_softmax (
bool、任意、デフォルトはFalse) — 粗いマッチングのステップでsoftmaxをスキップするかどうか。 - coarse_matching_threshold (
float、任意、デフォルト値は 0.2) — マッチングに必要とされる最低スコアの閾値です。 - coarse_matching_temperature (
float、省略可、デフォルト値は 0.1) — 粗い類似度行列に適用する温度 - coarse_matching_border_removal (
int、任意、デフォルト値は 2)— 粗マッチング時に除去する境界のサイズ - fine_kernel_size (
int、任意、デフォルトは 8) — 微細な特徴量マッチングに使用されるカーネルサイズ - batch_norm_eps (
float、任意、デフォルト値は 1e-05) — バッチ正規化レイヤーで使用する epsilon - rope_parameters (
dict, 任意) — RoPE 埋め込みの設定パラメータを含む辞書です。辞書にはrope_thetaの値が含まれており、より長いmax_position_embeddingsで RoPE を使用する場合、スケーリングに使用されるパラメータが任意で含まれます。 - fine_matching_slice_dim (
int、任意、デフォルトは 8) — 第 1 段階および第 2 段階のファインマッチングで、ファイン特徴量を分割するために使用されるスライスのサイズです。 - fine_matching_regress_temperature (
float、任意、デフォルト値は 10.0) — ファイン類似度行列に適用する温度 - initializer_range (
float、任意、デフォルトは0.02) — すべての重み行列を初期化するための truncated_normal_initializer の標準偏差です。
これは EfficientLoFTRModel の設定を保存するための設定クラスです。指定された引数に基づいて Efficientloftr モデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、zju-community/efficientloftr と同様の設定が得られます。
設定オブジェクトはPreTrainedConfigを継承し、モデルの出力を制御するために使用できます。詳細については、PreTrainedConfigのドキュメントを参照してください。
例:
>>> from transformers import EfficientLoFTRConfig, EfficientLoFTRForKeypointMatching
>>> # Initializing a EfficientLoFTR configuration
>>> configuration = EfficientLoFTRConfig()
>>> # Initializing a model from the EfficientLoFTR configuration
>>> model = EfficientLoFTRForKeypointMatching(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configEfficientLoFTRImageProcessor
class transformers.EfficientLoFTRImageProcessor
< source >( **kwargs: *<class 'transformers.models.efficientloftr.image_processing_efficientloftr.EfficientLoFTRImageProcessorKwargs'> )
パラメータ
- 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で上書きできます。
EfficientLoFTRImageProcessor イメージプロセッサを構築します。
preprocess
< source >( 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.efficientloftr.image_processing_efficientloftr.EfficientLoFTRImageProcessorKwargs'> ) → ~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
< source >( outputs: EfficientLoFTRKeypointMatchingOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple]threshold: float = 0.0 ) → List[Dict]
パラメータ
- outputs (
EfficientLoFTRKeypointMatchingOutput) — モデルの生出力です。 - target_sizes (
torch.TensorまたはList[Tuple[Tuple[int, int]]]、任意) — 形状が(batch_size, 2, 2)の Tensor、または各画像のターゲットサイズ(height, width)を含むタプルのタプルのリスト (Tuple[int, int])。これは、処理前の元の画像サイズである必要があります。 - threshold (
float、任意、デフォルト値は 0.0) — スコアが低いマッチングを除外するための閾値。
戻り値
List[Dict]
ペアの1枚目と2枚目の画像におけるキーポイント、マッチングスコア、およびマッチングインデックスをそれぞれ含む辞書のリスト
EfficientLoFTRKeypointMatchingOutputの生出力を、元の画像サイズに対する絶対座標を持つキーポイント、スコア、記述子のリストに変換します。
visualize_keypoint_matching
< source >( imageskeypoint_matching_output: list ) → List[PIL.Image.Image]
検出されたキーポイントおよびそれらの間の対応付けとともに、画像ペアを並べてプロットします。
EfficientLoFTRImageProcessorPil
class transformers.EfficientLoFTRImageProcessorPil
< source >( **kwargs: *<class 'transformers.models.efficientloftr.image_processing_pil_efficientloftr.EfficientLoFTRImageProcessorKwargs'> )
パラメータ
- 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で上書きできます。
EfficientLoFTRImageProcessor イメージプロセッサを構築します。
preprocess
< source >( 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.efficientloftr.image_processing_pil_efficientloftr.EfficientLoFTRImageProcessorKwargs'> ) → ~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
< source >( outputs: EfficientLoFTRKeypointMatchingOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple]threshold: float = 0.0 ) → List[Dict]
パラメータ
- outputs (
EfficientLoFTRKeypointMatchingOutput) — モデルの生出力です。 - target_sizes (
torch.TensorまたはList[Tuple[Tuple[int, int]]]、任意) — 形状が(batch_size, 2, 2)の Tensor、または各画像のターゲットサイズ(height, width)を含むタプルのタプルのリスト (Tuple[int, int])。これは、バッチ内の各画像の元の画像サイズ(処理前のサイズ)である必要があります。 - threshold (
float、任意、デフォルト値は 0.0) — スコアが低いマッチングを除外するための閾値。
戻り値
List[Dict]
ペアの1枚目と2枚目の画像におけるキーポイント、マッチングスコア、およびマッチングインデックスをそれぞれ含む辞書のリスト
EfficientLoFTRKeypointMatchingOutputの生出力を、元の画像サイズに対する絶対座標を持つキーポイント、スコア、記述子のリストに変換します。
visualize_keypoint_matching
< source >( 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) — プロットする画像ペア。EfficientLoFTRImageProcessor.preprocessと同じです。ピクセル値が 0 から 255 の範囲である 2 枚の画像のリスト、または 2 枚の画像のリストのリストを期待します。 - keypoint_matching_output (List[Dict[str, torch.Tensor]]) — 後処理が適用されたキーポイントマッチングの出力
戻り値
List[PIL.Image.Image]
検出されたキーポイントとそれらの間の対応付けを、画像ペアが横並びで表示されたPIL画像のリスト。
検出されたキーポイントおよびそれらの間の対応付けとともに、画像ペアを並べてプロットします。
EfficientLoFTRModel
クラス transformers.EfficientLoFTRModel
< source >( config: EfficientLoFTRConfig )
パラメータ
- config (EfficientLoFTRConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
画像を入力として受け取り、その画像の特徴量を出力するEfficientLoFTRモデル。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( pixel_values: FloatTensorlabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BackboneOutput or tuple(torch.FloatTensor)
パラメータ
- pixel_values (
torch.FloatTensor、shape(batch_size, num_channels, image_size, image_size)) — 入力画像に対応するテンソルです。ピクセル値はEfficientLoFTRImageProcessorを使用して取得できます。詳細はEfficientLoFTRImageProcessor.call()を参照してください(processor_classは画像の処理にEfficientLoFTRImageProcessorを使用します)。 - labels (
torch.LongTensor、shape(batch_size, sequence_length)、任意) — マスク言語モデリング損失を計算するためのラベルです。インデックスは[0, ..., config.vocab_size]の範囲内であるか、-100 である必要があります(input_idsの docstring を参照)。インデックスが-100に設定されたトークンは無視(マスク)され、損失は[0, ..., config.vocab_size]の範囲内のラベルを持つトークンに対してのみ計算されます。
戻り値
BackboneOutput または tuple(torch.FloatTensor)
BackboneOutput、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(EfficientLoFTRConfig)や入力に応じて、さまざまな要素で構成されます。
EfficientLoFTRModelのforwardメソッドは、__call__特殊メソッドをオーバーライドします。
この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく
Moduleインスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを黙って無視するためです。
feature_maps (
tuple(torch.FloatTensor)、形状(batch_size, num_channels, height, width)) — 各ステージのフィーチャマップ。hidden_states (
tuple(torch.FloatTensor)、任意、output_hidden_states=Trueが渡された場合またはconfig.output_hidden_states=Trueの場合に返されます)—torch.FloatTensorのタプル(埋め込みの出力用 1 つ + 各層の出力用 1 つ)。形状は(batch_size, sequence_length, hidden_size)または(batch_size, num_channels, height, width)で、バックボーンによって異なります。各ステージの出力におけるモデルのHidden-states、および初期の埋め込み出力。
attentions (
tuple(torch.FloatTensor)、optional、output_attentions=Trueが渡された場合またはconfig.output_attentions=Trueの場合に返される) —torch.FloatTensorのタプル(レイヤーごとに1つ)、形状は(batch_size, num_heads, sequence_length, sequence_length)。バックボーンがアテンションを使用する場合にのみ適用されます。アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
例:
>>> 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:
... image1 = 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:
... image2 = Image.open(BytesIO(response.read()))
>>> images = [image1, image2]
>>> processor = AutoImageProcessor.from_pretrained("zju-community/efficient_loftr")
>>> model = AutoModel.from_pretrained("zju-community/efficient_loftr")
>>> with torch.no_grad():
>>> inputs = processor(images, return_tensors="pt")
>>> outputs = model(**inputs)EfficientLoFTRForKeypointMatching
クラス transformers.EfficientLoFTRForKeypointMatching
< source >( config: EfficientLoFTRConfig )
パラメータ
- config (EfficientLoFTRConfig) — モデルのパラメータをすべて含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、from_pretrained() メソッドを参照してください。
EfficientLoFTRモデルは画像を入力として受け取り、それらのマッチングを出力します。
このモデルは PreTrainedModel を継承しています。すべてのモデルに実装されている汎用的なメソッド(ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど)については、スーパークラスのドキュメントを参照してください。
このモデルは、PyTorchのtorch.nn.Moduleのサブクラスでもあります。 通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。
forward
< source >( pixel_values: FloatTensorlabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → EfficientLoFTRKeypointMatchingOutput or tuple(torch.FloatTensor)
パラメータ
- pixel_values (
torch.FloatTensor、shape(batch_size, num_channels, image_size, image_size)) — 入力画像に対応するテンソルです。ピクセル値はimage_processor_classを使用して取得できます。詳細はimage_processor_class.__call__を参照してください(processor_classは画像の処理にimage_processor_classを使用します)。 - labels (
torch.LongTensor、shape(batch_size, sequence_length)、任意) — マスク言語モデリング損失を計算するためのラベルです。インデックスは[0, ..., config.vocab_size]の範囲内であるか、-100 である必要があります(input_idsの docstring を参照)。インデックスが-100に設定されたトークンは無視(マスク)され、損失は[0, ..., config.vocab_size]の範囲内のラベルを持つトークンに対してのみ計算されます。
戻り値
EfficientLoFTRKeypointMatchingOutput または tuple(torch.FloatTensor)
EfficientLoFTRKeypointMatchingOutput、またはtorch.FloatTensorのタプル(return_dict=Falseが渡された場合、またはconfig.return_dict=Falseの場合)。設定(None)や入力に応じて、さまざまな要素で構成されます。
EfficientLoFTRForKeypointMatching の 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)。 - 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:
... image1 = 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:
... image2 = Image.open(BytesIO(response.read()))
>>> images = [image1, image2]
>>> processor = AutoImageProcessor.from_pretrained("zju-community/efficient_loftr")
>>> model = AutoModel.from_pretrained("zju-community/efficient_loftr")
>>> with torch.no_grad():
>>> inputs = processor(images, return_tensors="pt")
>>> outputs = model(**inputs)