# キーポイントマッチング

Keypoint matching（キーポイントマッチング）とは、2つの異なる画像に写っている同一のオブジェクトに属する異なる関心点（point of interest）を対応付けます。最新の多くのキーポイントマッチャーは画像を入力とし、以下を出力します。

- **キーポイント座標 (x,y):** 2つのリストを用いて、最初の画像と2番目の画像のピクセル座標を1対1で対応付けます。最初のリストの特定のインデックスにあるキーポイントは、2番目のリストの同じインデックスにあるキーポイントと対応付けられます。
- **マッチングスコア:** キーポイントのマッチに割り当てられるスコア。

本チュートリアルでは、[MatchAnything フレームワーク](https://huggingface.co/zju-community/matchanything_eloftr)で学習された`EfficientLoFTR`モデルを使用してキーポイントのマッチングを抽出し、マッチングを精査します。このモデルはパラメータ数がわずか16Mであり、CPU上で実行できます。[AutoModelForKeypointMatching](/docs/transformers/v5.23.0/ja/model_doc/auto#transformers.AutoModelForKeypointMatching)クラスを使用します。

```python
from transformers import AutoImageProcessor, AutoModelForKeypointMatching
import torch

processor = AutoImageProcessor.from_pretrained("zju-community/matchanything_eloftr")
model = AutoModelForKeypointMatching.from_pretrained("zju-community/matchanything_eloftr")
```

同じ対象物を含む2つの画像を読み込みます。2枚目の写真は1秒後に撮影されたもので、色調が編集されており、さらにトリミングと回転が施されています。

    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"
         alt="Bee"
         style="height: 200px; object-fit: contain; margin-right: 10px;">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee_edited.jpg"
         alt="Bee edited"
         style="height: 200px; object-fit: contain;">

```python
from transformers.image_utils import load_image
image1 = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg")
image2 = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee_edited.jpg")

images = [image1, image2]
```

画像をプロセッサに渡し、推論を実行できます。

```python
inputs = processor(images, return_tensors="pt")
with torch.no_grad():
    outputs = model(**inputs)
```

出力を後処理できます。threshold パラメータは、出力された一致結果に含まれるノイズ（信頼度の低い閾値）を精査するために使用されます。

```python
image_sizes = [[(image.height, image.width) for image in images]]

outputs = processor.post_process_keypoint_matching(outputs, image_sizes, threshold=0.2)
print(outputs)
```

出力は以下の通りです。

```text
[{'keypoints0': tensor([[4514,  550],
          [4813,  683],
          [1972, 1547],
          ...
          [3916, 3408]], dtype=torch.int32),
  'keypoints1': tensor([[2280,  463],
          [2378,  613],
          [2231,  887],
          ...
          [1521, 2560]], dtype=torch.int32),
  'matching_scores': tensor([0.2189, 0.2073, 0.2414, ...
    ])}]
```

出力は短縮されていますが、一致箇所は401件あります！

```python
len(outputs[0]["keypoints0"])
# 401
```

プロセッサの[visualize_keypoint_matching()](/docs/transformers/v5.23.0/ja/model_doc/efficientloftr#transformers.EfficientLoFTRImageProcessor.visualize_keypoint_matching)メソッドを使用して、それらを可視化できます。

```python
plot_images = processor.visualize_keypoint_matching(images, outputs)
plot_images
```

![Matched Image](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/matched_bees.png)

必要に応じて、[Pipeline](/docs/transformers/v5.23.0/ja/main_classes/pipelines#transformers.Pipeline) API を使用し、タスクを`keypoint-matching`に設定できます。

```python
from transformers import pipeline 

image_1 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"
image_2 = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee_edited.jpg"

pipe = pipeline("keypoint-matching", model="zju-community/matchanything_eloftr")
pipe([image_1, image_2])
```

出力は以下のようになります。

```bash
[{'keypoint_image_0': {'x': 2444, 'y': 2869},
  'keypoint_image_1': {'x': 837, 'y': 1500},
  'score': 0.9756593704223633},
 {'keypoint_image_0': {'x': 1248, 'y': 2819},
  'keypoint_image_1': {'x': 862, 'y': 866},
  'score': 0.9735618829727173},
 {'keypoint_image_0': {'x': 1547, 'y': 3317},
  'keypoint_image_1': {'x': 1436, 'y': 1500},
  ...
 }
]
```

