From 7ef1ed996467f67436489e05b3626d84823b8e31 Mon Sep 17 00:00:00 2001 From: Lixin Xue Date: Sun, 24 Jan 2021 15:44:32 +0100 Subject: [PATCH 1/6] add disk feature extractor --- .gitmodules | 3 ++ hloc/extractors/disk.py | 117 ++++++++++++++++++++++++++++++++++++++++ third_party/disk | 1 + 3 files changed, 121 insertions(+) create mode 100644 hloc/extractors/disk.py create mode 160000 third_party/disk diff --git a/.gitmodules b/.gitmodules index 2f589b66..83996aac 100644 --- a/.gitmodules +++ b/.gitmodules @@ -5,3 +5,6 @@ path = third_party/SuperGluePretrainedNetwork url = https://github.com/skydes/SuperGluePretrainedNetwork.git branch = fix-memory +[submodule "third_party/disk"] + path = third_party/disk + url = https://github.com/cvlab-epfl/disk.git diff --git a/hloc/extractors/disk.py b/hloc/extractors/disk.py new file mode 100644 index 00000000..a339eac0 --- /dev/null +++ b/hloc/extractors/disk.py @@ -0,0 +1,117 @@ +import sys +from pathlib import Path +from functools import partial +import torch +import torch.nn.functional as F + +from ..utils.base_model import BaseModel + +disk_path = Path(__file__).parent / "../../third_party/disk" +sys.path.append(str(disk_path)) +from disk import DISK as _DISK + +class DISK(BaseModel): + default_conf = { + 'model_name': 'depth-save.pth', # Name of the model's .pth save file + # we rescale image only in the preprocessing step. + # we only pad the image size to be the multiple of 16 in this model + # 'height': None, # rescaled height (px). If unspecified, image is not resized in height dimension + # 'width': None, # rescaled width (px). If unspecified, image is not resized in width dimension + 'window': 5, # NMS window size + 'n': None, # Maximum number of features to extract. If unspecified, the number is not limited + 'desc-dim': 128, # descriptor dimension. Needs to match the checkpoint value + 'mode': 'nms', # Whether to extract features using the non-maxima suppresion mode or through training-time grid sampling technique + } + required_data_keys = ['image'] + + def _init(self, conf): + state_dict = torch.load(disk_path / conf['model_name'], map_location='cpu') + + if 'extractor' in state_dict: + weights = state_dict['extractor'] + elif 'disk' in state_dict: + weights = state_dict['disk'] + else: + raise KeyError('Incompatible weight file!') + self.model = _DISK(window=8, desc_dim=conf['desc-dim']) + self.model.load_state_dict(weights) + self.model.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu')) + if conf['mode'] == 'nms': + self.extract = partial( + self.model.features, + kind='nms', + window_size=conf['window'], + cutoff=0., + n=conf['n'] + ) + elif conf['mode'] == 'rng': + self.extract = partial(self.model.features, kind='rng') + else: + raise KeyError('mode must be either nms or rng!') + + def _forward(self, data): + img = data['image'][0] + assert len(img.shape) == 3 and img.shape[0] == 3 + # pad img so that its height and width be the multiple of 16 as required by the original repo + orig_h, orig_w = img.shape[1:] + new_h = ((orig_h-1)//16 + 1) * 16 + new_w = ((orig_w-1)//16 + 1) * 16 + y_pad = new_h - orig_h + x_pad = new_w - orig_w + + img = F.pad(img, (0, x_pad, 0, y_pad)) + assert img.shape[1] == new_h and img.shape[2] == new_w, "Wrong Padding!" + # print(orig_h, orig_w, new_h, new_w, img.shape) + # print(img[0, 0, :]) + # print(img[0, :, 0]) + + with torch.no_grad(): + try: + batched_features = self.extract(img[None]) # add batch dimension + except RuntimeError as e: + if 'U-Net failed' in str(e): + msg = ('Please use input size which is multiple of 16 (or ' + 'adjust the --height and --width flags to let this ' + 'script rescale it automatically). This is because ' + 'we internally use a U-Net with 4 downsampling ' + 'steps, each by a factor of 2, therefore 2^4=16.') + raise RuntimeError(msg) from e + else: + raise + + assert(len(batched_features) == 1) + features = batched_features[0] + for features in batched_features.flat: + features = features.to(torch.device('cpu')) + + kps_crop_space = features.kp.t() + + # TODO: start from here! + # we didn't rescale so no need for this + # kps_img_space, mask = image.to_image_coord(kps_crop_space) + kps_img_space = kps_crop_space # (2, N) + x = kps_crop_space[0, :] + y = kps_crop_space[1, :] + mask = (0 <= x) & (x < orig_w) & (0 <= y) & (y < orig_h) + + + keypoints = kps_img_space.t()[mask] + descriptors = features.desc[mask] + scores = features.kp_logp[mask] + + order = torch.argsort(-scores) + # order_gt = np.argsort(scores.cpu().numpy())[::-1] + # print(len(order)) + # print(np.sum(order.cpu().numpy() == order_gt)) + # assert np.all(order.cpu().numpy() == order_gt) + + keypoints = keypoints[order] + descriptors = descriptors[order] + scores = scores[order] + + assert descriptors.shape[1] == self.conf['desc-dim'] + assert keypoints.shape[1] == 2 + + pred = {'keypoints': keypoints[None], 'descriptors':descriptors.t()[None], 'scores':scores[None]} + return pred + diff --git a/third_party/disk b/third_party/disk new file mode 160000 index 00000000..eafa0ee8 --- /dev/null +++ b/third_party/disk @@ -0,0 +1 @@ +Subproject commit eafa0ee80d26f86d6c838b78cea8ae4c9abd4b51 From 0a30c0ea03b1d4f377766f1f6374d0ec3632bd18 Mon Sep 17 00:00:00 2001 From: Lixin Xue Date: Fri, 5 Feb 2021 13:01:06 +0100 Subject: [PATCH 2/6] rename required_data_keys to required_inputs --- hloc/extractors/disk.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hloc/extractors/disk.py b/hloc/extractors/disk.py index a339eac0..452cf7d7 100644 --- a/hloc/extractors/disk.py +++ b/hloc/extractors/disk.py @@ -22,7 +22,7 @@ class DISK(BaseModel): 'desc-dim': 128, # descriptor dimension. Needs to match the checkpoint value 'mode': 'nms', # Whether to extract features using the non-maxima suppresion mode or through training-time grid sampling technique } - required_data_keys = ['image'] + required_inputs = ['image'] def _init(self, conf): state_dict = torch.load(disk_path / conf['model_name'], map_location='cpu') From cdf96ff7fe9e99f654e77ecfb1b2e442259f52f9 Mon Sep 17 00:00:00 2001 From: Lixin Xue Date: Fri, 5 Feb 2021 13:15:11 +0100 Subject: [PATCH 3/6] remove debugging code --- hloc/extractors/disk.py | 8 -------- 1 file changed, 8 deletions(-) diff --git a/hloc/extractors/disk.py b/hloc/extractors/disk.py index 452cf7d7..e9878efc 100644 --- a/hloc/extractors/disk.py +++ b/hloc/extractors/disk.py @@ -61,9 +61,6 @@ def _forward(self, data): img = F.pad(img, (0, x_pad, 0, y_pad)) assert img.shape[1] == new_h and img.shape[2] == new_w, "Wrong Padding!" - # print(orig_h, orig_w, new_h, new_w, img.shape) - # print(img[0, 0, :]) - # print(img[0, :, 0]) with torch.no_grad(): try: @@ -86,7 +83,6 @@ def _forward(self, data): kps_crop_space = features.kp.t() - # TODO: start from here! # we didn't rescale so no need for this # kps_img_space, mask = image.to_image_coord(kps_crop_space) kps_img_space = kps_crop_space # (2, N) @@ -100,10 +96,6 @@ def _forward(self, data): scores = features.kp_logp[mask] order = torch.argsort(-scores) - # order_gt = np.argsort(scores.cpu().numpy())[::-1] - # print(len(order)) - # print(np.sum(order.cpu().numpy() == order_gt)) - # assert np.all(order.cpu().numpy() == order_gt) keypoints = keypoints[order] descriptors = descriptors[order] From 91945e8be7b6aeea5087dcf9074367efa2016929 Mon Sep 17 00:00:00 2001 From: Lixin Xue Date: Fri, 5 Feb 2021 13:23:10 +0100 Subject: [PATCH 4/6] add DIR submodule to resolve conflicts --- .gitmodules | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitmodules b/.gitmodules index 83996aac..b8866808 100644 --- a/.gitmodules +++ b/.gitmodules @@ -5,6 +5,9 @@ path = third_party/SuperGluePretrainedNetwork url = https://github.com/skydes/SuperGluePretrainedNetwork.git branch = fix-memory +[submodule "third_party/deep-image-retrieval"] + path = third_party/deep-image-retrieval + url = https://github.com/naver/deep-image-retrieval.git [submodule "third_party/disk"] path = third_party/disk url = https://github.com/cvlab-epfl/disk.git From 209ede1d85d55b4475afadbf6a86a94ef2bca49f Mon Sep 17 00:00:00 2001 From: Lixin Xue Date: Fri, 12 Feb 2021 17:36:44 +0100 Subject: [PATCH 5/6] remove unnessary comments, try-except block, device handling & no_grad. Rename model conf parameters --- hloc/extractors/disk.py | 100 +++++++++++++++++----------------------- 1 file changed, 42 insertions(+), 58 deletions(-) diff --git a/hloc/extractors/disk.py b/hloc/extractors/disk.py index e9878efc..8841ce70 100644 --- a/hloc/extractors/disk.py +++ b/hloc/extractors/disk.py @@ -10,22 +10,20 @@ sys.path.append(str(disk_path)) from disk import DISK as _DISK + class DISK(BaseModel): default_conf = { - 'model_name': 'depth-save.pth', # Name of the model's .pth save file - # we rescale image only in the preprocessing step. - # we only pad the image size to be the multiple of 16 in this model - # 'height': None, # rescaled height (px). If unspecified, image is not resized in height dimension - # 'width': None, # rescaled width (px). If unspecified, image is not resized in width dimension - 'window': 5, # NMS window size - 'n': None, # Maximum number of features to extract. If unspecified, the number is not limited - 'desc-dim': 128, # descriptor dimension. Needs to match the checkpoint value - 'mode': 'nms', # Whether to extract features using the non-maxima suppresion mode or through training-time grid sampling technique + 'model_name': 'depth-save.pth', + 'max_keypoints': None, + 'desc_dim': 128, + 'mode': 'nms', + 'nms_window_size': 5, } required_inputs = ['image'] def _init(self, conf): - state_dict = torch.load(disk_path / conf['model_name'], map_location='cpu') + state_dict = torch.load(disk_path/conf['model_name'], + map_location='cpu') if 'extractor' in state_dict: weights = state_dict['extractor'] @@ -35,7 +33,6 @@ def _init(self, conf): raise KeyError('Incompatible weight file!') self.model = _DISK(window=8, desc_dim=conf['desc-dim']) self.model.load_state_dict(weights) - self.model.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu')) if conf['mode'] == 'nms': self.extract = partial( self.model.features, @@ -52,7 +49,8 @@ def _init(self, conf): def _forward(self, data): img = data['image'][0] assert len(img.shape) == 3 and img.shape[0] == 3 - # pad img so that its height and width be the multiple of 16 as required by the original repo + # pad img so that its height and width be the multiple of 16 + # as required by the original dis repo orig_h, orig_w = img.shape[1:] new_h = ((orig_h-1)//16 + 1) * 16 new_w = ((orig_w-1)//16 + 1) * 16 @@ -60,50 +58,36 @@ def _forward(self, data): x_pad = new_w - orig_w img = F.pad(img, (0, x_pad, 0, y_pad)) - assert img.shape[1] == new_h and img.shape[2] == new_w, "Wrong Padding!" - - with torch.no_grad(): - try: - batched_features = self.extract(img[None]) # add batch dimension - except RuntimeError as e: - if 'U-Net failed' in str(e): - msg = ('Please use input size which is multiple of 16 (or ' - 'adjust the --height and --width flags to let this ' - 'script rescale it automatically). This is because ' - 'we internally use a U-Net with 4 downsampling ' - 'steps, each by a factor of 2, therefore 2^4=16.') - raise RuntimeError(msg) from e - else: - raise - - assert(len(batched_features) == 1) - features = batched_features[0] - for features in batched_features.flat: - features = features.to(torch.device('cpu')) - - kps_crop_space = features.kp.t() - - # we didn't rescale so no need for this - # kps_img_space, mask = image.to_image_coord(kps_crop_space) - kps_img_space = kps_crop_space # (2, N) - x = kps_crop_space[0, :] - y = kps_crop_space[1, :] - mask = (0 <= x) & (x < orig_w) & (0 <= y) & (y < orig_h) - - - keypoints = kps_img_space.t()[mask] - descriptors = features.desc[mask] - scores = features.kp_logp[mask] - - order = torch.argsort(-scores) - - keypoints = keypoints[order] - descriptors = descriptors[order] - scores = scores[order] - - assert descriptors.shape[1] == self.conf['desc-dim'] - assert keypoints.shape[1] == 2 - - pred = {'keypoints': keypoints[None], 'descriptors':descriptors.t()[None], 'scores':scores[None]} - return pred + assert img.shape[1] == new_h and img.shape[2] == new_w, "Wrong Padding" + + batched_features = self.extract(img[None]) # add batch dimension + + assert(len(batched_features) == 1) + features = batched_features[0] + for features in batched_features.flat: + features = features.to(torch.device('cpu')) + + kps_crop_space = features.kp.t() + + kps_img_space = kps_crop_space # (2, N) + x = kps_crop_space[0, :] + y = kps_crop_space[1, :] + mask = (0 <= x) & (x <= orig_w-1) & (0 <= y) & (y <= orig_h-1) + + keypoints = kps_img_space.t()[mask] + descriptors = features.desc[mask] + scores = features.kp_logp[mask] + + order = torch.argsort(-scores) + + keypoints = keypoints[order] + descriptors = descriptors[order] + scores = scores[order] + + assert descriptors.shape[1] == self.conf['desc-dim'] + assert keypoints.shape[1] == 2 + pred = {'keypoints': keypoints[None], + 'descriptors': descriptors.t()[None], + 'scores': scores[None]} + return pred From e1d9222983cb92771eb691eb693272264a508aef Mon Sep 17 00:00:00 2001 From: Lixin Xue Date: Fri, 12 Feb 2021 19:03:29 +0100 Subject: [PATCH 6/6] fix typos and validate with original repo (>97% keypoints overlap) --- hloc/extractors/disk.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/hloc/extractors/disk.py b/hloc/extractors/disk.py index 8841ce70..4545eb0e 100644 --- a/hloc/extractors/disk.py +++ b/hloc/extractors/disk.py @@ -31,15 +31,15 @@ def _init(self, conf): weights = state_dict['disk'] else: raise KeyError('Incompatible weight file!') - self.model = _DISK(window=8, desc_dim=conf['desc-dim']) + self.model = _DISK(window=8, desc_dim=conf['desc_dim']) self.model.load_state_dict(weights) if conf['mode'] == 'nms': self.extract = partial( self.model.features, kind='nms', - window_size=conf['window'], + window_size=conf['nms_window_size'], cutoff=0., - n=conf['n'] + n=conf['max_keypoints'] ) elif conf['mode'] == 'rng': self.extract = partial(self.model.features, kind='rng') @@ -84,7 +84,7 @@ def _forward(self, data): descriptors = descriptors[order] scores = scores[order] - assert descriptors.shape[1] == self.conf['desc-dim'] + assert descriptors.shape[1] == self.conf['desc_dim'] assert keypoints.shape[1] == 2 pred = {'keypoints': keypoints[None],