Debian Codegraph @

src/pycolmap/feature/extraction.cc

raw
1 #include "colmap/feature/extractor.h"
2 #include "colmap/feature/sift.h"
3 #ifdef COLMAP_ONNX_ENABLED
4 #include "colmap/feature/aliked.h"
5 #include "colmap/feature/loma.h"
6 #endif
7
8 #include "pycolmap/helpers.h"
9 #include "pycolmap/sensor/bitmap.h"
10 #include "pycolmap/utils.h"
11
12 #include <algorithm>
13 #include <memory>
14
15 #include <Eigen/Core>
16 #include <pybind11/eigen.h>
17 #include <pybind11/numpy.h>
18 #include <pybind11/pybind11.h>
19
20 using namespace colmap;
21 using namespace pybind11::literals;
22 namespace py = pybind11;
23
24 template <typename dtype>
25 using pyimage_t =
26 Eigen::Matrix<dtype, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
27
28 typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
29 descriptors_t;
30 typedef std::tuple<FeatureKeypointsMatrix, descriptors_t> sift_output_t;
31
32 static std::map<int, std::unique_ptr<std::mutex>> sift_gpu_mutexes;
33
34 namespace {
35
36 class PyFeatureExtractor : public FeatureExtractor,
37 py::trampoline_self_life_support {
38 public:
39 static std::unique_ptr<FeatureExtractor> CreateOnDevice(
40 std::optional<FeatureExtractionOptions> options, Device device) {
41 if (options) {
42 if (options->use_gpu != IsGPU(device)) {
43 LOG(WARNING) << "FeatureExtractionOptions::use_gpu does not match "
44 "device. FeatureExtractionOptions::use_gpu is ignored.";
45 }
46 } else {
47 options = FeatureExtractionOptions();
48 }
49 options->use_gpu = IsGPU(device);
50 return THROW_CHECK_NOTNULL(FeatureExtractor::Create(*options));
51 }
52
53 bool Extract(const Bitmap& bitmap,
54 FeatureKeypoints* keypoints,
55 FeatureDescriptors* descriptors) override {
56 PYBIND11_OVERRIDE_PURE(
57 bool, FeatureExtractor, Extract, bitmap, keypoints, descriptors);
58 }
59 };
60
61 } // namespace
62
63 class Sift {
64 public:
65 Sift(std::optional<FeatureExtractionOptions> options, Device device)
66 : use_gpu_(IsGPU(device)) {
67 PyErr_WarnEx(PyExc_DeprecationWarning,
68 "pycolmap.Sift is deprecated, use "
69 "pycolmap.FeatureExtractor.create() instead.",
70 1);
71 if (options) {
72 options_ = std::move(*options);
73 }
74 options_.use_gpu = use_gpu_;
75 extractor_ = THROW_CHECK_NOTNULL(CreateSiftFeatureExtractor(options_));
76 }
77
78 sift_output_t Extract(const Eigen::Ref<const pyimage_t<uint8_t>>& image) {
79 Bitmap bitmap(image.cols(), image.rows(), /*as_rgb=*/false);
80 std::memcpy(bitmap.RowMajorData().data(), image.data(), bitmap.NumBytes());
81
82 const double scale = bitmap.Thumbnail(options_.EffMaxImageSize());
83
84 FeatureKeypoints feature_keypoints;
85 FeatureDescriptors feature_descriptors;
86 THROW_CHECK(
87 extractor_->Extract(bitmap, &feature_keypoints, &feature_descriptors));
88
89 FeatureKeypointsMatrix keypoints = KeypointsToMatrix(feature_keypoints);
90 const double inv_scale = 1.0 / scale;
91 keypoints.col(0) *= inv_scale;
92 keypoints.col(1) *= inv_scale;
93 keypoints.col(2) *= inv_scale;
94 descriptors_t descriptors = feature_descriptors.ToFloat().data;
95 descriptors /= 512.0f;
96
97 return std::make_tuple(std::move(keypoints), std::move(descriptors));
98 }
99
100 sift_output_t Extract(const Eigen::Ref<const pyimage_t<float>>& image) {
101 const pyimage_t<uint8_t> image_f = (image * 255.0f).cast<uint8_t>();
102 return Extract(image_f);
103 }
104
105 const FeatureExtractionOptions& Options() const { return options_; };
106
107 Device GetDevice() const { return (use_gpu_) ? Device::CUDA : Device::CPU; };
108
109 private:
110 std::unique_ptr<FeatureExtractor> extractor_;
111 FeatureExtractionOptions options_;
112 bool use_gpu_ = false;
113 };
114
115 void BindFeatureExtraction(py::module& m) {
116 auto PyNormalization =
117 py::enum_<SiftExtractionOptions::Normalization>(m, "Normalization")
118 .value("L1_ROOT",
119 SiftExtractionOptions::Normalization::L1_ROOT,
120 "L1-normalizes each descriptor followed by element-wise "
121 "square rooting. This normalization is usually better than "
122 "standard "
123 "L2-normalization. See 'Three things everyone should know "
124 "to improve object retrieval', Relja Arandjelovic and "
125 "Andrew Zisserman, CVPR 2012.")
126 .value("L2",
127 SiftExtractionOptions::Normalization::L2,
128 "Each vector is L2-normalized.");
129 AddStringToEnumConstructor(PyNormalization);
130
131 auto PySiftExtractionOptions =
132 py::classh<SiftExtractionOptions>(m, "SiftExtractionOptions")
133 .def(py::init<>())
134 .def_readwrite("max_num_features",
135 &SiftExtractionOptions::max_num_features,
136 "Maximum number of features to detect, keeping "
137 "larger-scale features.")
138 .def_readwrite("first_octave",
139 &SiftExtractionOptions::first_octave,
140 "First octave in the pyramid, i.e. -1 upsamples the "
141 "image by one level.")
142 .def_readwrite("num_octaves", &SiftExtractionOptions::num_octaves)
143 .def_readwrite("octave_resolution",
144 &SiftExtractionOptions::octave_resolution,
145 "Number of levels per octave.")
146 .def_readwrite("peak_threshold",
147 &SiftExtractionOptions::peak_threshold,
148 "Peak threshold for detection.")
149 .def_readwrite("edge_threshold",
150 &SiftExtractionOptions::edge_threshold,
151 "Edge threshold for detection.")
152 .def_readwrite("estimate_affine_shape",
153 &SiftExtractionOptions::estimate_affine_shape,
154 "Estimate affine shape of SIFT features in the form "
155 "of oriented ellipses as opposed to original SIFT "
156 "which estimates oriented disks.")
157 .def_readwrite("max_num_orientations",
158 &SiftExtractionOptions::max_num_orientations,
159 "Maximum number of orientations per keypoint if not "
160 "estimate_affine_shape.")
161 .def_readwrite("upright",
162 &SiftExtractionOptions::upright,
163 "Fix the orientation to 0 for upright features")
164 .def_readwrite("darkness_adaptivity",
165 &SiftExtractionOptions::darkness_adaptivity,
166 "Whether to adapt the feature detection depending "
167 "on the image darkness. only available on GPU.")
168 .def_readwrite(
169 "domain_size_pooling",
170 &SiftExtractionOptions::domain_size_pooling,
171 "\"Domain-Size Pooling in Local Descriptors and Network"
172 "Architectures\", J. Dong and S. Soatto, CVPR 2015")
173 .def_readwrite("dsp_min_scale", &SiftExtractionOptions::dsp_min_scale)
174 .def_readwrite("dsp_max_scale", &SiftExtractionOptions::dsp_max_scale)
175 .def_readwrite("dsp_num_scales",
176 &SiftExtractionOptions::dsp_num_scales)
177 .def_readwrite("normalization",
178 &SiftExtractionOptions::normalization,
179 "L1_ROOT or L2 descriptor normalization")
180 .def("check", &SiftExtractionOptions::Check);
181 MakeDataclass(PySiftExtractionOptions);
182
183 #ifdef COLMAP_ONNX_ENABLED
184 auto PyAlikedExtractionOptions =
185 py::classh<AlikedExtractionOptions>(m, "AlikedExtractionOptions")
186 .def(py::init<>())
187 .def_readwrite("max_num_features",
188 &AlikedExtractionOptions::max_num_features,
189 "Maximum number of features to detect, keeping "
190 "higher-score features.")
191 .def_readwrite("min_score",
192 &AlikedExtractionOptions::min_score,
193 "Minimum score threshold for keypoint detection.")
194 .def_readwrite("n16rot_model_path",
195 &AlikedExtractionOptions::n16rot_model_path,
196 "Path to the ONNX model file for the n16rot ALIKED "
197 "extractor.")
198 .def_readwrite("n32_model_path",
199 &AlikedExtractionOptions::n32_model_path,
200 "Path to the ONNX model file for the n32 ALIKED "
201 "extractor.")
202 .def("check", &AlikedExtractionOptions::Check);
203 MakeDataclass(PyAlikedExtractionOptions);
204
205 auto PyLomaExtractionOptions =
206 py::classh<LomaExtractionOptions>(m, "LomaExtractionOptions")
207 .def(py::init<>())
208 .def_readwrite("max_num_features",
209 &LomaExtractionOptions::max_num_features,
210 "Number of keypoints to detect. Recommended is to "
211 "use either 2048 or 4096.")
212 .def_readwrite("min_score",
213 &LomaExtractionOptions::min_score,
214 "Minimum score threshold for keypoint detection.")
215 .def_readwrite("use_bf16",
216 &LomaExtractionOptions::use_bf16,
217 "Whether to use the bf16 descriptor variant when "
218 "supported by the selected ONNX execution provider "
219 "(only affects LOMA_B; falls back to fp32 otherwise).")
220 .def_readwrite("use_fast_resize",
221 &LomaExtractionOptions::use_fast_resize,
222 "Whether to downsize each image to the "
223 "descriptor's fixed input resolution with a fast "
224 "bilinear resample instead of a higher-quality "
225 "filtered resize. ~2-3x faster on high-resolution "
226 "images, at a small AUC cost visible only at the "
227 "tightest rotation-error thresholds.")
228 .def_readwrite("detector_model_path",
229 &LomaExtractionOptions::detector_model_path,
230 "Path to the ONNX model file for the LoMa detector "
231 "(shared across all variants).")
232 .def_readwrite(
233 "descriptor_model_path",
234 &LomaExtractionOptions::descriptor_model_path,
235 "Path to the fp32 ONNX model file for the LOMA_B descriptor.")
236 .def_readwrite(
237 "descriptor_model_path_bf16",
238 &LomaExtractionOptions::descriptor_model_path_bf16,
239 "Path to the bf16 ONNX model file for the LOMA_B descriptor.")
240 .def_readwrite(
241 "descriptor_b128_model_path",
242 &LomaExtractionOptions::descriptor_b128_model_path,
243 "Path to the ONNX model file for the LOMA_B128 descriptor.")
244 .def("check", &LomaExtractionOptions::Check);
245 MakeDataclass(PyLomaExtractionOptions);
246 #endif
247
248 auto PyFeatureExtractionOptions =
249 py::classh<FeatureExtractionOptions>(m, "FeatureExtractionOptions")
250 .def(py::init<FeatureExtractorType>(),
251 "type"_a = FeatureExtractorType::SIFT)
252 .def_readwrite("type", &FeatureExtractionOptions::type)
253 .def_readwrite(
254 "max_image_size",
255 &FeatureExtractionOptions::max_image_size,
256 "Maximum image size, otherwise image will be down-scaled. If "
257 "max_image_size is non-positive, the appropriate size is "
258 "selected automatically based on the extractor type.")
259 .def_readwrite("num_threads",
260 &FeatureExtractionOptions::num_threads,
261 "Number of threads for feature matching and "
262 "geometric verification.")
263 .def_readwrite("use_gpu", &FeatureExtractionOptions::use_gpu)
264 .def_readwrite("gpu_index",
265 &FeatureExtractionOptions::gpu_index,
266 "Index of the GPU used for feature matching. For "
267 "multi-GPU matching, you should separate multiple "
268 "GPU indices by comma, e.g., '0,1,2,3'.")
269 .def_readwrite("sift", &FeatureExtractionOptions::sift)
270
271 .def("requires_rgb", &FeatureExtractionOptions::RequiresRGB)
272 .def("requires_opengl", &FeatureExtractionOptions::RequiresOpenGL)
273 .def("eff_max_image_size", &FeatureExtractionOptions::EffMaxImageSize)
274 .def("check", &FeatureExtractionOptions::Check);
275 #ifdef COLMAP_ONNX_ENABLED
276 PyFeatureExtractionOptions.def_readwrite("aliked",
277 &FeatureExtractionOptions::aliked);
278 PyFeatureExtractionOptions.def_readwrite("loma",
279 &FeatureExtractionOptions::loma);
280 #endif
281 MakeDataclass(PyFeatureExtractionOptions);
282
283 py::classh<FeatureExtractor, PyFeatureExtractor>(m, "FeatureExtractor")
284 .def_static("create",
285 &PyFeatureExtractor::CreateOnDevice,
286 "options"_a = std::nullopt,
287 "device"_a = Device::AUTO)
288 .def(
289 "extract",
290 [](FeatureExtractor& self, const Bitmap& bitmap) {
291 FeatureKeypoints keypoints;
292 FeatureDescriptors descriptors;
293 THROW_CHECK(self.Extract(bitmap, &keypoints, &descriptors));
294 return py::make_tuple(std::move(keypoints), std::move(descriptors));
295 },
296 "bitmap"_a,
297 "Extract features from a Bitmap. Returns (FeatureKeypoints, "
298 "FeatureDescriptors).")
299 .def(
300 "extract_from_uint8_array",
301 [](FeatureExtractor& self,
302 py::array_t<uint8_t, py::array::c_style> image) {
303 const Bitmap bitmap = BitmapFromArray(image);
304 FeatureKeypoints keypoints;
305 FeatureDescriptors descriptors;
306 THROW_CHECK(self.Extract(bitmap, &keypoints, &descriptors));
307 return py::make_tuple(std::move(keypoints), std::move(descriptors));
308 },
309 "image"_a,
310 "Extract features from a uint8 numpy array with shape (H, W) or "
311 "(H, W, 3). Returns (FeatureKeypoints, FeatureDescriptors).")
312 .def(
313 "extract_from_float32_array",
314 [](FeatureExtractor& self,
315 py::array_t<float, py::array::c_style> image) {
316 auto buf = image.request();
317 std::vector<size_t> shape(buf.shape.begin(), buf.shape.end());
318 py::array_t<uint8_t> image_u8(shape);
319 const float* src = static_cast<const float*>(buf.ptr);
320 uint8_t* dst = static_cast<uint8_t*>(image_u8.request().ptr);
321 const size_t num_elements = buf.size;
322 for (size_t i = 0; i < num_elements; ++i) {
323 dst[i] = static_cast<uint8_t>(
324 std::clamp(src[i] * 255.0f, 0.0f, 255.0f));
325 }
326 const Bitmap bitmap = BitmapFromArray(image_u8);
327 FeatureKeypoints keypoints;
328 FeatureDescriptors descriptors;
329 THROW_CHECK(self.Extract(bitmap, &keypoints, &descriptors));
330 return py::make_tuple(std::move(keypoints), std::move(descriptors));
331 },
332 "image"_a,
333 "Extract features from a float32 numpy array with values in "
334 "[0, 1] and shape (H, W) or (H, W, 3). Returns "
335 "(FeatureKeypoints, FeatureDescriptors).");
336
337 py::classh<Sift>(m, "Sift")
338 .def(py::init<std::optional<FeatureExtractionOptions>, Device>(),
339 "options"_a = std::nullopt,
340 "device"_a = Device::AUTO)
341 .def("extract",
342 py::overload_cast<const Eigen::Ref<const pyimage_t<uint8_t>>&>(
343 &Sift::Extract),
344 "image"_a.noconvert())
345 .def("extract",
346 py::overload_cast<const Eigen::Ref<const pyimage_t<float>>&>(
347 &Sift::Extract),
348 "image"_a.noconvert())
349 .def_property_readonly("options", &Sift::Options)
350 .def_property_readonly("device", &Sift::GetDevice);
351 }