Debian Codegraph @

src/pycolmap/pybind11_extension.h

raw
1 #pragma once
2
3 #include "colmap/util/hash_containers.h"
4 #include "colmap/util/types.h"
5
6 #include "pycolmap/feature/opaque_types.h"
7
8 #include <memory>
9 #include <string>
10
11 #include <Eigen/Geometry>
12 #include <pybind11/cast.h>
13 #include <pybind11/eigen.h>
14 #include <pybind11/numpy.h>
15 #include <pybind11/pybind11.h>
16 #include <pybind11/pytypes.h>
17 #include <pybind11/stl.h>
18 #include <pybind11/stl/filesystem.h>
19 #include <pybind11/stl_bind.h>
20
21 namespace pycolmap {
22
23 // Wrapper for Rotation3d that can hold either owned data or a view into
24 // existing memory (e.g., Rigid3d.params). This enables zero-copy access
25 // to rotation data while providing the full quaternion interface.
26 struct Rotation3dWrapper {
27 pybind11::array_t<double> data;
28
29 // Default constructor - creates owned identity quaternion
30 Rotation3dWrapper() : data(4) { map() = Eigen::Quaterniond::Identity(); }
31
32 // Copy from Eigen::Quaterniond - creates owned data
33 explicit Rotation3dWrapper(const Eigen::Quaterniond& q) : data(4) {
34 map() = q;
35 }
36
37 // From xyzw coefficients
38 explicit Rotation3dWrapper(const Eigen::Vector4d& xyzw) : data(4) {
39 map().coeffs() = xyzw;
40 }
41
42 // From rotation matrix
43 explicit Rotation3dWrapper(const Eigen::Matrix3d& matrix) : data(4) {
44 map() = Eigen::Quaterniond(matrix);
45 }
46
47 // From axis-angle vector
48 explicit Rotation3dWrapper(const Eigen::Vector3d& axis_angle) : data(4) {
49 map() = Eigen::Quaterniond(
50 Eigen::AngleAxisd(axis_angle.norm(), axis_angle.normalized()));
51 }
52
53 // View constructor - borrows existing array (zero-copy)
54 explicit Rotation3dWrapper(pybind11::array_t<double> arr)
55 : data(std::move(arr)) {}
56
57 Eigen::Map<Eigen::Quaterniond> map() {
58 return Eigen::Map<Eigen::Quaterniond>(data.mutable_data());
59 }
60
61 Eigen::Map<const Eigen::Quaterniond> map() const {
62 return Eigen::Map<const Eigen::Quaterniond>(data.data());
63 }
64 };
65
66 } // namespace pycolmap
67
68 namespace PYBIND11_NAMESPACE {
69 namespace detail {
70
71 // Type caster to allow functions taking Eigen::Quaterniond to accept
72 // Rotation3dWrapper, and functions returning Eigen::Quaterniond to return
73 // Rotation3dWrapper.
74 template <>
75 struct type_caster<Eigen::Quaterniond> {
76 PYBIND11_TYPE_CASTER(Eigen::Quaterniond, const_name("Rotation3d"));
77
78 // Python -> C++ (when calling functions that take Eigen::Quaterniond)
79 bool load(handle src, bool) {
80 // Try to load from Rotation3dWrapper
81 if (isinstance<pycolmap::Rotation3dWrapper>(src)) {
82 value = src.cast<pycolmap::Rotation3dWrapper&>().map();
83 return true;
84 }
85 // Also accept raw numpy arrays
86 try {
87 auto arr = src.cast<pybind11::array_t<double>>();
88 if (arr.size() == 4) {
89 value = Eigen::Map<const Eigen::Quaterniond>(arr.data());
90 return true;
91 }
92 } catch (...) {
93 }
94 return false;
95 }
96
97 // C++ -> Python (when returning Eigen::Quaterniond)
98 static handle cast(const Eigen::Quaterniond& src,
99 return_value_policy,
100 handle) {
101 pycolmap::Rotation3dWrapper wrapper(src);
102 return pybind11::cast(std::move(wrapper)).release();
103 }
104 };
105
106 // Bind COLMAP's backport implementation of std::span. This copies the content
107 // into a list. We could instead create a view with an Eigen::Map but the cast
108 // should be explicit and cannot be automatic - likely not worth the added
109 // logic.
110 template <typename Type>
111 struct type_caster<colmap::span<Type>> : list_caster<colmap::span<Type>, Type> {
112 };
113
114 // Autocast from numpy.ndarray to std::vector<Eigen::Vector>
115 template <typename Scalar, int Size>
116 struct type_caster<std::vector<Eigen::Matrix<Scalar, Size, 1>>> {
117 public:
118 using MatrixType =
119 typename Eigen::Matrix<Scalar, Eigen::Dynamic, Size, Eigen::RowMajor>;
120 using VectorType = typename Eigen::Matrix<Scalar, Size, 1>;
121 using props = EigenProps<MatrixType>;
122 PYBIND11_TYPE_CASTER(std::vector<VectorType>, props::descriptor);
123
124 bool load(handle src, bool) {
125 const auto buf = array::ensure(src);
126 if (!buf) {
127 return false;
128 }
129 const buffer_info info = buf.request();
130 if (info.ndim != 2 || info.shape[1] != Size) {
131 return false;
132 }
133 const size_t num_elements = info.shape[0];
134 value.resize(num_elements);
135 const auto& mat = src.cast<Eigen::Ref<const MatrixType>>();
136 Eigen::Map<MatrixType>(
137 reinterpret_cast<Scalar*>(value.data()), num_elements, Size) = mat;
138 return true;
139 }
140
141 static handle cast(const std::vector<VectorType>& vec,
142 return_value_policy /* policy */,
143 handle h) {
144 Eigen::Map<const MatrixType> mat(
145 reinterpret_cast<const Scalar*>(vec.data()), vec.size(), Size);
146 return type_caster<Eigen::Map<const MatrixType>>::cast(
147 mat, return_value_policy::copy, h);
148 }
149 };
150
151 // pybind11's built-in STL casters only recognize std:: containers, so provide
152 // casters for the colmap flat hash aliases used across the bindings (e.g.
153 // ObservationManager::ImagePairs, IncrementalMapper::FilteredFrames,
154 // BundleAdjustmentConfig::VariablePoints, the FilterPoints3D* parameters). Only
155 // needed for the BOOST backend; for STD the aliases are std:: types pybind11
156 // already handles. Flat containers are never PYBIND11_MAKE_OPAQUE, so these
157 // generic casters cannot collide with opaque bound types. (The NodeHashMap
158 // caster lives in pycolmap/scene/types.h next to the opaque element-store
159 // maps.)
160 #if defined(COLMAP_HASH_BOOST)
161 template <typename Key, typename Value, typename Hash, typename Equal>
162 struct type_caster<colmap::FlatHashMap<Key, Value, Hash, Equal>>
163 : map_caster<colmap::FlatHashMap<Key, Value, Hash, Equal>, Key, Value> {};
164
165 template <typename Key, typename Hash, typename Equal>
166 struct type_caster<colmap::FlatHashSet<Key, Hash, Equal>>
167 : set_caster<colmap::FlatHashSet<Key, Hash, Equal>, Key> {};
168 #endif
169
170 } // namespace detail
171
172 template <typename type_, typename... options>
173 class classh_ext : public classh<type_, options...> {
174 public:
175 using Parent = classh<type_, options...>;
176 using Parent::Parent; // inherit constructors
177 using type = type_;
178
179 template <typename C, typename D, typename... Extra>
180 classh_ext& def_readwrite(const char* name,
181 D C::* pm,
182 const Extra&... extra) {
183 static_assert(
184 std::is_same<C, type>::value || std::is_base_of<C, type>::value,
185 "def_readwrite() requires a class member (or base class member)");
186 cpp_function fget([pm](type& c) -> D& { return c.*pm; }, is_method(*this)),
187 fset([pm](type& c, const D& value) { c.*pm = value; },
188 is_method(*this));
189 this->def_property(
190 name, fget, fset, return_value_policy::reference_internal, extra...);
191 return *this;
192 }
193
194 template <typename... Args>
195 classh_ext& def(Args&&... args) {
196 Parent::def(std::forward<Args>(args)...);
197 return *this;
198 }
199
200 template <typename... Args>
201 classh_ext& def_property(Args&&... args) {
202 Parent::def_property(std::forward<Args>(args)...);
203 return *this;
204 }
205 };
206
207 } // namespace PYBIND11_NAMESPACE