Kornia 0.6 : Tutorials (中級) : KeyNet-AdaLAM による画像マッチング

Kornia 0.6 : Tutorials (中級) : KeyNet-AdaLAM による画像マッチング (翻訳/解説)

翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 10/28/2022 (v0.6.8)

* 本ページは、Kornia Tutorials の以下のドキュメントを翻訳した上で適宜、補足説明したものです:

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

クラスキャット 人工知能 研究開発支援サービス

クラスキャット は人工知能・テレワークに関する各種サービスを提供しています。お気軽にご相談ください :

◆ 人工知能とビジネスをテーマに WEB セミナーを定期的に開催しています。スケジュール
  • お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。

お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。

  • 株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション
  • sales-info@classcat.com  ;  Web: www.classcat.com  ;   ClassCatJP

 

 

Kornia 0.6 : Tutorials (中級) : KeyNet-AdaLAM による画像マッチング

最初に、必要なものすべてをインストールします :

  • AdaLAM 用の kornia の最新版
  • MAGSAC++ geometry 推定のための OpenCV の最新版
  • 変換と可視化のための kornia_moons

Docs: match_adalam

%%capture
!pip install git+https://github.com/kornia/kornia
!pip install kornia_moons
!pip install opencv-python --upgrade

次に画像ペアをダウンロードしましょう :

%%capture
!wget https://github.com/kornia/data/raw/main/matching/kn_church-2.jpg
!wget https://github.com/kornia/data/raw/main/matching/kn_church-8.jpg

First, imports.

import matplotlib.pyplot as plt
import cv2
import kornia as K
import kornia.feature as KF
import numpy as np
import torch
from kornia_moons.feature import *

def load_torch_image(fname):
    img = K.image_to_tensor(cv2.imread(fname), False).float() /255.
    img = K.color.bgr_to_rgb(img)
    return img

device = K.utils.get_cuda_device_if_available()
/home/docs/checkouts/readthedocs.org/user_builds/kornia-tutorials/envs/latest/lib/python3.7/site-packages/tqdm/auto.py:22: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
%%capture
fname1 = 'kn_church-2.jpg'
fname2 = 'kn_church-8.jpg'

img1 = load_torch_image(fname1)
img2 = load_torch_image(fname2)


feature = KF.KeyNetAffNetHardNet(5000, True).eval().to(device)

input_dict = {"image0": K.color.rgb_to_grayscale(img1), # LofTR works on grayscale images only 
              "image1": K.color.rgb_to_grayscale(img2)}

hw1 = torch.tensor(img1.shape[2:])
hw2 = torch.tensor(img1.shape[2:])

adalam_config = {"device": device}

with torch.inference_mode():
    lafs1, resps1, descs1 = feature(K.color.rgb_to_grayscale(img1))
    lafs2, resps2, descs2 = feature(K.color.rgb_to_grayscale(img2))
    dists, idxs = KF.match_adalam(descs1.squeeze(0), descs2.squeeze(0),
                                  lafs1, lafs2, # Adalam takes into account also geometric information
                                  config=adalam_config,
                                  hw1=hw1, hw2=hw2) # Adalam also benefits from knowing image size

print (f"{idxs.shape[0]} tentative matches with AdaLAM")
399 tentative matches with AdaLAM
def get_matching_keypoints(lafs1, lafs2, idxs):
    mkpts1 = KF.get_laf_center(lafs1).squeeze()[idxs[:,0]].detach().cpu().numpy()
    mkpts2 = KF.get_laf_center(lafs2).squeeze()[idxs[:,1]].detach().cpu().numpy()
    return mkpts1, mkpts2

mkpts1, mkpts2 = get_matching_keypoints(lafs1, lafs2, idxs)

Fm, inliers = cv2.findFundamentalMat(mkpts1, mkpts2, cv2.USAC_MAGSAC, 0.75, 0.999, 100000)
inliers = inliers > 0
print (f"{inliers.sum()} inliers with AdaLAM")
176 inliers with AdaLAM

inlier は緑色で不確かな (= tentative) 対応は黄色で描画しましょう :

draw_LAF_matches(
    lafs1,
    lafs2,
    idxs,
    K.tensor_to_image(img1),
    K.tensor_to_image(img2),
    inliers,
    draw_dict={'inlier_color': (0.2, 1, 0.2),
               'tentative_color': (1, 1, 0.2, 0.3), 
               'feature_color': None, 'vertical': False})

 

以上