PointCloudCrafter
Loading...
Searching...
No Matches
pointcloudmodifier.hpp
1/*
2 * Copyright 2024 2024 Markus Pielmeier, Florian Sauerbeck,
3 * Dominik Kulmer, Maximilian Leitenstern
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#pragma once
19
20#include <math.h>
21
22#include <algorithm>
23#include <filesystem> // NOLINT
24#include <fstream>
25#include <functional>
26#include <iomanip>
27#include <iostream>
28#include <limits>
29#include <map>
30#include <memory>
31#include <sstream>
32#include <string>
33#include <tuple>
34#include <utility>
35#include <vector>
36
37// PCL
38#define PCL_NO_PRECOMPILE
39#include <pcl/filters/crop_box.h>
40#include <pcl/filters/extract_indices.h>
41#include <pcl/filters/radius_outlier_removal.h>
42#include <pcl/filters/statistical_outlier_removal.h>
43#include <pcl/filters/voxel_grid.h>
44#include <pcl/io/pcd_io.h>
45#include <pcl/io/ply_io.h>
46#include <pcl/io/obj_io.h>
47#include <pcl/visualization/pcl_visualizer.h>
48#include <pcl/conversions.h>
49#include <pcl/point_cloud.h>
50#include <pcl/point_types.h>
51#include <pcl/PCLPointCloud2.h>
52
53#include "formats.hpp"
54
55// TODO(ga58lar): unify the usage of pcl::PCLPointCloud2
56using PointCloud = pcl::PCLPointCloud2;
57namespace pointcloudmodifierlib
58{
62class Modifier
63{
64public:
65 Modifier()
66 : input_cloud(new pcl::PCLPointCloud2()), output_cloud(new pcl::PCLPointCloud2())
67 {
68 }
69 ~Modifier() = default;
70
71 // Loading point clouds
78 bool load(const std::string & file_path,
79 pointcloudcrafter::tools::formats::FileFormat format)
80 {
81 switch (format) {
82 case pointcloudcrafter::tools::formats::FileFormat::PCD:
83 return load_pcd(file_path);
84 case pointcloudcrafter::tools::formats::FileFormat::PLY:
85 return load_ply(file_path);
86 case pointcloudcrafter::tools::formats::FileFormat::TXT:
87 return load_txt(file_path);
88 case pointcloudcrafter::tools::formats::FileFormat::KITTI:
89 return load_kitti(file_path);
90 case pointcloudcrafter::tools::formats::FileFormat::NUSCENES:
91 return load_nuscenes(file_path);
92 case pointcloudcrafter::tools::formats::FileFormat::OBJ:
93 return load_obj(file_path);
94 default:
95 std::cerr << "Error: Unknown file format" << std::endl;
96 return false;
97 }
98 }
99
105 bool save(const std::string & file_path,
106 pointcloudcrafter::tools::formats::FileFormat format)
107 {
108 switch (format) {
109 case pointcloudcrafter::tools::formats::FileFormat::PCD:
110 return save_pcd(file_path);
111 case pointcloudcrafter::tools::formats::FileFormat::PLY:
112 return save_ply(file_path);
113 case pointcloudcrafter::tools::formats::FileFormat::TXT:
114 return save_txt(file_path);
115 case pointcloudcrafter::tools::formats::FileFormat::KITTI:
116 return save_kitti(file_path);
117 case pointcloudcrafter::tools::formats::FileFormat::NUSCENES:
118 return save_nuscenes(file_path);
119 default:
120 std::cerr << "Error: Unknown file format" << std::endl;
121 return false;
122 }
123 }
124
125 // Filtering functions
132 Modifier & cropBox(const std::vector<double> & box_params, const bool & negative = false)
133 {
134 // Check box_params size
135 if (box_params.size() != 6) {
136 std::cerr << "Error: box_params must contain exactly 6 elements." << std::endl;
137 return *this;
138 }
139
140 pcl::CropBox<PointCloud> boxFilter;
141 boxFilter.setMin(Eigen::Vector4f(box_params[0], box_params[1], box_params[2], 1.0));
142 boxFilter.setMax(Eigen::Vector4f(box_params[3], box_params[4], box_params[5], 1.0));
143 boxFilter.setInputCloud(output_cloud);
144 boxFilter.setNegative(negative);
145 boxFilter.filter(*output_cloud);
146 return *this;
147 }
148
154 Modifier & cropSphere(const double & sphere_params, const bool & negative = false)
155 {
156 const auto radius_sq = sphere_params * sphere_params;
157 pcl::PointCloud<pcl::PointXYZ>::Ptr tmp(new pcl::PointCloud<pcl::PointXYZ>);
158 pcl::fromPCLPointCloud2(*output_cloud, *tmp);
159
160 pcl::PointIndices::Ptr inliers(new pcl::PointIndices());
161 inliers->indices.reserve(tmp->size());
162
163 for (size_t i = 0; i < tmp->size(); ++i) {
164 if (tmp->points[i].getVector3fMap().squaredNorm() < radius_sq) {
165 inliers->indices.push_back(i);
166 }
167 }
168
169 pcl::ExtractIndices<pcl::PCLPointCloud2> extract;
170 extract.setInputCloud(output_cloud);
171 extract.setIndices(inliers);
172 extract.setNegative(negative);
173 extract.filter(*output_cloud);
174
175 return *this;
176 }
177
183 Modifier & cropCylinder(const double & zylinder_params, const bool & negative = false)
184 {
185 const auto radius_sq = zylinder_params * zylinder_params;
186 pcl::PointCloud<pcl::PointXYZ>::Ptr tmp(new pcl::PointCloud<pcl::PointXYZ>);
187 pcl::fromPCLPointCloud2(*output_cloud, *tmp);
188
189 pcl::PointIndices::Ptr inliers(new pcl::PointIndices());
190 inliers->indices.reserve(tmp->size());
191
192 for (size_t i = 0; i < tmp->size(); ++i) {
193 auto point = tmp->points[i].getVector3fMap();
194 auto r = point.x() * point.x() + point.y() * point.y();
195 if (r < radius_sq) {
196 inliers->indices.push_back(i);
197 }
198 }
199
200 pcl::ExtractIndices<pcl::PCLPointCloud2> extract;
201 extract.setInputCloud(output_cloud);
202 extract.setIndices(inliers);
203 extract.setNegative(negative);
204 extract.filter(*output_cloud);
205
206 return *this;
207 }
208
213 Modifier & voxelFilter(const std::vector<double> & voxel)
214 {
215 // Check voxel size
216 if (voxel.size() != 3) {
217 std::cerr << "Error: voxel must contain exactly 3 elements." << std::endl;
218 return *this;
219 }
220
221 pcl::PointCloud<pcl::PointXYZ>::Ptr tmp(new pcl::PointCloud<pcl::PointXYZ>);
222 pcl::fromPCLPointCloud2(*output_cloud, *tmp);
223
224 // Compute min_pt and max_pt
225 pcl::PointXYZ min_pt, max_pt;
226 pcl::getMinMax3D(*tmp, min_pt, max_pt);
227
228 // Figure out how many cells we’d have in each dimension
229 const auto num_x = static_cast<uint64_t>(std::floor((max_pt.x - min_pt.x) / voxel[0]));
230 const auto num_y = static_cast<uint64_t>(std::floor((max_pt.y - min_pt.y) / voxel[1]));
231 const auto num_z = static_cast<uint64_t>(std::floor((max_pt.z - min_pt.z) / voxel[2]));
232 const auto total = num_x * num_y * num_z;
233
234 // If the total # of voxels would exceed int32_t, apply subvoxel
235 if (total > static_cast<uint64_t>(INT32_MAX)) {
236 applySubVoxelFilter(voxel, output_cloud, min_pt, max_pt, num_x, num_y, num_z);
237 } else {
238 applyVoxelFilter(voxel, output_cloud);
239 }
240
241 return *this;
242 }
243
249 Modifier & outlierRadiusFilter(const double & radius, const int & min_neighbors)
250 {
251 // Check radius and min_neighbors
252 if (radius <= 0.0 || min_neighbors < 1) {
253 std::cerr << "Error: radius must be positive and min_neighbors must be at least 1."
254 << std::endl;
255 return *this;
256 }
257
258 pcl::RadiusOutlierRemoval<PointCloud> radiusFilter;
259 radiusFilter.setRadiusSearch(radius);
260 radiusFilter.setMinNeighborsInRadius(min_neighbors);
261 radiusFilter.setInputCloud(output_cloud);
262 radiusFilter.filter(*output_cloud);
263 return *this;
264 }
265
271 Modifier & outlierStatFilter(const double & threshold, const int & mean)
272 {
273 // Check threshold and mean neighbors
274 if (threshold <= 0.0 || mean < 1) {
275 std::cerr << "Error: threshold must be positive and mean must be at least 1." << std::endl;
276 return *this;
277 }
278
279 pcl::StatisticalOutlierRemoval<PointCloud> statFilter;
280 statFilter.setMeanK(mean);
281 statFilter.setStddevMulThresh(threshold);
282 statFilter.setInputCloud(output_cloud);
283 statFilter.filter(*output_cloud);
284 return *this;
285 }
286
287 // Transforms
293 Modifier & transform(const Eigen::Affine3d & transformation)
294 {
295 // Find x, y, z field offsets
296 int x_offset = -1, y_offset = -1, z_offset = -1;
297 for (const auto & field : output_cloud->fields) {
298 if (field.name == "x") x_offset = field.offset;
299 else if (field.name == "y") y_offset = field.offset;
300 else if (field.name == "z") z_offset = field.offset;
301 }
302
303 Eigen::Affine3f transform_f = transformation.cast<float>();
304
305 // Transform each point in-place
306 for (size_t i = 0; i < output_cloud->data.size(); i += output_cloud->point_step) {
307 float x, y, z;
308 memcpy(&x, &output_cloud->data[i + x_offset], sizeof(float));
309 memcpy(&y, &output_cloud->data[i + y_offset], sizeof(float));
310 memcpy(&z, &output_cloud->data[i + z_offset], sizeof(float));
311
312 Eigen::Vector3f pt(x, y, z);
313 Eigen::Vector3f pt_transformed = transform_f * pt;
314
315 memcpy(&output_cloud->data[i + x_offset], &pt_transformed.x(), sizeof(float));
316 memcpy(&output_cloud->data[i + y_offset], &pt_transformed.y(), sizeof(float));
317 memcpy(&output_cloud->data[i + z_offset], &pt_transformed.z(), sizeof(float));
318 }
319
320 return *this;
321 }
322
325 using ProgressCallback = std::function<void (const std::string &, size_t, size_t)>;
326
333 std::map<std::pair<int, int>, Modifier> split(
334 const double & grid_size,
335 const ProgressCallback & on_progress = nullptr)
336 {
337 std::map<std::pair<int, int>, Modifier> result;
338
339 if (output_cloud->data.empty()) {
340 std::cerr << "Error: Cannot split empty point cloud" << std::endl;
341 return result;
342 }
343 if (grid_size <= 0.0) {
344 std::cerr << "Error: grid_size must be positive" << std::endl;
345 return result;
346 }
347
348 int x_offset = -1, y_offset = -1;
349 for (const auto & field : output_cloud->fields) {
350 if (field.name == "x") x_offset = static_cast<int>(field.offset);
351 else if (field.name == "y") y_offset = static_cast<int>(field.offset);
352 }
353 if (x_offset == -1 || y_offset == -1) {
354 std::cerr << "Error: Point cloud must have x and y fields" << std::endl;
355 return result;
356 }
357
358 const size_t num_points = output_cloud->width * output_cloud->height;
359 const size_t point_step = output_cloud->point_step;
360
361 // Collect point indices per grid cell
362 std::map<std::pair<int, int>, std::vector<size_t>> grid_index;
363 const size_t bin_report_step = std::max<size_t>(num_points / 100, 1);
364 for (size_t i = 0; i < num_points; ++i) {
365 const uint8_t * pt_data = output_cloud->data.data() + i * point_step;
366 float x, y;
367 memcpy(&x, pt_data + x_offset, sizeof(float));
368 memcpy(&y, pt_data + y_offset, sizeof(float));
369 int ix = static_cast<int>(std::floor(x / grid_size));
370 int iy = static_cast<int>(std::floor(y / grid_size));
371 grid_index[{ix, iy}].push_back(i);
372 if (on_progress && ((i + 1) % bin_report_step == 0 || i + 1 == num_points)) {
373 on_progress("Binning points", i + 1, num_points);
374 }
375 }
376
377 const size_t total_cells = grid_index.size();
378 size_t cells_built = 0;
379 for (const auto & cell : grid_index) {
380 const auto & indices = cell.second;
381 PointCloud::Ptr cell_cloud = std::make_shared<PointCloud>();
382 cell_cloud->header = output_cloud->header;
383 cell_cloud->fields = output_cloud->fields;
384 cell_cloud->is_bigendian = output_cloud->is_bigendian;
385 cell_cloud->point_step = point_step;
386 cell_cloud->width = indices.size();
387 cell_cloud->height = 1;
388 cell_cloud->is_dense = true;
389 cell_cloud->row_step = cell_cloud->point_step * cell_cloud->width;
390 cell_cloud->data.resize(indices.size() * point_step);
391
392 for (size_t j = 0; j < indices.size(); ++j) {
393 memcpy(
394 cell_cloud->data.data() + j * point_step,
395 output_cloud->data.data() + indices[j] * point_step,
396 point_step);
397 }
398
399 Modifier cell_modifier;
400 cell_modifier.setCloud(cell_cloud);
401 result.emplace(cell.first, std::move(cell_modifier));
402
403 ++cells_built;
404 if (on_progress) {
405 on_progress("Building cells", cells_built, total_cells);
406 }
407 }
408
409 return result;
410 }
411
420 static bool writeGridMetadata(
421 const std::map<std::pair<int, int>, Modifier> & cells,
422 const double & grid_size,
423 const std::string & file_path,
424 const std::string & extension = ".pcd")
425 {
426 std::ofstream file(file_path);
427 if (!file.is_open()) {
428 std::cerr << "Error: Failed to write metadata file: " << file_path << std::endl;
429 return false;
430 }
431
432 auto format_coord = [](double val) -> std::string {
433 if (val == std::floor(val)) {
434 return std::to_string(static_cast<int64_t>(val));
435 }
436 std::ostringstream oss;
437 oss << val;
438 return oss.str();
439 };
440
441 file << "x_resolution: " << grid_size << "\n";
442 file << "y_resolution: " << grid_size << "\n";
443
444 for (const auto & cell : cells) {
445 double coord_x = cell.first.first * grid_size;
446 double coord_y = cell.first.second * grid_size;
447 std::string sx = format_coord(coord_x);
448 std::string sy = format_coord(coord_y);
449 file << sx << "_" << sy << extension << ": [" << sx << ", " << sy << "]\n";
450 }
451
452 return true;
453 }
454
455 // Analysis
461 Modifier & timestampAnalyzer(const std::string & file_path)
462 {
463 std::vector<double> time_float{};
464 std::vector<size_t> time_int{};
465 for (size_t i = 0; i < output_cloud->data.size(); i += output_cloud->point_step) {
466 for (size_t j = 0; j < output_cloud->fields.size(); ++j) {
467 double tf{0.0};
468 size_t ti{0};
469 pcl::PCLPointField & field = output_cloud->fields[j];
470 size_t point_offset = i + field.offset;
471 if (field.name == "timestamp" || field.name == "time_stamp" || field.name == "t") {
472 if (field.datatype == pcl::PCLPointField::FLOAT32) {
473 float tmp_stamp;
474 memcpy(&tmp_stamp, &output_cloud->data[point_offset], sizeof(float));
475 tf = static_cast<double>(tmp_stamp);
476 } else if (field.datatype == pcl::PCLPointField::FLOAT64) {
477 memcpy(&tf, &output_cloud->data[point_offset], sizeof(double));
478 } else if (field.datatype == pcl::PCLPointField::UINT32) {
479 memcpy(&ti, &output_cloud->data[point_offset], sizeof(uint32_t));
480 } else if (field.datatype == pcl::PCLPointField::UINT8 && field.count == 8) {
481 ti = 0;
482 for (size_t k = 0; k < 8; ++k) {
483 ti |= static_cast<uint64_t>(output_cloud->data[point_offset + k]) << (8 * k);
484 }
485 } else if (field.datatype == pcl::PCLPointField::UINT8 && field.count == 4) {
486 ti = 0;
487 for (size_t k = 0; k < 4; ++k) {
488 ti |= static_cast<uint32_t>(output_cloud->data[point_offset + k]) << (8 * k);
489 }
490 } else {
491 std::cerr << "Error: Unknown datatype for timestamp field" << std::endl;
492 return *this;
493 }
494 }
495 if (tf > 0.0) {
496 time_float.push_back(tf);
497 } else if (ti > 0) {
498 time_int.push_back(ti);
499 }
500 }
501 }
502
503 if (!time_float.empty()) {
504 saveTimestamps<double>(time_float, file_path);
505
506 // Basic statistics
507 std::cout << "Float timestamps: " << time_float.size() << " entries" << std::endl;
508 if (time_float.size() > 1) {
509 double min_ts = *std::min_element(time_float.begin(), time_float.end());
510 double max_ts = *std::max_element(time_float.begin(), time_float.end());
511 std::cout << " Min: " << min_ts << "\n Max: " << max_ts
512 << "\n Duration: " << (max_ts - min_ts) << std::endl;
513 }
514 }
515
516 if (!time_int.empty()) {
517 saveTimestamps<size_t>(time_int, file_path);
518
519 // Basic statistics
520 std::cout << "Integer timestamps: " << time_int.size() << " entries" << std::endl;
521 if (time_int.size() > 1) {
522 uint64_t min_ts = *std::min_element(time_int.begin(), time_int.end());
523 uint64_t max_ts = *std::max_element(time_int.begin(), time_int.end());
524 std::cout << " Min: " << min_ts << "\n Max: " << max_ts
525 << "\n Duration: " << (max_ts - min_ts) << std::endl;
526 }
527 }
528
529 return *this;
530 }
531
532 // Visualization
537 {
538 // Convert to PointXYZ for visualization
539 pcl::PointCloud<pcl::PointXYZ>::Ptr input_xyz(new pcl::PointCloud<pcl::PointXYZ>());
540 pcl::PointCloud<pcl::PointXYZ>::Ptr output_xyz(new pcl::PointCloud<pcl::PointXYZ>());
541
542 pcl::fromPCLPointCloud2(*input_cloud, *input_xyz);
543 pcl::fromPCLPointCloud2(*output_cloud, *output_xyz);
544
545 pcl::visualization::PCLVisualizer viewer("Point Cloud Viewer");
546
547 // Add input cloud with white color
548
549 pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> input_color(
550 input_xyz, 255, 255, 255);
551 viewer.addPointCloud(input_xyz, input_color, "input_cloud");
552 viewer.setPointCloudRenderingProperties(
553 pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "input_cloud");
554
555 // Add output cloud with red color
556 pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> output_color(
557 output_xyz, 230, 20, 20);
558 viewer.addPointCloud(output_xyz, output_color, "output_cloud");
559 viewer.setPointCloudRenderingProperties(
560 pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "output_cloud");
561
562 // Additional visualization settings
563 viewer.addCoordinateSystem(1.0, "cloud", 0);
564 viewer.setBackgroundColor(0.15, 0.15, 0.15, 0);
565
566 std::cout << "Input_cloud: white | Output_cloud: red" << std::endl;
567
568 // Spin until window is closed
569 viewer.spin();
570 }
571
572 // Setters
577 void setCloud(const PointCloud::Ptr & cloud)
578 {
579 *output_cloud = *cloud;
580 *input_cloud = *cloud;
581 }
582
583 // Getters
588 const PointCloud::Ptr getInputCloud() const { return input_cloud; }
593 const PointCloud::Ptr getOutputCloud() const { return output_cloud; }
594
595private:
596 PointCloud::Ptr input_cloud;
597 PointCloud::Ptr output_cloud;
598
604 bool load_pcd(const std::string & file_path)
605 {
606 pcl::PCDReader reader;
607 if (reader.read(file_path, *input_cloud) == -1) {
608 std::cerr << "Error: Failed to load PCD file: " << file_path << std::endl;
609 return false;
610 }
611 *output_cloud = *input_cloud;
612 return true;
613 }
619 bool load_ply(const std::string & file_path)
620 {
621 pcl::PLYReader reader;
622 if (reader.read(file_path, *input_cloud) == -1) {
623 std::cerr << "Error: Failed to load PLY file: " << file_path << std::endl;
624 return false;
625 }
626 *output_cloud = *input_cloud;
627 return true;
628 }
639 bool load_txt(const std::string & file_path)
640 {
641 std::ifstream file(file_path);
642 if (!file.is_open()) {
643 std::cerr << "Error: Failed to open TXT file: " << file_path << std::endl;
644 return false;
645 }
646
647 std::string line;
648 std::vector<std::string> field_names;
649 std::vector<std::vector<float>> data;
650
651 // Read first line to check for header
652 if (!std::getline(file, line)) {
653 std::cerr << "Error: Empty TXT file: " << file_path << std::endl;
654 return false;
655 }
656
657 // Try to parse first line as header (check if it contains non-numeric values)
658 std::istringstream first_line(line);
659 std::string token;
660 bool is_header = false;
661
662 while (first_line >> token) {
663 // Check if token is a number
664 char* end;
665 std::strtof(token.c_str(), &end);
666 if (*end != '\0') {
667 // Not a number, treat as header
668 is_header = true;
669 }
670 field_names.push_back(token);
671 }
672
673 if (!is_header) {
674 // First line was data, use default field names and parse as data
675 field_names.clear();
676 size_t num_fields = 0;
677
678 // Count fields and parse first line as data
679 std::istringstream data_line(line);
680 std::vector<float> point_data;
681 float value;
682 while (data_line >> value) {
683 point_data.push_back(value);
684 num_fields++;
685 }
686 data.push_back(point_data);
687
688 // Generate default field names based on number of fields
689 if (num_fields >= 3) {
690 field_names = {"x", "y", "z"};
691 for (size_t i = 3; i < num_fields; ++i) {
692 field_names.push_back("field_" + std::to_string(i));
693 }
694 } else {
695 for (size_t i = 0; i < num_fields; ++i) {
696 field_names.push_back("field_" + std::to_string(i));
697 }
698 }
699 }
700
701 // Read remaining lines as data
702 while (std::getline(file, line)) {
703 if (line.empty() || line[0] == '#') continue;
704
705 std::istringstream iss(line);
706 std::vector<float> point_data;
707 float value;
708
709 while (iss >> value) {
710 point_data.push_back(value);
711 }
712
713 if (point_data.size() == field_names.size()) {
714 data.push_back(point_data);
715 }
716 }
717
718 if (data.empty()) {
719 std::cerr << "Error: No valid points in TXT file: " << file_path << std::endl;
720 return false;
721 }
722
723 // Build PCLPointCloud2 manually
724 const size_t num_points = data.size();
725 const size_t num_fields = field_names.size();
726
727 input_cloud->width = num_points;
728 input_cloud->height = 1;
729 input_cloud->is_dense = true;
730 input_cloud->is_bigendian = false;
731
732 // Setup fields (all as FLOAT32)
733 input_cloud->fields.clear();
734 input_cloud->fields.resize(num_fields);
735 uint32_t offset = 0;
736
737 for (size_t i = 0; i < num_fields; ++i) {
738 input_cloud->fields[i].name = field_names[i];
739 input_cloud->fields[i].offset = offset;
740 input_cloud->fields[i].datatype = pcl::PCLPointField::FLOAT32;
741 input_cloud->fields[i].count = 1;
742 offset += sizeof(float);
743 }
744
745 input_cloud->point_step = offset;
746 input_cloud->row_step = input_cloud->point_step * input_cloud->width;
747 input_cloud->data.resize(input_cloud->row_step * input_cloud->height);
748
749 // Fill data
750 for (size_t i = 0; i < num_points; ++i) {
751 uint8_t* pt_data = input_cloud->data.data() + i * input_cloud->point_step;
752 for (size_t j = 0; j < num_fields; ++j) {
753 float value = data[i][j];
754 memcpy(pt_data + input_cloud->fields[j].offset, &value, sizeof(float));
755 }
756 }
757
758 *output_cloud = *input_cloud;
759 return true;
760 }
769 bool load_kitti(const std::string & file_path)
770 {
771 std::ifstream file(file_path, std::ios::binary);
772 if (!file.is_open()) {
773 std::cerr << "Error: Failed to open KITTI file: " << file_path << std::endl;
774 return false;
775 }
776
777 // Get file size
778 file.seekg(0, std::ios::end);
779 const size_t file_size = file.tellg();
780 file.seekg(0, std::ios::beg);
781
782 // KITTI format: 4 floats per point (x, y, z, intensity)
783 constexpr size_t point_size = 4 * sizeof(float);
784 const size_t num_points = file_size / point_size;
785
786 // Read all data
787 std::vector<float> buffer(num_points * 4);
788 file.read(reinterpret_cast<char*>(buffer.data()), file_size);
789
790 // Convert to PointXYZI
791 pcl::PointCloud<pcl::PointXYZI>::Ptr tmp(new pcl::PointCloud<pcl::PointXYZI>);
792 tmp->reserve(num_points);
793
794 for (size_t i = 0; i < num_points; ++i) {
795 pcl::PointXYZI point;
796 point.x = buffer[i * 4 + 0];
797 point.y = buffer[i * 4 + 1];
798 point.z = buffer[i * 4 + 2];
799 point.intensity = buffer[i * 4 + 3];
800 tmp->push_back(point);
801 }
802
803 tmp->width = tmp->size();
804 tmp->height = 1;
805 tmp->is_dense = true;
806
807 pcl::toPCLPointCloud2(*tmp, *input_cloud);
808 *output_cloud = *input_cloud;
809 return true;
810 }
819 bool load_nuscenes(const std::string & file_path)
820 {
821 std::ifstream file(file_path, std::ios::binary);
822 if (!file.is_open()) {
823 std::cerr << "Error: Failed to open nuScenes file: " << file_path << std::endl;
824 return false;
825 }
826
827 // Get file size
828 file.seekg(0, std::ios::end);
829 const size_t file_size = file.tellg();
830 file.seekg(0, std::ios::beg);
831
832 // nuScenes format: 5 floats per point (x, y, z, intensity, ring)
833 constexpr size_t point_size = 5 * sizeof(float);
834 const size_t num_points = file_size / point_size;
835
836 // Read all data
837 std::vector<float> buffer(num_points * 5);
838 file.read(reinterpret_cast<char*>(buffer.data()), file_size);
839
840 // Create custom point cloud with ring field
841 // Using PointXYZI and storing ring in a separate structure
842 pcl::PointCloud<pcl::PointXYZI>::Ptr tmp(new pcl::PointCloud<pcl::PointXYZI>);
843 tmp->reserve(num_points);
844
845 for (size_t i = 0; i < num_points; ++i) {
846 pcl::PointXYZI point;
847 point.x = buffer[i * 5 + 0];
848 point.y = buffer[i * 5 + 1];
849 point.z = buffer[i * 5 + 2];
850 point.intensity = buffer[i * 5 + 3];
851 // Note: ring (buffer[i * 5 + 4]) is lost in PointXYZI
852 // For full support, use a custom point type
853 tmp->push_back(point);
854 }
855
856 tmp->width = tmp->size();
857 tmp->height = 1;
858 tmp->is_dense = true;
859
860 pcl::toPCLPointCloud2(*tmp, *input_cloud);
861 *output_cloud = *input_cloud;
862 return true;
863 }
869 bool load_obj(const std::string & file_path)
870 {
871 pcl::OBJReader reader;
872 if (reader.read(file_path, *input_cloud) == -1) {
873 std::cerr << "Error: Failed to load OBJ file: " << file_path << std::endl;
874 return false;
875 }
876 *output_cloud = *input_cloud;
877 return true;
878 }
879
885 bool save_pcd(const std::string & file_path)
886 {
887 pcl::PCDWriter writer;
888 if (writer.write(file_path, *output_cloud, Eigen::Vector4f::Zero(),
889 Eigen::Quaternionf::Identity(), true) == -1) {
890 std::cerr << "Error: Failed to save PCD file: " << file_path << std::endl;
891 return false;
892 }
893 return true;
894 }
900 bool save_ply(const std::string & file_path)
901 {
902 pcl::PLYWriter writer;
903 if (writer.write(file_path, *output_cloud, Eigen::Vector4f::Zero(),
904 Eigen::Quaternionf::Identity(), true, false) == -1) {
905 std::cerr << "Error: Failed to save PLY file: " << file_path << std::endl;
906 return false;
907 }
908 return true;
909 }
919 bool save_txt(const std::string & file_path)
920 {
921 std::ofstream file(file_path);
922 if (!file.is_open()) {
923 std::cerr << "Error: Failed to open TXT file for writing: " << file_path << std::endl;
924 return false;
925 }
926
927 // Write header line with channel names
928 for (size_t i = 0; i < output_cloud->fields.size(); ++i) {
929 file << output_cloud->fields[i].name;
930 if (i < output_cloud->fields.size() - 1) {
931 file << " ";
932 }
933 }
934 file << "\n";
935
936 // Write point data
937 const size_t num_points = output_cloud->width * output_cloud->height;
938 file << std::fixed << std::setprecision(6);
939
940 for (size_t i = 0; i < num_points; ++i) {
941 const uint8_t* pt_data = output_cloud->data.data() + i * output_cloud->point_step;
942
943 for (size_t j = 0; j < output_cloud->fields.size(); ++j) {
944 const auto & field = output_cloud->fields[j];
945 float value = getFieldValue(pt_data, field);
946 file << value;
947 if (j < output_cloud->fields.size() - 1) {
948 file << " ";
949 }
950 }
951 file << "\n";
952 }
953
954 return true;
955 }
964 bool save_kitti(const std::string & file_path)
965 {
966 std::ofstream file(file_path, std::ios::binary);
967 if (!file.is_open()) {
968 std::cerr << "Error: Failed to open KITTI file for writing: " << file_path << std::endl;
969 return false;
970 }
971
972 // Find field indices
973 int idx_x = -1, idx_y = -1, idx_z = -1, idx_intensity = -1;
974 for (size_t i = 0; i < output_cloud->fields.size(); ++i) {
975 std::string name = output_cloud->fields[i].name;
976 std::transform(name.begin(), name.end(), name.begin(),
977 [](unsigned char c){ return std::tolower(c); });
978 if (name == "x") idx_x = static_cast<int>(i);
979 else if (name == "y") idx_y = static_cast<int>(i);
980 else if (name == "z") idx_z = static_cast<int>(i);
981 else if (name == "intensity") idx_intensity = static_cast<int>(i);
982 }
983
984 const size_t num_points = output_cloud->width * output_cloud->height;
985
986 for (size_t i = 0; i < num_points; ++i) {
987 uint8_t* pt_data = output_cloud->data.data() + i * output_cloud->point_step;
988
989 float x = *reinterpret_cast<float*>(pt_data + output_cloud->fields[idx_x].offset);
990 float y = *reinterpret_cast<float*>(pt_data + output_cloud->fields[idx_y].offset);
991 float z = *reinterpret_cast<float*>(pt_data + output_cloud->fields[idx_z].offset);
992
993 float intensity = 0.0f;
994 if (idx_intensity != -1) {
995 intensity = getFieldValue(pt_data, output_cloud->fields[idx_intensity]);
996 }
997
998 float data[4] = {x, y, z, intensity};
999 file.write(reinterpret_cast<char*>(data), sizeof(data));
1000 }
1001
1002 return true;
1003 }
1012 bool save_nuscenes(const std::string & file_path)
1013 {
1014 std::ofstream file(file_path, std::ios::binary);
1015 if (!file.is_open()) {
1016 std::cerr << "Error: Failed to open nuScenes file for writing: " << file_path << std::endl;
1017 return false;
1018 }
1019
1020 // Find field indices (case-insensitive)
1021 int idx_x = -1, idx_y = -1, idx_z = -1, idx_intensity = -1, idx_ring = -1;
1022 for (size_t i = 0; i < output_cloud->fields.size(); ++i) {
1023 std::string name = output_cloud->fields[i].name;
1024 std::transform(name.begin(), name.end(), name.begin(),
1025 [](unsigned char c){ return std::tolower(c); });
1026 if (name == "x") idx_x = static_cast<int>(i);
1027 else if (name == "y") idx_y = static_cast<int>(i);
1028 else if (name == "z") idx_z = static_cast<int>(i);
1029 else if (name == "intensity") idx_intensity = static_cast<int>(i);
1030 else if (name == "ring" || name == "channel") idx_ring = static_cast<int>(i);
1031 }
1032
1033 const size_t num_points = output_cloud->width * output_cloud->height;
1034
1035 for (size_t i = 0; i < num_points; ++i) {
1036 uint8_t* pt_data = output_cloud->data.data() + i * output_cloud->point_step;
1037
1038 float x = *reinterpret_cast<float*>(pt_data + output_cloud->fields[idx_x].offset);
1039 float y = *reinterpret_cast<float*>(pt_data + output_cloud->fields[idx_y].offset);
1040 float z = *reinterpret_cast<float*>(pt_data + output_cloud->fields[idx_z].offset);
1041
1042 float intensity = (idx_intensity != -1) ?
1043 getFieldValue(pt_data, output_cloud->fields[idx_intensity]) : 0.0f;
1044 float ring = (idx_ring != -1) ?
1045 getFieldValue(pt_data, output_cloud->fields[idx_ring]) : 0.0f;
1046
1047 float data[5] = {x, y, z, intensity, ring};
1048 file.write(reinterpret_cast<char*>(data), sizeof(data));
1049 }
1050
1051 return true;
1052 }
1059 float getFieldValue(const uint8_t* pt_data, const pcl::PCLPointField & field)
1060 {
1061 switch (field.datatype) {
1062 case pcl::PCLPointField::INT8:
1063 return static_cast<float>(*reinterpret_cast<const int8_t*>(pt_data + field.offset));
1064 case pcl::PCLPointField::UINT8:
1065 return static_cast<float>(*reinterpret_cast<const uint8_t*>(pt_data + field.offset));
1066 case pcl::PCLPointField::INT16:
1067 return static_cast<float>(*reinterpret_cast<const int16_t*>(pt_data + field.offset));
1068 case pcl::PCLPointField::UINT16:
1069 return static_cast<float>(*reinterpret_cast<const uint16_t*>(pt_data + field.offset));
1070 case pcl::PCLPointField::INT32:
1071 return static_cast<float>(*reinterpret_cast<const int32_t*>(pt_data + field.offset));
1072 case pcl::PCLPointField::UINT32:
1073 return static_cast<float>(*reinterpret_cast<const uint32_t*>(pt_data + field.offset));
1074 case pcl::PCLPointField::FLOAT32:
1075 return *reinterpret_cast<const float*>(pt_data + field.offset);
1076 case pcl::PCLPointField::FLOAT64:
1077 return static_cast<float>(*reinterpret_cast<const double*>(pt_data + field.offset));
1078 default:
1079 return 0.0f;
1080 }
1081 }
1082
1093 void applySubVoxelFilter(
1094 const std::vector<double> & voxel, PointCloud::Ptr & cloud, const pcl::PointXYZ & min_pt,
1095 const pcl::PointXYZ & max_pt, const uint64_t num_x, const uint64_t num_y, const uint64_t num_z)
1096 {
1097 PointCloud::Ptr tpc = std::make_shared<PointCloud>();
1098 PointCloud::Ptr apc = std::make_shared<PointCloud>();
1099 uint64_t num = std::floor(std::cbrt((num_x * num_y * num_z) / INT32_MAX)) + 1;
1100 uint64_t iter = 0;
1101
1102 for (uint64_t ix = 0; ix < num; ix++) {
1103 for (uint64_t iy = 0; iy < num; iy++) {
1104 for (uint64_t iz = 0; iz < num; iz++) {
1105 std::cout << "\rSubvoxel split: " << ++iter << " of "
1106 << static_cast<uint64_t>(std::pow(num, 3)) << std::flush;
1107 pcl::CropBox<PointCloud> box;
1108 pcl::PointXYZ tmin = {
1109 min_pt.x + (ix * (max_pt.x - min_pt.x) / num),
1110 min_pt.y + (iy * (max_pt.y - min_pt.y) / num),
1111 min_pt.z + (iz * (max_pt.z - min_pt.z) / num)};
1112 pcl::PointXYZ tmax = {
1113 tmin.x + (max_pt.x - min_pt.x) / num, tmin.y + (max_pt.y - min_pt.y) / num,
1114 tmin.z + (max_pt.z - min_pt.z) / num};
1115
1116 box.setMin(Eigen::Vector4f(tmin.x, tmin.y, tmin.z, 1.0));
1117 box.setMax(Eigen::Vector4f(tmax.x, tmax.y, tmax.z, 1.0));
1118 box.setInputCloud(cloud);
1119 box.filter(*tpc);
1120
1121 pcl::VoxelGrid<PointCloud> grid;
1122 grid.setInputCloud(tpc);
1123 grid.setLeafSize(voxel[0], voxel[1], voxel[2]);
1124 grid.filter(*tpc);
1125
1126 *apc += *tpc;
1127 }
1128 }
1129 }
1130 std::cout << std::endl;
1131 *output_cloud = *apc;
1132 }
1133
1139 void applyVoxelFilter(const std::vector<double> & voxel, PointCloud::Ptr & cloud)
1140 {
1141 pcl::VoxelGrid<PointCloud> voxelFilter;
1142 voxelFilter.setLeafSize(voxel[0], voxel[1], voxel[2]);
1143 voxelFilter.setInputCloud(cloud);
1144 voxelFilter.filter(*cloud);
1145 }
1146
1153 template <typename T>
1154 bool saveTimestamps(const std::vector<T> & timestamps, const std::string & output_path)
1155 {
1156 std::ofstream outfile;
1157 outfile.open(output_path);
1158
1159 if (!outfile.is_open()) {
1160 std::cerr << "Failed to open file for writing: " << output_path << std::endl;
1161 return false;
1162 }
1163
1164 for (const auto & ts : timestamps) {
1165 outfile << std::fixed << std::setprecision(9) << ts << std::endl;
1166 }
1167
1168 outfile.close();
1169 std::cout << "Timestamps saved to: " << output_path << std::endl;
1170 return true;
1171 }
1172};
1173} // namespace pointcloudmodifierlib
Modifier & cropCylinder(const double &zylinder_params, const bool &negative=false)
Crop cylinder filter.
Definition pointcloudmodifier.hpp:183
const PointCloud::Ptr getOutputCloud() const
Get output point cloud.
Definition pointcloudmodifier.hpp:593
const PointCloud::Ptr getInputCloud() const
Get input point cloud.
Definition pointcloudmodifier.hpp:588
std::function< void(const std::string &, size_t, size_t)> ProgressCallback
Callback invoked to report split() progress: (stage, current, total).
Definition pointcloudmodifier.hpp:325
void setCloud(const PointCloud::Ptr &cloud)
Set point cloud directly.
Definition pointcloudmodifier.hpp:577
Modifier & outlierStatFilter(const double &threshold, const int &mean)
Outlier statistical filter.
Definition pointcloudmodifier.hpp:271
Modifier & voxelFilter(const std::vector< double > &voxel)
Voxel grid filter with subvoxel handling.
Definition pointcloudmodifier.hpp:213
void visualize()
Visualize input and output point clouds.
Definition pointcloudmodifier.hpp:536
Modifier & cropBox(const std::vector< double > &box_params, const bool &negative=false)
Crop box filter.
Definition pointcloudmodifier.hpp:132
Modifier & timestampAnalyzer(const std::string &file_path)
Save timestamps to a file and print basic statistics.
Definition pointcloudmodifier.hpp:461
Modifier & transform(const Eigen::Affine3d &transformation)
Apply transformation to the point cloud.
Definition pointcloudmodifier.hpp:293
Modifier & cropSphere(const double &sphere_params, const bool &negative=false)
Crop sphere filter.
Definition pointcloudmodifier.hpp:154
Modifier & outlierRadiusFilter(const double &radius, const int &min_neighbors)
Outlier radius filter.
Definition pointcloudmodifier.hpp:249
std::map< std::pair< int, int >, Modifier > split(const double &grid_size, const ProgressCallback &on_progress=nullptr)
Split the point cloud into grid cells along x and y.
Definition pointcloudmodifier.hpp:333
static bool writeGridMetadata(const std::map< std::pair< int, int >, Modifier > &cells, const double &grid_size, const std::string &file_path, const std::string &extension=".pcd")
Write a metadata YAML for a grid split result.
Definition pointcloudmodifier.hpp:420
bool save(const std::string &file_path, pointcloudcrafter::tools::formats::FileFormat format)
Save point cloud to file based on the specified format.
Definition pointcloudmodifier.hpp:105
bool load(const std::string &file_path, pointcloudcrafter::tools::formats::FileFormat format)
Load a point cloud file based on the specified format.
Definition pointcloudmodifier.hpp:78