1 // Copyright (c) 2018, ETH Zurich and UNC Chapel Hill.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 //
10 // * Redistributions in binary form must reproduce the above copyright
11 // notice, this list of conditions and the following disclaimer in the
12 // documentation and/or other materials provided with the distribution.
13 //
14 // * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of
15 // its contributors may be used to endorse or promote products derived
16 // from this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
22 // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 // POSSIBILITY OF SUCH DAMAGE.
29 //
30 // Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de)
31
32 #ifndef COLMAP_SRC_BASE_DATABASE_H_
33 #define COLMAP_SRC_BASE_DATABASE_H_
34
35 #include <mutex>
36 #include <unordered_map>
37 #include <vector>
38
39 #include <Eigen/Core>
40
41 #include "sqlite3.h"
42 #include "base/camera.h"
43 #include "base/image.h"
44 #include "estimators/two_view_geometry.h"
45 #include "feature/types.h"
46 #include "util/types.h"
47
48 namespace colmap {
49
50 // Database class to read and write images, features, cameras, matches, etc.
51 // from a SQLite database. The class is not thread-safe and must not be accessed
52 // concurrently. The class is optimized for single-thread speed and for optimal
53 // performance, wrap multiple method calls inside a leading `BeginTransaction`
54 // and trailing `EndTransaction`.
55 class Database {
56 public:
57 const static int kSchemaVersion = 1;
58
59 // The maximum number of images, that can be stored in the database.
60 // This limitation arises due to the fact, that we generate unique IDs for
61 // image pairs manually. Note: do not change this to
62 // another type than `size_t`.
63 const static size_t kMaxNumImages;
64
65 Database();
66 explicit Database(const std::string& path);
67 ~Database();
68
69 // Open and close database. The same database should not be opened
70 // concurrently in multiple threads or processes.
71 void Open(const std::string& path);
72 void Close();
73
74 // Check if entry already exists in database. For image pairs, the order of
75 // `image_id1` and `image_id2` does not matter.
76 bool ExistsCamera(const camera_t camera_id) const;
77 bool ExistsImage(const image_t image_id) const;
78 bool ExistsImageWithName(std::string name) const;
79 bool ExistsKeypoints(const image_t image_id) const;
80 bool ExistsDescriptors(const image_t image_id) const;
81 bool ExistsMatches(const image_t image_id1, const image_t image_id2) const;
82 bool ExistsInlierMatches(const image_t image_id1,
83 const image_t image_id2) const;
84
85 // Number of rows in `cameras` table.
86 size_t NumCameras() const;
87
88 // Number of rows in `images` table.
89 size_t NumImages() const;
90
91 // Sum of `rows` column in `keypoints` table, i.e. number of total keypoints.
92 size_t NumKeypoints() const;
93
94 // The number of keypoints for the image with most features.
95 size_t MaxNumKeypoints() const;
96
97 // Number of descriptors for specific image.
98 size_t NumKeypointsForImage(const image_t image_id) const;
99
100 // Sum of `rows` column in `descriptors` table,
101 // i.e. number of total descriptors.
102 size_t NumDescriptors() const;
103
104 // The number of descriptors for the image with most features.
105 size_t MaxNumDescriptors() const;
106
107 // Number of descriptors for specific image.
108 size_t NumDescriptorsForImage(const image_t image_id) const;
109
110 // Sum of `rows` column in `matches` table, i.e. number of total matches.
111 size_t NumMatches() const;
112
113 // Sum of `rows` column in `two_view_geometries` table,
114 // i.e. number of total inlier matches.
115 size_t NumInlierMatches() const;
116
117 // Number of rows in `matches` table.
118 size_t NumMatchedImagePairs() const;
119
120 // Number of rows in `two_view_geometries` table.
121 size_t NumVerifiedImagePairs() const;
122
123 // Each image pair is assigned an unique ID in the `matches` and
124 // `two_view_geometries` table. We intentionally avoid to store the pairs in a
125 // separate table by using e.g. AUTOINCREMENT, since the overhead of querying
126 // the unique pair ID is significant.
127 inline static image_pair_t ImagePairToPairId(const image_t image_id1,
128 const image_t image_id2);
129
130 inline static void PairIdToImagePair(const image_pair_t pair_id,
131 image_t* image_id1, image_t* image_id2);
132
133 // Return true if image pairs should be swapped. Used to enforce a specific
134 // image order to generate unique image pair identifiers independent of the
135 // order in which the image identifiers are used.
136 inline static bool SwapImagePair(const image_t image_id1,
137 const image_t image_id2);
138
139 // Read an existing entry in the database. The user is responsible for making
140 // sure that the entry actually exists. For image pairs, the order of
141 // `image_id1` and `image_id2` does not matter.
142 Camera ReadCamera(const camera_t camera_id) const;
143 std::vector<Camera> ReadAllCameras() const;
144
145 Image ReadImage(const image_t image_id) const;
146 Image ReadImageWithName(const std::string& name) const;
147 std::vector<Image> ReadAllImages() const;
148
149 FeatureKeypoints ReadKeypoints(const image_t image_id) const;
150 FeatureDescriptors ReadDescriptors(const image_t image_id) const;
151
152 FeatureMatches ReadMatches(const image_t image_id1,
153 const image_t image_id2) const;
154 std::vector<std::pair<image_pair_t, FeatureMatches>> ReadAllMatches() const;
155
156 TwoViewGeometry ReadTwoViewGeometry(const image_t image_id1,
157 const image_t image_id2) const;
158 void ReadTwoViewGeometries(
159 std::vector<image_pair_t>* image_pair_ids,
160 std::vector<TwoViewGeometry>* two_view_geometries) const;
161
162 // Read all image pairs that have an entry in the `NumVerifiedImagePairs`
163 // table with at least one inlier match and their number of inlier matches.
164 void ReadTwoViewGeometryNumInliers(
165 std::vector<std::pair<image_t, image_t>>* image_pairs,
166 std::vector<int>* num_inliers) const;
167
168 // Add new camera and return its database identifier. If `use_camera_id`
169 // is false a new identifier is automatically generated.
170 camera_t WriteCamera(const Camera& camera,
171 const bool use_camera_id = false) const;
172
173 // Add new image and return its database identifier. If `use_image_id`
174 // is false a new identifier is automatically generated.
175 image_t WriteImage(const Image& image, const bool use_image_id = false) const;
176
177 // Write a new entry in the database. The user is responsible for making sure
178 // that the entry does not yet exist. For image pairs, the order of
179 // `image_id1` and `image_id2` does not matter.
180 void WriteKeypoints(const image_t image_id,
181 const FeatureKeypoints& keypoints) const;
182 void WriteDescriptors(const image_t image_id,
183 const FeatureDescriptors& descriptors) const;
184 void WriteMatches(const image_t image_id1, const image_t image_id2,
185 const FeatureMatches& matches) const;
186 void WriteTwoViewGeometry(const image_t image_id1, const image_t image_id2,
187 const TwoViewGeometry& two_view_geometry) const;
188
189 // Update an existing camera in the database. The user is responsible for
190 // making sure that the entry already exists.
191 void UpdateCamera(const Camera& camera) const;
192
193 // Update an existing image in the database. The user is responsible for
194 // making sure that the entry already exists.
195 void UpdateImage(const Image& image) const;
196
197 // Delete matches of an image pair.
198 void DeleteMatches(const image_t image_id1, const image_t image_id2) const;
199
200 // Delete inlier matches of an image pair.
201 void DeleteInlierMatches(const image_t image_id1,
202 const image_t image_id2) const;
203
204 // Clear the entire matches table.
205 void ClearMatches() const;
206
207 // Clear the entire inlier matches table.
208 void ClearTwoViewGeometries() const;
209
210 // Merge two databases into a single, new database.
211 static void Merge(const Database& database1, const Database& database2,
212 Database* merged_database);
213
214 private:
215 friend class DatabaseTransaction;
216
217 // Combine multiple queries into one transaction by wrapping a code section
218 // into a `BeginTransaction` and `EndTransaction`. You can create a scoped
219 // transaction with `DatabaseTransaction` that ends when the transaction
220 // object is destructed. Combining queries results in faster transaction time
221 // due to reduced locking of the database etc.
222 void BeginTransaction() const;
223 void EndTransaction() const;
224
225 // Prepare SQL statements once at construction of the database, and reuse
226 // the statements for multiple queries by resetting their states.
227 void PrepareSQLStatements();
228 void FinalizeSQLStatements();
229
230 // Create database tables, if not existing, called when opening a database.
231 void CreateTables() const;
232 void CreateCameraTable() const;
233 void CreateImageTable() const;
234 void CreateKeypointsTable() const;
235 void CreateDescriptorsTable() const;
236 void CreateMatchesTable() const;
237 void CreateTwoViewGeometriesTable() const;
238
239 void UpdateSchema() const;
240
241 bool ExistsTable(const std::string& table_name) const;
242 bool ExistsColumn(const std::string& table_name,
243 const std::string& column_name) const;
244
245 bool ExistsRowId(sqlite3_stmt* sql_stmt, const sqlite3_int64 row_id) const;
246 bool ExistsRowString(sqlite3_stmt* sql_stmt,
247 const std::string& row_entry) const;
248
249 size_t CountRows(const std::string& table) const;
250 size_t CountRowsForEntry(sqlite3_stmt* sql_stmt,
251 const sqlite3_int64 row_id) const;
252 size_t SumColumn(const std::string& column, const std::string& table) const;
253 size_t MaxColumn(const std::string& column, const std::string& table) const;
254
255 sqlite3* database_ = nullptr;
256
257 // Ensure that only one database object at a time updates the schema of a
258 // database. Since the schema is updated every time a database is opened, this
259 // is to ensure that there are no race conditions ("database locked" error
260 // messages) when the user actually only intends to read from the database,
261 // which requires to open it.
262 static std::mutex update_schema_mutex_;
263
264 // Used to ensure that only one transaction is active at the same time.
265 std::mutex transaction_mutex_;
266
267 // A collection of all `sqlite3_stmt` objects for deletion in the destructor.
268 std::vector<sqlite3_stmt*> sql_stmts_;
269
270 // num_*
271 sqlite3_stmt* sql_stmt_num_keypoints_ = nullptr;
272 sqlite3_stmt* sql_stmt_num_descriptors_ = nullptr;
273
274 // exists_*
275 sqlite3_stmt* sql_stmt_exists_camera_ = nullptr;
276 sqlite3_stmt* sql_stmt_exists_image_id_ = nullptr;
277 sqlite3_stmt* sql_stmt_exists_image_name_ = nullptr;
278 sqlite3_stmt* sql_stmt_exists_keypoints_ = nullptr;
279 sqlite3_stmt* sql_stmt_exists_descriptors_ = nullptr;
280 sqlite3_stmt* sql_stmt_exists_matches_ = nullptr;
281 sqlite3_stmt* sql_stmt_exists_two_view_geometry_ = nullptr;
282
283 // add_*
284 sqlite3_stmt* sql_stmt_add_camera_ = nullptr;
285 sqlite3_stmt* sql_stmt_add_image_ = nullptr;
286
287 // update_*
288 sqlite3_stmt* sql_stmt_update_camera_ = nullptr;
289 sqlite3_stmt* sql_stmt_update_image_ = nullptr;
290
291 // read_*
292 sqlite3_stmt* sql_stmt_read_camera_ = nullptr;
293 sqlite3_stmt* sql_stmt_read_cameras_ = nullptr;
294 sqlite3_stmt* sql_stmt_read_image_id_ = nullptr;
295 sqlite3_stmt* sql_stmt_read_image_name_ = nullptr;
296 sqlite3_stmt* sql_stmt_read_images_ = nullptr;
297 sqlite3_stmt* sql_stmt_read_keypoints_ = nullptr;
298 sqlite3_stmt* sql_stmt_read_descriptors_ = nullptr;
299 sqlite3_stmt* sql_stmt_read_matches_ = nullptr;
300 sqlite3_stmt* sql_stmt_read_matches_all_ = nullptr;
301 sqlite3_stmt* sql_stmt_read_two_view_geometry_ = nullptr;
302 sqlite3_stmt* sql_stmt_read_two_view_geometries_ = nullptr;
303 sqlite3_stmt* sql_stmt_read_two_view_geometry_num_inliers_ = nullptr;
304
305 // write_*
306 sqlite3_stmt* sql_stmt_write_keypoints_ = nullptr;
307 sqlite3_stmt* sql_stmt_write_descriptors_ = nullptr;
308 sqlite3_stmt* sql_stmt_write_matches_ = nullptr;
309 sqlite3_stmt* sql_stmt_write_two_view_geometry_ = nullptr;
310
311 // delete_*
312 sqlite3_stmt* sql_stmt_delete_matches_ = nullptr;
313 sqlite3_stmt* sql_stmt_delete_two_view_geometry_ = nullptr;
314
315 // clear_*
316 sqlite3_stmt* sql_stmt_clear_matches_ = nullptr;
317 sqlite3_stmt* sql_stmt_clear_two_view_geometries_ = nullptr;
318 };
319
320 // This class automatically manages the scope of a database transaction by
321 // calling `BeginTransaction` and `EndTransaction` during construction and
322 // destruction, respectively.
323 class DatabaseTransaction {
324 public:
325 explicit DatabaseTransaction(Database* database);
326 ~DatabaseTransaction();
327
328 private:
329 NON_COPYABLE(DatabaseTransaction)
330 NON_MOVABLE(DatabaseTransaction)
331 Database* database_;
332 std::unique_lock<std::mutex> database_lock_;
333 };
334
335 ////////////////////////////////////////////////////////////////////////////////
336 // Implementation
337 ////////////////////////////////////////////////////////////////////////////////
338
ImagePairToPairId(const image_t image_id1,const image_t image_id2)339 image_pair_t Database::ImagePairToPairId(const image_t image_id1,
340 const image_t image_id2) {
341 CHECK_GE(image_id1, 0);
342 CHECK_GE(image_id2, 0);
343 CHECK_LT(image_id1, kMaxNumImages);
344 CHECK_LT(image_id2, kMaxNumImages);
345 if (SwapImagePair(image_id1, image_id2)) {
346 return static_cast<image_pair_t>(kMaxNumImages) * image_id2 + image_id1;
347 } else {
348 return static_cast<image_pair_t>(kMaxNumImages) * image_id1 + image_id2;
349 }
350 }
351
PairIdToImagePair(const image_pair_t pair_id,image_t * image_id1,image_t * image_id2)352 void Database::PairIdToImagePair(const image_pair_t pair_id, image_t* image_id1,
353 image_t* image_id2) {
354 *image_id2 = static_cast<image_t>(pair_id % kMaxNumImages);
355 *image_id1 = static_cast<image_t>((pair_id - *image_id2) / kMaxNumImages);
356 CHECK_GE(*image_id1, 0);
357 CHECK_GE(*image_id2, 0);
358 CHECK_LT(*image_id1, kMaxNumImages);
359 CHECK_LT(*image_id2, kMaxNumImages);
360 }
361
362 // Return true if image pairs should be swapped. Used to enforce a specific
363 // image order to generate unique image pair identifiers independent of the
364 // order in which the image identifiers are used.
SwapImagePair(const image_t image_id1,const image_t image_id2)365 bool Database::SwapImagePair(const image_t image_id1, const image_t image_id2) {
366 return image_id1 > image_id2;
367 }
368
369 } // namespace colmap
370
371 #endif // COLMAP_SRC_BASE_DATABASE_H_
372