41 bool CObservation3DRangeScan::EXTERNALS_AS_TEXT =
false;
45 #define COBS3DRANGE_USE_MEMPOOL
52 #ifdef COBS3DRANGE_USE_MEMPOOL
66 std::vector<float>
pts_x,pts_y,pts_z;
67 std::vector<uint16_t>
idxs_x, idxs_y;
76 return H==req.
H && W==req.
W;
136 CObservation3DRangeScan::CObservation3DRangeScan( ) :
137 m_points3D_external_stored(false),
138 m_rangeImage_external_stored(false),
140 hasRangeImage(false),
141 range_is_depth(true),
142 hasIntensityImage(false),
143 intensityImageChannel(CH_VISIBLE),
144 hasConfidenceImage(false),
147 cameraParamsIntensity(),
161 #ifdef COBS3DRANGE_USE_MEMPOOL
264 vector<char> validRange(N);
265 in.ReadBuffer( &validRange[0],
sizeof(validRange[0])*N );
283 #ifdef COBS3DRANGE_USE_MEMPOOL
356 in >> do_have_labels;
416 M.loadFromTextFile(fil);
419 M.extractRow(0,
const_cast<std::vector<float>&
>(
points3D_x));
420 M.extractRow(1,
const_cast<std::vector<float>&
>(
points3D_y));
421 M.extractRow(2,
const_cast<std::vector<float>&
>(
points3D_z));
470 out_path = CImage::IMAGES_PATH_BASE;
471 size_t N=CImage::IMAGES_PATH_BASE.size()-1;
472 if (CImage::IMAGES_PATH_BASE[N]!=
'/' && CImage::IMAGES_PATH_BASE[N]!=
'\\' )
486 out_path = CImage::IMAGES_PATH_BASE;
487 size_t N=CImage::IMAGES_PATH_BASE.size()-1;
488 if (CImage::IMAGES_PATH_BASE[N]!=
'/' && CImage::IMAGES_PATH_BASE[N]!=
'\\' )
504 const string savedDir = CImage::IMAGES_PATH_BASE;
505 CImage::IMAGES_PATH_BASE = use_this_base_dir;
507 CImage::IMAGES_PATH_BASE = savedDir;
519 real_absolute_file_path,
545 const string savedDir = CImage::IMAGES_PATH_BASE;
546 CImage::IMAGES_PATH_BASE = use_this_base_dir;
548 CImage::IMAGES_PATH_BASE = savedDir;
553 real_absolute_file_path,
568 #define CALIB_DECIMAT 15
581 obs(obs_),z_offset(z_offset_) {}
586 if (
x.size()<4+4)
x.resize(4+4);
593 for (
size_t i=0;i<4;i++)
594 x[4+i] = camPar.
dist[i];
603 for (
size_t i=0;i<4;i++)
604 camPar.
dist[i] =
x[4+i];
616 const size_t nC = obs.
rangeImage.getColCount();
617 const size_t nR = obs.
rangeImage.getRowCount();
626 const size_t idx = nC*
r +
c;
635 const double x = P.
x/P.
z;
636 const double y = P.
y/P.
z;
640 const double r4 =
square(r2);
648 err.push_back(
c-pixel.
x );
649 err.push_back(
r-pixel.
y );
666 const double camera_offset)
674 TMyLevMar::TResultInfo
info;
676 const size_t nR = obs.
rangeImage.getRowCount();
677 const size_t nC = obs.
rangeImage.getColCount();
692 increments_x.assign(1e-4);
704 mrpt::utils::LVL_INFO,
714 out_camParams.
ncols = nC;
715 out_camParams.
nrows = nR;
726 const unsigned int &r1,
const unsigned int &r2,
727 const unsigned int &c1,
const unsigned int &c2 )
733 ASSERT_( (r2<rows) && (c2<cols) )
767 for (
unsigned int i = r1; i < r2; i++ )
768 for (
unsigned int j = c1; j < c2; j++ )
787 #ifdef COBS3DRANGE_USE_MEMPOOL
841 #ifdef COBS3DRANGE_USE_MEMPOOL
868 static const double EPSILON=1e-7;
881 const double angle_sup,
882 const double angle_inf,
883 const double oversampling_ratio,
929 const double real_FOV_left = atan2(cx, fx);
930 const double real_FOV_right = atan2(nCols-1-cx, fx);
933 const float FOV_equiv = 2. * std::max(real_FOV_left,real_FOV_right);
952 const float tan_min = -tan( std::abs(sp.
angle_inf) );
953 const float tan_max = tan( std::abs(sp.
angle_sup) );
957 std::vector<float> vert_ang_tan(nRows);
958 for (
size_t r=0;
r<nRows;
r++)
959 vert_ang_tan[
r] =
static_cast<float>( (cy-
r)/fy );
968 double ang = -FOV_equiv*0.5;
969 const double A_ang = FOV_equiv/(nLaserRays-1);
976 for (
size_t i=0;i<nLaserRays;i++, ang+=A_ang )
979 const double tan_ang = tan(ang);
981 const size_t c =
std::min(
static_cast<size_t>(std::max(0.0,cx + fx*tan_ang)),nCols-1);
983 bool any_valid =
false;
984 float closest_range = out_scan2d.
maxRange;
986 for (
size_t r=0;
r<nRows;
r++)
993 const float this_point_tan = vert_ang_tan[
r] * D;
994 if (this_point_tan>tan_min && this_point_tan<tan_max)
1005 out_scan2d.
setScanRange(i, closest_range*std::sqrt(1.0+tan_ang*tan_ang) );
1021 const std::vector<float> & xs = pc->getArrayX(), &ys = pc->getArrayY(), &zs = pc->getArrayZ();
1022 const size_t N = xs.size();
1024 const double A_ang = FOV_equiv/(nLaserRays-1);
1025 const double ang0 = -FOV_equiv*0.5;
1027 for (
size_t i=0;i<N;i++)
1032 const double phi_wrt_origin = atan2(ys[i], xs[i]);
1034 int i_range = (phi_wrt_origin-ang0)/A_ang;
1035 if (i_range<0 || i_range>=
int(nLaserRays))
1038 const float r_wrt_origin = ::hypotf(xs[i],ys[i]);
1039 if (out_scan2d.
scan[i_range]> r_wrt_origin) out_scan2d.
setScanRange(i_range, r_wrt_origin);
1052 o <<
"Homogeneous matrix for the sensor's 3D pose, relative to robot base:\n";
1055 o <<
"maxRange = " <<
maxRange <<
" m" << endl;
1057 o <<
"Has 3D point cloud? ";
1060 o <<
"YES: " <<
points3D_x.size() <<
" points";
1063 else o <<
" (embedded)." << endl;
1065 else o <<
"NO" << endl;
1067 o <<
"Has raw range data? " << (
hasRangeImage ?
"YES":
"NO");
1072 else o <<
" (embedded)." << endl;
1080 else o <<
" (embedded).\n";
1090 else o <<
" (embedded)." << endl;
1093 o << endl <<
"Has pixel labels? " << (
hasPixelLabels()?
"YES":
"NO");
1096 o <<
" Human readable labels:" << endl;
1098 o <<
" label[" << it->first <<
"]: '" << it->second <<
"'" << endl;
1102 o <<
"Depth camera calibration parameters:" << endl;
1108 o << endl <<
"Intensity camera calibration parameters:" << endl;
1114 o << endl << endl <<
"Pose of the intensity cam. wrt the depth cam:\n"
1145 in >> bitfield_bytes;
1149 switch (bitfield_bytes)
1160 throw std::runtime_error(
"Unknown type of pixelLabel inner class while deserializing!");
1178 z_min(-std::numeric_limits<double>::max() ),z_max(std::numeric_limits<double>::max()),
1179 oversampling_ratio(1.2),use_origin_sensor_pose(false)
void mempool_donate_range_matrix(CObservation3DRangeScan &obs)
mrpt::system::CGenericMemoryPool< CObservation3DRangeScan_Ranges_MemPoolParams, CObservation3DRangeScan_Ranges_MemPoolData > TMyRangesMemPool
mrpt::system::CGenericMemoryPool< CObservation3DRangeScan_Points_MemPoolParams, CObservation3DRangeScan_Points_MemPoolData > TMyPointsMemPool
void mempool_donate_xyz_buffers(CObservation3DRangeScan &obs)
#define IMPLEMENTS_SERIALIZABLE(class_name, base, NameSpace)
This must be inserted in all CSerializable classes implementation files.
An implementation of the Levenberg-Marquardt algorithm for least-square minimization.
This class is a "CSerializable" wrapper for "CMatrixFloat".
A matrix of dynamic size.
Column vector, like Eigen::MatrixX*, but automatically initialized to zeros since construction.
A "CObservation"-derived class that represents a 2D range scan measurement (typically from a laser sc...
void resizeScanAndAssign(const size_t len, const float rangeVal, const bool rangeValidity, const int32_t rangeIntensity=0)
Resizes all data vectors to allocate a given number of scan rays and assign default values.
float maxRange
The maximum range allowed by the device, in meters (e.g. 80m, 50m,...)
float aperture
The "aperture" or field-of-view of the range finder, in radians (typically M_PI = 180 degrees).
mrpt::poses::CPose3D sensorPose
The 6D pose of the sensor on the robot at the moment of starting the scan.
bool rightToLeft
The scanning direction: true=counterclockwise; false=clockwise.
mrpt::utils::ContainerReadOnlyProxyAccessor< std::vector< float > > scan
The range values of the scan, in meters. Must have same length than validRange.
void resizeScan(const size_t len)
Resizes all data vectors to allocate a given number of scan rays.
void setScanRangeValidity(const size_t i, const bool val)
void setScanRange(const size_t i, const float val)
Declares a class derived from "CObservation" that encapsules a 3D range scan measurement,...
void resizePoints3DVectors(const size_t nPoints)
Use this method instead of resizing all three points3D_x, points3D_y & points3D_z to allow the usage ...
void points3D_convertToExternalStorage(const std::string &fileName, const std::string &use_this_base_dir)
Users won't normally want to call this, it's only used from internal MRPT programs.
float stdError
The "sigma" error of the device in meters, used while inserting the scan in an occupancy grid.
bool m_points3D_external_stored
If set to true, m_points3D_external_file is valid.
mrpt::utils::TCamera cameraParamsIntensity
Projection parameters of the intensity (graylevel or RGB) camera.
bool hasPixelLabels() const
Returns true if the field CObservation3DRangeScan::pixelLabels contains a non-NULL smart pointer.
virtual void unload() MRPT_OVERRIDE
Unload all images, for the case they being delayed-load images stored in external files (othewise,...
void project3DPointsFromDepthImageInto(POINTMAP &dest_pointcloud, const T3DPointsProjectionParams &projectParams, const TRangeImageFilterParams &filterParams=TRangeImageFilterParams())
Project the RGB+D images into a 3D point cloud (with color if the target map supports it) and optiona...
std::shared_ptr< TPixelLabelInfoBase > TPixelLabelInfoPtr
Used in CObservation3DRangeScan::pixelLabels.
TPixelLabelInfoPtr pixelLabels
All information about pixel labeling is stored in this (smart pointer to) structure; refer to TPixelL...
TIntensityChannelID intensityImageChannel
The source of the intensityImage; typically the visible channel.
void rangeImage_convertToExternalStorage(const std::string &fileName, const std::string &use_this_base_dir)
Users won't normally want to call this, it's only used from internal MRPT programs.
std::vector< uint16_t > points3D_idxs_x
void writeToStream(mrpt::utils::CStream &out, int *getVersion) const
Introduces a pure virtual method responsible for writing to a CStream.
bool hasConfidenceImage
true means the field confidenceImage contains valid data
mrpt::utils::TCamera cameraParams
Projection parameters of the depth camera.
float maxRange
The maximum range allowed by the device, in meters (e.g. 8.0m, 5.0m,...)
bool hasIntensityImage
true means the field intensityImage contains valid data
mrpt::poses::CPose3D relativePoseIntensityWRTDepth
Relative pose of the intensity camera wrt the depth camera (which is the coordinates origin for this ...
void convertTo2DScan(mrpt::obs::CObservation2DRangeScan &out_scan2d, const T3DPointsTo2DScanParams &scanParams, const TRangeImageFilterParams &filterParams=TRangeImageFilterParams())
Convert this 3D observation into an "equivalent 2D fake laser scan", with a configurable vertical FOV...
bool points3D_isExternallyStored() const
std::string m_points3D_external_file
3D points are in CImage::IMAGES_PATH_BASE+<this_file_name>
std::string m_rangeImage_external_file
rangeImage is in CImage::IMAGES_PATH_BASE+<this_file_name>
void swap(CObservation3DRangeScan &o)
Very efficient method to swap the contents of two observations.
bool hasPoints3D
true means the field points3D contains valid data.
static bool EXTERNALS_AS_TEXT
Whether external files (3D points, range and confidence) are to be saved as .txt text files (MATLAB c...
bool doDepthAndIntensityCamerasCoincide() const
Return true if relativePoseIntensityWRTDepth equals the pure rotation (0,0,0,-90deg,...
void getZoneAsObs(CObservation3DRangeScan &obs, const unsigned int &r1, const unsigned int &r2, const unsigned int &c1, const unsigned int &c2)
Extract a ROI of the 3D observation as a new one.
std::vector< float > points3D_x
void readFromStream(mrpt::utils::CStream &in, int version)
Introduces a pure virtual method responsible for loading from a CStream This can not be used directly...
std::vector< uint16_t > points3D_idxs_y
//!< If hasPoints3D=true, the (x,y) pixel coordinates for each (X,Y,Z) point in points3D_x,...
mrpt::utils::CImage confidenceImage
If hasConfidenceImage=true, an image with the "confidence" value [range 0-255] as estimated by the ca...
std::vector< float > points3D_y
bool m_rangeImage_external_stored
If set to true, m_rangeImage_external_file is valid.
std::string points3D_getExternalStorageFileAbsolutePath() const
virtual ~CObservation3DRangeScan()
Destructor.
bool hasRangeImage
true means the field rangeImage contains valid data
std::vector< float > points3D_z
If hasPoints3D=true, the (X,Y,Z) coordinates of the 3D point cloud detected by the camera.
virtual void load() const MRPT_OVERRIDE
Makes sure all images and other fields which may be externally stored are loaded in memory.
mrpt::math::CMatrix rangeImage
If hasRangeImage=true, a matrix of floats with the range data as captured by the camera (in meters)
TIntensityChannelID
Enum type for intensityImageChannel.
@ CH_VISIBLE
Grayscale or RGB visible channel of the camera sensor.
static double recoverCameraCalibrationParameters(const CObservation3DRangeScan &in_obs, mrpt::utils::TCamera &out_camParams, const double camera_offset=0.01)
A Levenberg-Marquart-based optimizer to recover the calibration parameters of a 3D camera given a ran...
mrpt::utils::CImage intensityImage
If hasIntensityImage=true, a color or gray-level intensity image of the same size than "rangeImage".
void rangeImage_setSize(const int HEIGHT, const int WIDTH)
Similar to calling "rangeImage.setSize(H,W)" but this method provides memory pooling to speed-up the ...
mrpt::poses::CPose3D sensorPose
The 6D pose of the sensor on the robot.
bool rangeImage_isExternallyStored() const
void getDescriptionAsText(std::ostream &o) const MRPT_OVERRIDE
Build a detailed, multi-line textual description of the observation contents and dump it to the outpu...
bool range_is_depth
true: Kinect-like ranges: entries of rangeImage are distances along the +X axis; false: Ranges in ran...
std::string rangeImage_getExternalStorageFile() const
std::string rangeImage_getExternalStorageFileAbsolutePath() const
std::string points3D_getExternalStorageFile() const
Declares a class that represents any robot's observation.
virtual void getDescriptionAsText(std::ostream &o) const
Build a detailed, multi-line textual description of the observation contents and dump it to the outpu...
std::string sensorLabel
An arbitrary label that can be used to identify the sensor.
mrpt::system::TTimeStamp timestamp
The associated UTC time-stamp. Where available, this should contain the accurate satellite-based time...
void swap(CObservation &o)
Swap with another observation, ONLY the data defined here in the base class CObservation....
static CPointCloudPtr Create()
A class used to store a 3D pose (a 3D translation + a rotation in 3D).
void getRotationMatrix(mrpt::math::CMatrixDouble33 &ROT) const
Get the 3x3 rotation matrix.
mrpt::math::CMatrixDouble44 getHomogeneousMatrixVal() const
mrpt::math::CArrayDouble< 3 > m_coords
The translation vector [x,y,z] access directly or with x(), y(), z() setter/getter methods.
A generic system for versatile memory pooling.
POOLABLE_DATA * request_memory(const DATA_PARAMS ¶ms)
Request a block of data which fulfils the size requirements stated in params.
static CGenericMemoryPool< DATA_PARAMS, POOLABLE_DATA > * getInstance(const size_t max_pool_entries=5)
Construct-on-first-use (~singleton) pattern: Return the unique instance of this class for a given tem...
void dump_to_pool(const DATA_PARAMS ¶ms, POOLABLE_DATA *block)
Saves the passed data block (characterized by params) to the pool.
This class implements a config file-like interface over a memory-stored string list.
void getContent(std::string &str) const
Return the current contents of the virtual "config file".
std::string getExternalStorageFile() const MRPT_NO_THROWS
< Only if isExternallyStored() returns true.
bool isExternallyStored() const MRPT_NO_THROWS
See setExternalStorage().
void swap(CImage &o)
Very efficient swap of two images (just swap the internal pointers)
void extract_patch(CImage &patch, const unsigned int col=0, const unsigned int row=0, const unsigned int width=1, const unsigned int height=1) const
Extract a patch from this image, saveing it into "patch" (its previous contents will be overwritten).
void unload() const MRPT_NO_THROWS
For external storage image objects only, this method unloads the image from memory (or does nothing i...
This base class is used to provide a unified interface to files,memory buffers,..Please see the deriv...
void WriteBufferFixEndianness(const T *ptr, size_t ElementCount)
Writes a sequence of elemental datatypes, taking care of reordering their bytes from the running arch...
Structure to hold the parameters of a pinhole camera model.
double focalLengthMeters
The focal length of the camera, in meters (can be used among 'intrinsicParams' to determine the pixel...
uint32_t nrows
Camera resolution.
mrpt::math::CArrayDouble< 5 > dist
[k1 k2 t1 t2 k3] -> k_i: parameters of radial distortion, t_i: parameters of tangential distortion (d...
mrpt::math::CMatrixDouble33 intrinsicParams
Matrix of intrinsic parameters (containing the focal length and principal point coordinates)
double cx() const
Get the value of the principal point x-coordinate (in pixels).
void saveToConfigFile(const std::string §ion, mrpt::utils::CConfigFileBase &cfg) const
Save as a config block:
double fx() const
Get the value of the focal length x-value (in pixels).
double cy() const
Get the value of the principal point y-coordinate (in pixels).
double fy() const
Get the value of the focal length y-value (in pixels).
const Scalar * const_iterator
void loadFromTextFile(const std::string &file)
Load matrix from a text file, compatible with MATLAB text format.
GLdouble GLdouble GLdouble r
GLenum const GLfloat * params
GLsizei const GLchar ** string
std::string BASE_IMPEXP fileNameChangeExtension(const std::string &filename, const std::string &newExtension)
Replace the filename extension by another one.
std::string BASE_IMPEXP extractFileExtension(const std::string &filePath, bool ignore_gz=false)
Extract the extension of a filename.
#define CFileGZOutputStream
Saves data to a file and transparently compress the data using the given compression level.
bool BASE_IMPEXP strCmpI(const std::string &s1, const std::string &s2)
Return true if the two strings are equal (case insensitive)
#define ASSERT_EQUAL_(__A, __B)
#define ASSERT_ABOVE_(__A, __B)
#define MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(__V)
For use in CSerializable implementations.
This base provides a set of functions for maths stuff.
@ MATRIX_FORMAT_FIXED
fixed floating point 'f'
dynamic_vector< double > CVectorDouble
Column vector, like Eigen::MatrixXd, but automatically initialized to zeros since construction.
T square(const T x)
Inline function for the square of a number.
void cost_func(const CVectorDouble &par, const TLevMarData &d, CVectorDouble &err)
void cam2vec(const TCamera &camPar, CVectorDouble &x)
void vec2cam(const CVectorDouble &x, TCamera &camPar)
This namespace contains representation of robot actions and observations.
Classes for 2D/3D geometry representation, both of single values and probability density distribution...
Classes for serialization, sockets, ini-file manipulation, streams, list of properties-values,...
void vector_strong_clear(VECTOR_T &v)
Like calling a std::vector<>'s clear() method, but really forcing deallocating the memory.
void keep_min(T &var, const K test_val)
If the second argument is below the first one, set the first argument to this lower value.
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
This file implements several operations that operate element-wise on individual or pairs of container...
unsigned __int32 uint32_t
std::vector< float > pts_x
std::vector< uint16_t > idxs_x
std::vector< uint16_t > idxs_y
for each point, the corresponding (x,y) pixel coordinates
std::vector< float > pts_y
std::vector< float > pts_z
size_t WH
Width*Height, that is, the number of 3D points.
bool isSuitable(const CObservation3DRangeScan_Points_MemPoolParams &req) const
mrpt::math::CMatrix rangeImage
bool isSuitable(const CObservation3DRangeScan_Ranges_MemPoolParams &req) const
double z
X,Y,Z coordinates.
Look-up-table struct for project3DPointsFromDepthImageInto()
Virtual interface to all pixel-label information structs.
virtual void internal_readFromStream(mrpt::utils::CStream &in)=0
virtual void internal_writeToStream(mrpt::utils::CStream &out) const =0
const uint8_t BITFIELD_BYTES
Minimum number of bytes required to hold MAX_NUM_DIFFERENT_LABELS bits.
static TPixelLabelInfoBase * readAndBuildFromStream(mrpt::utils::CStream &in)
void writeToStream(mrpt::utils::CStream &out) const
Used in CObservation3DRangeScan::project3DPointsFromDepthImageInto()
bool takeIntoAccountSensorPoseOnRobot
(Default: false) If false, local (sensor-centric) coordinates of points are generated....
Used in CObservation3DRangeScan::convertTo2DScan()
std::string sensorLabel
The sensor label that will have the newly created observation.
double z_max
(Default:-inf, +inf) [Only if use_origin_sensor_pose=true] Only obstacle points with Z coordinates wi...
T3DPointsTo2DScanParams()
double oversampling_ratio
(Default=1.2=120%) How many more laser scans rays to create (read docs for CObservation3DRangeScan::c...
bool use_origin_sensor_pose
(Default:false) If false, the conversion will be such that the 2D observation pose on the robot coinc...
double angle_inf
(Default=5 degrees) [Only if use_origin_sensor_pose=false] The upper & lower half-FOV angle (in radia...
Mainly for internal use within CObservation3DRangeScan::project3DPointsFromDepthImageInto()
bool do_range_filter(size_t r, size_t c, const float D) const
Returns true if the point (r,c) with depth D passes all filters.
Used in CObservation3DRangeScan::project3DPointsFromDepthImageInto()
const mrpt::math::CMatrix * rangeMask_min
(Default: NULL) If provided, each data range will be tested to be greater-than (rangeMask_min) or les...
const mrpt::math::CMatrix * rangeMask_max
TLevMarData(const CObservation3DRangeScan &obs_, const double z_offset_)
const CObservation3DRangeScan & obs
static std::string value2name(const ENUMTYPE val)
Gives the textual name for a given enum value.
A pair (x,y) of pixel coordinates (subpixel resolution).