|
| 1 | +""" |
| 2 | +Copyright (c) 2024 Intel Corporation |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +""" |
| 16 | + |
| 17 | +import os |
| 18 | +from pathlib import Path |
| 19 | +import numpy as np |
| 20 | +from .format_converter import DirectoryBasedAnnotationConverter, ConverterReturn |
| 21 | +from ..config import NumberField, StringField |
| 22 | +from ..representation import ImageFeatureAnnotation |
| 23 | +from ..utils import UnsupportedPackage |
| 24 | +from ..data_readers import AnnotationDataIdentifier |
| 25 | +from ..progress_reporters import TQDMReporter |
| 26 | + |
| 27 | + |
| 28 | +# Large images that were ignored in previous papers |
| 29 | +ignored_scenes = ( |
| 30 | + "i_contruction", |
| 31 | + "i_crownnight", |
| 32 | + "i_dc", |
| 33 | + "i_pencils", |
| 34 | + "i_whitebuilding", |
| 35 | + "v_artisans", |
| 36 | + "v_astronautis", |
| 37 | + "v_talent", |
| 38 | +) |
| 39 | + |
| 40 | + |
| 41 | +class HpatchesConverter(DirectoryBasedAnnotationConverter): |
| 42 | + __provider__ = 'hpatches_with_kornia_feature' |
| 43 | + |
| 44 | + @classmethod |
| 45 | + def parameters(cls): |
| 46 | + params = super().parameters() |
| 47 | + params.update({ |
| 48 | + 'sequences_dir_name': StringField( |
| 49 | + optional=True, default='hpatches-sequences-release', |
| 50 | + description="Dataset subfolder name, where hpatches sequences are located." |
| 51 | + ), |
| 52 | + 'max_num_keypoints': NumberField( |
| 53 | + optional=True, default=512, value_type=int, min_value=128, max_value=2048, |
| 54 | + description='Maksimum number of image keypoints.' |
| 55 | + ), |
| 56 | + 'image_side_size': NumberField( |
| 57 | + optional=True, default=480, value_type=int, min_value=128, max_value=2048, |
| 58 | + description='Image short side size.' |
| 59 | + ) |
| 60 | + }) |
| 61 | + |
| 62 | + return params |
| 63 | + |
| 64 | + def configure(self): |
| 65 | + try: |
| 66 | + import torch # pylint: disable=import-outside-toplevel |
| 67 | + self._torch = torch |
| 68 | + except ImportError as torch_import_error: |
| 69 | + UnsupportedPackage('torch', torch_import_error.msg).raise_error(self.__provider__) |
| 70 | + try: |
| 71 | + import kornia # pylint: disable=import-outside-toplevel |
| 72 | + self._kornia = kornia |
| 73 | + except ImportError as kornia_import_error: |
| 74 | + UnsupportedPackage('kornia', kornia_import_error.msg).raise_error(self.__provider__) |
| 75 | + |
| 76 | + |
| 77 | + self.data_dir = self.get_value_from_config('data_dir') |
| 78 | + self.sequences_dir = self.get_value_from_config('sequences_dir_name') |
| 79 | + self.max_num_keypoints = self.get_value_from_config('max_num_keypoints') |
| 80 | + self.side_size = self.get_value_from_config('image_side_size') |
| 81 | + |
| 82 | + def _get_new_image_size(self, h: int, w: int): |
| 83 | + side_size = self.side_size |
| 84 | + aspect_ratio = w / h |
| 85 | + if aspect_ratio < 1.0: |
| 86 | + size = int(side_size / aspect_ratio), side_size |
| 87 | + else: |
| 88 | + size = side_size, int(side_size * aspect_ratio) |
| 89 | + return size |
| 90 | + |
| 91 | + |
| 92 | + def _get_image_data(self, path, image_size = None): |
| 93 | + img = self._kornia.io.load_image(path, self._kornia.io.ImageLoadType.RGB32, device='cpu')[None, ...] |
| 94 | + |
| 95 | + h, w = img.shape[-2:] |
| 96 | + size = h, w |
| 97 | + size = self._get_new_image_size(h, w) |
| 98 | + if image_size and size != image_size: |
| 99 | + size = image_size |
| 100 | + img = self._kornia.geometry.transform.resize( |
| 101 | + img, |
| 102 | + size, |
| 103 | + side='short', |
| 104 | + antialias=True, |
| 105 | + align_corners=None, |
| 106 | + interpolation='bilinear', |
| 107 | + ) |
| 108 | + scale = self._torch.Tensor([img.shape[-1] / w, img.shape[-2] / h]).to(img) |
| 109 | + T = np.diag([scale[0], scale[1], 1]) |
| 110 | + |
| 111 | + data = { |
| 112 | + "scales": scale, |
| 113 | + "image_size": np.array(size[::-1]), |
| 114 | + "transform": T, |
| 115 | + "original_image_size": np.array([w, h]), |
| 116 | + "image" : img |
| 117 | + } |
| 118 | + return data |
| 119 | + |
| 120 | + @staticmethod |
| 121 | + def _read_homography(path): |
| 122 | + with open(path, encoding="utf-8") as f: |
| 123 | + result = [] |
| 124 | + for line in f.readlines(): |
| 125 | + while " " in line: # Remove double spaces |
| 126 | + line = line.replace(" ", " ") |
| 127 | + line = line.replace(" \n", "").replace("\n", "") |
| 128 | + # Split and discard empty strings |
| 129 | + elements = list(filter(lambda s: s, line.split(" "))) |
| 130 | + if elements: |
| 131 | + result.append(elements) |
| 132 | + return np.array(result).astype(float) |
| 133 | + |
| 134 | + def get_image_features(self, model, data): |
| 135 | + with self._torch.inference_mode(): |
| 136 | + return model(data["image"], self.max_num_keypoints, pad_if_not_divisible=True)[0] |
| 137 | + |
| 138 | + def convert(self, check_content=False, progress_callback=None, progress_interval=50, **kwargs): |
| 139 | + annotations = [] |
| 140 | + items = [] |
| 141 | + |
| 142 | + sequences_dir = Path(os.path.join(self.data_dir, self.sequences_dir)) |
| 143 | + sequences = sorted([x.name for x in sequences_dir.iterdir()]) |
| 144 | + |
| 145 | + for seq in sequences: |
| 146 | + if seq in ignored_scenes: |
| 147 | + continue |
| 148 | + for i in range(2, 7): |
| 149 | + items.append((seq, i, seq[0] == "i")) |
| 150 | + |
| 151 | + disk_model = self._kornia.feature.DISK().from_pretrained("depth") |
| 152 | + |
| 153 | + num_iterations = len(items) |
| 154 | + progress_reporter = TQDMReporter(print_interval=progress_interval) |
| 155 | + progress_reporter.reset(num_iterations) |
| 156 | + |
| 157 | + for item_id, item in enumerate(items): |
| 158 | + seq, idx, _ = item |
| 159 | + |
| 160 | + if idx == 2: |
| 161 | + img_path = Path(sequences_dir / seq / "1.ppm") |
| 162 | + data0 = self._get_image_data(img_path) |
| 163 | + features0 = self.get_image_features(disk_model, data0) |
| 164 | + |
| 165 | + img_path = Path(sequences_dir / seq / f"{idx}.ppm") |
| 166 | + data1 = self._get_image_data(img_path) |
| 167 | + features1 = self.get_image_features(disk_model, data1) |
| 168 | + |
| 169 | + H = self._read_homography(Path(sequences_dir / seq / f"H_1_{idx}")) |
| 170 | + H = data1["transform"] @ H @ np.linalg.inv(data0["transform"]) |
| 171 | + |
| 172 | + data = { |
| 173 | + "keypoints0": features0.keypoints.unsqueeze(0), |
| 174 | + "keypoints1": features1.keypoints.unsqueeze(0), |
| 175 | + "descriptors0": features0.descriptors.unsqueeze(0), |
| 176 | + "descriptors1" : features1.descriptors.unsqueeze(0), |
| 177 | + "image_size0": data0["image_size"], |
| 178 | + "image_size1": data1["image_size"], |
| 179 | + "H_0to1": H |
| 180 | + } |
| 181 | + |
| 182 | + sequence = f"{seq}/{idx}" |
| 183 | + annotated_id = AnnotationDataIdentifier(sequence, data) |
| 184 | + annotation = ImageFeatureAnnotation( |
| 185 | + identifier = annotated_id, |
| 186 | + sequence = sequence |
| 187 | + ) |
| 188 | + annotations.append(annotation) |
| 189 | + progress_reporter.update(item_id, 1) |
| 190 | + |
| 191 | + progress_reporter.finish() |
| 192 | + return ConverterReturn(annotations, None, None) |
0 commit comments