@@ -257,28 +257,45 @@ std::shared_ptr<geometry::VoxelGrid> UniformTSDFVolume::ExtractVoxelGrid()
257257 voxel_grid->voxel_size_ = voxel_length_;
258258 voxel_grid->origin_ = origin_;
259259
260+ // Create a vector to hold voxels for each thread in the parallel region,
261+ // since access to voxel_grid->voxels_ (std::unordered_map) is not
262+ // thread-safe.
263+ std::vector<std::vector<geometry::Voxel>> per_thread_voxels;
264+
265+ #pragma omp parallel num_threads(utility::EstimateMaxThreads())
266+ {
267+ #pragma omp single
268+ { per_thread_voxels.resize (omp_get_num_threads ()); }
269+ int thread_id = omp_get_thread_num ();
270+
260271#ifdef _WIN32
261- #pragma omp parallel for schedule(static) \
262- num_threads (utility::EstimateMaxThreads ())
272+ #pragma omp for schedule(static)
263273#else
264- #pragma omp parallel for collapse(2) schedule(static) \
265- num_threads (utility::EstimateMaxThreads ())
274+ #pragma omp for collapse(2) schedule(static)
266275#endif
267- for (int x = 0 ; x < resolution_; x++) {
268- for (int y = 0 ; y < resolution_; y++) {
269- for (int z = 0 ; z < resolution_; z++) {
270- const int ind = IndexOf (x, y, z);
271- const float w = voxels_[ind].weight_ ;
272- const float f = voxels_[ind].tsdf_ ;
273- if (w != 0 .0f && f < 0 .98f && f >= -0 .98f ) {
274- double c = (f + 1.0 ) * 0.5 ;
275- Eigen::Vector3d color = Eigen::Vector3d (c, c, c);
276- Eigen::Vector3i index = Eigen::Vector3i (x, y, z);
277- voxel_grid->voxels_ [index] = geometry::Voxel (index, color);
276+ for (int x = 0 ; x < resolution_; x++) {
277+ for (int y = 0 ; y < resolution_; y++) {
278+ for (int z = 0 ; z < resolution_; z++) {
279+ const int ind = IndexOf (x, y, z);
280+ const float w = voxels_[ind].weight_ ;
281+ const float f = voxels_[ind].tsdf_ ;
282+ if (w != 0 .0f && f < 0 .98f && f >= -0 .98f ) {
283+ double c = (f + 1.0 ) * 0.5 ;
284+ Eigen::Vector3d color (c, c, c);
285+ Eigen::Vector3i index (x, y, z);
286+ per_thread_voxels[thread_id].emplace_back (index, color);
287+ }
278288 }
279289 }
280290 }
281291 }
292+
293+ for (const auto &thread_vector : per_thread_voxels) {
294+ for (const auto &voxel : thread_vector) {
295+ voxel_grid->voxels_ [voxel.grid_index_ ] = voxel;
296+ }
297+ }
298+
282299 return voxel_grid;
283300}
284301
0 commit comments