| 270 | DatabaseTransaction::~DatabaseTransaction() { database_->EndTransaction(); } |
| 271 | |
| 272 | FeatureDescriptorsFloat LoadRandomDatabaseDescriptors(const Database& database, |
| 273 | int max_num_descriptors) { |
| 274 | const std::vector<Image> images = database.ReadAllImages(); |
| 275 | const size_t total_num_descriptors = database.NumDescriptors(); |
| 276 | |
| 277 | if (total_num_descriptors == 0) { |
| 278 | return FeatureDescriptorsFloat(); |
| 279 | } |
| 280 | |
| 281 | FeatureDescriptorsFloat result; |
| 282 | result.type = FeatureExtractorType::UNDEFINED; |
| 283 | |
| 284 | std::vector<size_t> descriptor_idxs; |
| 285 | if (max_num_descriptors < 0 || |
| 286 | static_cast<size_t>(max_num_descriptors) >= total_num_descriptors) { |
| 287 | descriptor_idxs.resize(total_num_descriptors); |
| 288 | std::iota(descriptor_idxs.begin(), descriptor_idxs.end(), 0); |
| 289 | } else { |
| 290 | // Random subset of images in the database. |
| 291 | THROW_CHECK_LE(max_num_descriptors, total_num_descriptors); |
| 292 | RandomSampler random_sampler(max_num_descriptors); |
| 293 | random_sampler.Initialize(total_num_descriptors); |
| 294 | random_sampler.Sample(&descriptor_idxs); |
| 295 | std::sort(descriptor_idxs.begin(), descriptor_idxs.end()); |
| 296 | } |
| 297 | |
| 298 | int image_idx = -1; |
| 299 | FeatureDescriptorsFloat image_descriptors; |
| 300 | size_t image_descriptor_start = 0; |
| 301 | size_t image_descriptor_end = 0; |
| 302 | auto read_next_image = [&]() { |
| 303 | ++image_idx; |
| 304 | THROW_CHECK_LT(image_idx, images.size()); |
| 305 | const Image& image = images[image_idx]; |
| 306 | image_descriptors = database.ReadDescriptors(image.ImageId()).ToFloat(); |
| 307 | image_descriptor_start = image_descriptor_end; |
| 308 | image_descriptor_end = |
| 309 | image_descriptor_start + image_descriptors.data.rows(); |
| 310 | }; |
| 311 | |
| 312 | size_t descriptor_row = 0; |
| 313 | for (const size_t descriptor_idx : descriptor_idxs) { |
| 314 | while (descriptor_idx >= image_descriptor_end) { |
| 315 | read_next_image(); |
| 316 | } |
| 317 | |
| 318 | // Check that all images have the same feature type. |
| 319 | if (result.type == FeatureExtractorType::UNDEFINED) { |
| 320 | THROW_CHECK_NE(image_descriptors.type, FeatureExtractorType::UNDEFINED); |
| 321 | result.type = image_descriptors.type; |
| 322 | result.data.resize(descriptor_idxs.size(), image_descriptors.data.cols()); |
| 323 | } else { |
| 324 | THROW_CHECK_EQ(result.type, image_descriptors.type) |
| 325 | << "All images must have the same feature type"; |
| 326 | THROW_CHECK_EQ(image_descriptors.data.cols(), result.data.cols()) |
| 327 | << "All images must have the same descriptor dimensionality"; |
| 328 | } |
| 329 | |