Debian Codegraph @

python/README.md

raw
1 # Python Bindings for COLMAP
2
3 PyCOLMAP exposes to Python most capabilities of the [COLMAP](https://colmap.github.io/) Structure-from-Motion (SfM) and Multi-View Stereo (MVS) pipeline.
4
5 ## Installation
6
7 Pre-built wheels for Linux, macOS, and Windows can be installed using pip:
8
9 ```bash
10 pip install pycolmap
11 ```
12
13 The wheels are automatically built and pushed to [PyPI](https://pypi.org/project/pycolmap/) at each release. To benefit from GPU acceleration, wheels built for CUDA 12 (only for Linux - for now) are available under the [package `pycolmap-cuda12`](https://pypi.org/project/pycolmap-cuda12/).
14
15 <details>
16 <summary>[Building PyCOLMAP from source - click to expand]</summary>
17
18 1. Install COLMAP from source following [the official guide](https://colmap.github.io/install.html).
19
20 2. Build PyCOLMAP:
21 - On Linux and macOS:
22 ```bash
23 python -m pip install .
24 ```
25 - On Windows, after installing COLMAP [via VCPKG](https://colmap.github.io/install.html#id3), run in powershell:
26 ```powershell
27 python -m pip install . `
28 --cmake.define.CMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" `
29 --cmake.define.VCPKG_TARGET_TRIPLET="x64-windows"
30 ```
31
32 </details>
33
34 ## Reconstruction Pipeline
35
36 PyCOLMAP provides bindings for multiple steps of the standard reconstruction pipeline:
37
38 - Extracting and matching SIFT features
39 - Importing an image folder into a COLMAP database
40 - Inferring the camera parameters from the EXIF metadata of an image file
41 - Running two-view geometric verification of matches on a COLMAP database
42 - Triangulating points into an existing COLMAP model
43 - Running incremental reconstruction from a COLMAP database
44 - Dense reconstruction with multi-view stereo
45
46 ### Sparse & Dense Reconstruction
47
48 Sparse & Dense reconstruction from a folder of images can be performed with:
49
50 ```python
51 output_path: pathlib.Path
52 image_dir: pathlib.Path
53
54 output_path.mkdir()
55 mvs_path = output_path / "mvs"
56 database_path = output_path / "database.db"
57
58 pycolmap.extract_features(database_path, image_dir)
59 pycolmap.match_exhaustive(database_path)
60 maps = pycolmap.incremental_mapping(database_path, image_dir, output_path)
61 maps[0].write(output_path)
62
63 # Dense reconstruction
64 pycolmap.undistort_images(mvs_path, output_path, image_dir)
65 pycolmap.patch_match_stereo(mvs_path) # requires compilation with CUDA
66 pycolmap.stereo_fusion(mvs_path / "dense.ply", mvs_path)
67 ```
68
69 PyCOLMAP can leverage the GPU for feature extraction, matching, and multi-view stereo if COLMAP was compiled with CUDA support. Similarly, PyCOLMAP can run Delaunay Triangulation and Advancing Front Surface Reconstruction if COLMAP was compiled with CGAL support. This requires to build the package from source and is not available with the PyPI wheels.
70
71 ### Configuration Options
72
73 All of the above steps are easily configurable with python dicts which are recursively merged into their respective defaults, for example:
74
75 ```python
76 pycolmap.extract_features(
77 database_path, image_dir,
78 extraction_options={"sift": {"max_num_features": 512}}
79 )
80
81 # Equivalent to:
82 ops = pycolmap.FeatureExtractionOptions()
83 ops.sift.max_num_features = 512
84 pycolmap.extract_features(database_path, image_dir, extraction_options=ops)
85 ```
86
87 To list available options and their default parameters:
88
89 ```python
90 help(pycolmap.SiftExtractionOptions)
91 ```
92
93 For another example of usage, see [`example.py`](./examples/example.py) or [`hloc/reconstruction.py`](https://github.com/cvg/Hierarchical-Localization/blob/master/hloc/reconstruction.py).
94
95 ## Reconstruction Object
96
97 We can load and manipulate an existing COLMAP 3D reconstruction:
98
99 ```python
100 import pycolmap
101
102 reconstruction = pycolmap.Reconstruction("path/to/reconstruction/dir")
103 print(reconstruction.summary())
104
105 for image_id, image in reconstruction.images.items():
106 print(image_id, image)
107
108 for point3D_id, point3D in reconstruction.points3D.items():
109 print(point3D_id, point3D)
110
111 for camera_id, camera in reconstruction.cameras.items():
112 print(camera_id, camera)
113
114 reconstruction.write("path/to/reconstruction/dir/")
115 ```
116
117 ### Common Operations
118
119 The object API mirrors the COLMAP C++ library. The bindings support many operations, for example:
120
121 **Projecting a 3D point into an image** with arbitrary camera model:
122
123 ```python
124 uv = camera.img_from_cam(image.cam_from_world * point3D.xyz)
125 ```
126
127 **Aligning two 3D reconstructions** by their camera poses:
128
129 ```python
130 rec2_from_rec1 = pycolmap.align_reconstructions_via_reprojections(
131 reconstruction1, reconstruction2
132 )
133 reconstruction1.transform(rec2_from_rec1)
134 print(rec2_from_rec1.scale, rec2_from_rec1.rotation, rec2_from_rec1.translation)
135 ```
136
137 **Exporting reconstructions** to text, PLY, or other formats:
138
139 ```python
140 reconstruction.write_text("path/to/new/reconstruction/dir/") # text format
141 reconstruction.export_PLY("rec.ply") # PLY format
142 ```
143
144 ## Estimators
145
146 We provide robust RANSAC-based estimators for:
147
148 - Absolute camera pose (single-camera and multi-camera-rig)
149 - Essential matrix
150 - Fundamental matrix
151 - Homography
152 - Two-view relative pose for calibrated cameras
153
154 All RANSAC and estimation parameters are exposed as objects that behave similarly as Python dataclasses. The RANSAC options are described in [`colmap/optim/ransac.h`](https://github.com/colmap/colmap/blob/main/src/colmap/optim/ransac.h#L43-L72) and their default values are:
155
156 ```python
157 ransac_options = pycolmap.RANSACOptions(
158 max_error=4.0, # For example the reprojection error in pixels
159 min_inlier_ratio=0.01,
160 confidence=0.9999,
161 min_num_trials=1000,
162 max_num_trials=100000,
163 )
164 ```
165
166 ### Absolute Pose Estimation
167
168 To estimate the absolute pose of a query camera given 2D-3D correspondences:
169
170 ```python
171 # Parameters:
172 # - points2D: Nx2 array; pixel coordinates
173 # - points3D: Nx3 array; world coordinates
174 # - camera: pycolmap.Camera
175 # Optional parameters:
176 # - estimation_options: dict or pycolmap.AbsolutePoseEstimationOptions
177 # - refinement_options: dict or pycolmap.AbsolutePoseRefinementOptions
178 answer = pycolmap.estimate_and_refine_absolute_pose(points2D, points3D, camera)
179 # Returns: dictionary of estimation outputs or None if failure
180 ```
181
182 2D and 3D points are passed as Numpy arrays or lists. The options are defined in [`estimators/absolute_pose.cc`](./pycolmap/estimators/absolute_pose.h#L100-L122) and can be passed as regular (nested) Python dictionaries:
183
184 ```python
185 pycolmap.estimate_and_refine_absolute_pose(
186 points2D, points3D, camera,
187 estimation_options=dict(ransac=dict(max_error=12.0)),
188 refinement_options=dict(refine_focal_length=True),
189 )
190 ```
191
192 ### Absolute Pose Refinement
193
194 ```python
195 # Parameters:
196 # - cam_from_world: pycolmap.Rigid3d, initial pose
197 # - points2D: Nx2 array; pixel coordinates
198 # - points3D: Nx3 array; world coordinates
199 # - inlier_mask: array of N bool; inlier_mask[i] is true if correspondence i is an inlier
200 # - camera: pycolmap.Camera
201 # Optional parameters:
202 # - refinement_options: dict or pycolmap.AbsolutePoseRefinementOptions
203 answer = pycolmap.refine_absolute_pose(
204 cam_from_world, points2D, points3D, inlier_mask, camera
205 )
206 # Returns: dictionary of refinement outputs or None if failure
207 ```
208
209 ### Essential Matrix Estimation
210
211 ```python
212 # Parameters:
213 # - points1: Nx2 array; 2D pixel coordinates in image 1
214 # - points2: Nx2 array; 2D pixel coordinates in image 2
215 # - camera1: pycolmap.Camera of image 1
216 # - camera2: pycolmap.Camera of image 2
217 # Optional parameters:
218 # - options: dict or pycolmap.RANSACOptions (default inlier threshold is 4px)
219 answer = pycolmap.estimate_essential_matrix(points1, points2, camera1, camera2)
220 # Returns: dictionary of estimation outputs or None if failure
221 ```
222
223 ### Fundamental Matrix Estimation
224
225 ```python
226 answer = pycolmap.estimate_fundamental_matrix(
227 points1,
228 points2,
229 [options], # optional dict or pycolmap.RANSACOptions
230 )
231 ```
232
233 ### Homography Estimation
234
235 ```python
236 answer = pycolmap.estimate_homography_matrix(
237 points1,
238 points2,
239 [options], # optional dict or pycolmap.RANSACOptions
240 )
241 ```
242
243 ### Two-View Geometry Estimation
244
245 COLMAP can also estimate a relative pose between two calibrated cameras by estimating both E and H and accounting for the degeneracies of each model.
246
247 ```python
248 # Parameters:
249 # - camera1: pycolmap.Camera of image 1
250 # - points1: Nx2 array; 2D pixel coordinates in image 1
251 # - camera2: pycolmap.Camera of image 2
252 # - points2: Nx2 array; 2D pixel coordinates in image 2
253 # Optional parameters:
254 # - matches: Nx2 integer array; correspondences across images
255 # - options: dict or pycolmap.TwoViewGeometryOptions
256 answer = pycolmap.estimate_calibrated_two_view_geometry(
257 camera1, points1, camera2, points2
258 )
259 # Returns: pycolmap.TwoViewGeometry
260 ```
261
262 The `TwoViewGeometryOptions` control how each model is selected. The output structure contains the geometric model, inlier matches, the relative pose (if `options.compute_relative_pose=True`), and the type of camera configuration, which is an instance of the enum `pycolmap.TwoViewGeometryConfiguration`.
263
264 ### Camera Argument
265
266 Some estimators expect a COLMAP camera object, which can be created as follows:
267
268 ```python
269 camera = pycolmap.Camera(
270 model=camera_model_name_or_id,
271 width=width,
272 height=height,
273 params=params,
274 )
275 ```
276
277 The different camera models and their extra parameters are defined in [`colmap/src/colmap/sensor/models.h`](https://github.com/colmap/colmap/blob/main/src/colmap/sensor/models.h). For example for a pinhole camera:
278
279 ```python
280 camera = pycolmap.Camera(
281 model='SIMPLE_PINHOLE',
282 width=width,
283 height=height,
284 params=[focal_length, cx, cy],
285 )
286 ```
287
288 Alternatively, we can also pass a camera dictionary:
289
290 ```python
291 camera_dict = {
292 'model': COLMAP_CAMERA_MODEL_NAME_OR_ID,
293 'width': IMAGE_WIDTH,
294 'height': IMAGE_HEIGHT,
295 'params': EXTRA_CAMERA_PARAMETERS_LIST
296 }
297 ```
298
299
300 ## SIFT Feature Extraction
301
302 ```python
303 import numpy as np
304 import pycolmap
305 from PIL import Image, ImageOps
306
307 # Input should be grayscale image with range [0, 1].
308 img = Image.open('image.jpg').convert('RGB')
309 img = ImageOps.grayscale(img)
310 img = np.array(img).astype(np.float) / 255.
311
312 # Optional parameters:
313 # - options: dict or pycolmap.SiftExtractionOptions
314 # - device: default pycolmap.Device.auto uses the GPU if available
315 sift = pycolmap.Sift()
316
317 # Parameters:
318 # - image: HxW float array
319 keypoints, descriptors = sift.extract(img)
320 # Returns:
321 # - keypoints: Nx4 array; format: x (j), y (i), scale, orientation
322 # - descriptors: Nx128 array; L2-normalized descriptors
323 ```
324
325 ## Bitmap
326
327 PyCOLMAP provides bindings for the `Bitmap` class to work with images and convert them to/from NumPy arrays:
328
329 ```python
330 import numpy as np
331 import pycolmap
332
333 # Read a bitmap from file
334 bitmap = pycolmap.Bitmap.read("image.jpg", as_rgb=True)
335 print(f"Size: {bitmap.width}x{bitmap.height}, Channels: {bitmap.channels}")
336
337 # Convert to NumPy array
338 array = bitmap.to_array() # Shape: (H, W, 3) for RGB or (H, W) for grayscale
339
340 # Create bitmap from NumPy array
341 array = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
342 bitmap = pycolmap.Bitmap.from_array(array)
343
344 # Write bitmap to file
345 bitmap.write("output.jpg")
346
347 # Rescale bitmap
348 bitmap.rescale(new_width=320, new_height=240)
349 ```