18 #include <mrpt/otherlibs/do_opencv_includes.h>
33 #if MRPT_HAS_KINECT_FREENECT
34 #if defined(__APPLE__)
35 #include <libfreenect/libfreenect.h>
37 #include <libfreenect.h>
44 #if MRPT_HAS_KINECT_FREENECT
46 #define f_ctx reinterpret_cast<freenect_context*>(m_f_ctx)
47 #define f_ctx_ptr reinterpret_cast<freenect_context**>(&m_f_ctx)
48 #define f_dev reinterpret_cast<freenect_device*>(m_f_dev)
49 #define f_dev_ptr reinterpret_cast<freenect_device**>(&m_f_dev)
52 #ifdef KINECT_PROFILE_MEM_ALLOC
59 #ifdef MRPT_KINECT_DEPTH_10BIT
60 const float k1 = 1.1863f;
61 const float k2 = 2842.5f;
62 const float k3 = 0.1236f;
65 m_range2meters[i] = k3 * tanf(i / k2 + k1);
69 m_range2meters[i] = 1.0f / (i * (-0.0030711016) + 3.3309495161);
73 m_range2meters[0] = 0;
81 : m_sensorPoseOnRobot(),
82 m_preview_window(false),
83 m_preview_window_decimation(1),
84 m_preview_decim_counter_range(0),
85 m_preview_decim_counter_rgb(0),
87 #if MRPT_HAS_KINECT_FREENECT
90 m_tim_latest_depth(0),
93 m_relativePoseIntensityWRTDepth(
95 m_initial_tilt_angle(360),
96 m_user_device_number(0),
99 m_grab_3D_points(true),
138 "MRPT was compiled without support for Kinect. Please, rebuild it.")
158 bool thereIs, hwError;
161 mrpt::make_aligned_shared<CObservation3DRangeScan>();
163 mrpt::make_aligned_shared<CObservationIMU>();
177 vector<CSerializable::Ptr> objs;
179 objs.push_back(newObs);
197 configSource.
read_float(iniSection,
"pose_x", 0),
198 configSource.
read_float(iniSection,
"pose_y", 0),
199 configSource.
read_float(iniSection,
"pose_z", 0),
231 catch (std::exception& e)
233 std::cout <<
"[CKinect::loadConfig_sensorSpecific] Warning: Ignoring "
234 "error loading calibration parameters:\n"
259 iniSection,
"relativePoseIntensityWRTDepth",
"");
269 #if MRPT_HAS_KINECT_FREENECT
270 return f_dev !=
nullptr;
278 #if MRPT_HAS_KINECT_FREENECT
280 void depth_cb(freenect_device* dev,
void* v_depth,
uint32_t timestamp)
282 const freenect_frame_mode frMode = freenect_get_current_video_mode(dev);
289 std::lock_guard<std::mutex> lock(
obj->internal_latest_obs_cs());
295 #ifdef KINECT_PROFILE_MEM_ALLOC
296 alloc_tim.
enter(
"depth_cb alloc");
302 #ifdef KINECT_PROFILE_MEM_ALLOC
303 alloc_tim.
leave(
"depth_cb alloc");
307 for (
int r = 0;
r < frMode.height;
r++)
308 for (
int c = 0;
c < frMode.width;
c++)
316 obj->internal_tim_latest_depth() = timestamp;
319 void rgb_cb(freenect_device* dev,
void* img_data,
uint32_t timestamp)
322 const freenect_frame_mode frMode = freenect_get_current_video_mode(dev);
325 std::lock_guard<std::mutex> lock(
obj->internal_latest_obs_cs());
328 #ifdef KINECT_PROFILE_MEM_ALLOC
329 alloc_tim.
enter(
"depth_rgb loadFromMemoryBuffer");
343 frMode.width, frMode.height,
CH_RGB,
true );
346 #if MRPT_OPENCV_VERSION_NUM < 0x200
348 IplImage* src_img_bayer =
349 cvCreateImageHeader(cvSize(frMode.width, frMode.height), 8, 1);
350 src_img_bayer->imageDataOrigin =
reinterpret_cast<char*
>(img_data);
351 src_img_bayer->imageData = src_img_bayer->imageDataOrigin;
352 src_img_bayer->widthStep = frMode.width;
357 cvCvtColor(src_img_bayer, dst_img_RGB, CV_BayerGB2BGR);
361 const cv::Mat src_img_bayer(
362 frMode.height, frMode.width, CV_8UC1, img_data, frMode.width);
364 cv::Mat dst_img_RGB = cv::cvarrToMat(
369 cv::cvtColor(src_img_bayer, dst_img_RGB, CV_BayerGB2BGR);
380 frMode.width, frMode.height,
382 reinterpret_cast<unsigned char*
>(img_data));
387 #ifdef KINECT_PROFILE_MEM_ALLOC
388 alloc_tim.
leave(
"depth_rgb loadFromMemoryBuffer");
391 obj->internal_tim_latest_rgb() = timestamp;
404 #if MRPT_HAS_KINECT_FREENECT
406 if (freenect_init(f_ctx_ptr,
nullptr) < 0)
409 freenect_set_log_level(
418 int nr_devices = freenect_num_devices(f_ctx);
431 freenect_set_led(f_dev, LED_RED);
432 freenect_set_depth_callback(f_dev, depth_cb);
433 freenect_set_video_callback(f_dev, rgb_cb);
436 const freenect_frame_mode desiredFrMode = freenect_find_video_mode(
437 FREENECT_RESOLUTION_MEDIUM,
439 ? FREENECT_VIDEO_IR_8BIT
440 : FREENECT_VIDEO_BAYER
445 if (freenect_set_video_mode(f_dev, desiredFrMode) < 0)
449 const freenect_frame_mode frMode = freenect_get_current_video_mode(f_dev);
452 m_buf_depth.resize(frMode.width * frMode.height * 3);
453 m_buf_rgb.resize(frMode.width * frMode.height * 3);
462 freenect_set_video_buffer(f_dev, &
m_buf_rgb[0]);
465 freenect_set_depth_mode(
466 f_dev, freenect_find_depth_mode(
467 FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_10BIT));
470 freenect_set_user(f_dev,
this);
472 if (freenect_start_depth(f_dev) < 0)
475 if (freenect_start_video(f_dev) < 0)
483 #if MRPT_HAS_KINECT_FREENECT
486 freenect_stop_depth(f_dev);
487 freenect_stop_video(f_dev);
488 freenect_close_device(f_dev);
492 if (f_ctx) freenect_shutdown(f_ctx);
504 #if MRPT_HAS_KINECT_FREENECT
509 freenect_stop_video(f_dev);
512 const freenect_frame_mode desiredFrMode = freenect_find_video_mode(
513 FREENECT_RESOLUTION_MEDIUM,
515 ? FREENECT_VIDEO_IR_8BIT
516 : FREENECT_VIDEO_BAYER
521 if (freenect_set_video_mode(f_dev, desiredFrMode) < 0)
524 freenect_start_video(f_dev);
542 bool& hardware_error)
544 there_is_obs =
false;
545 hardware_error =
false;
547 #if MRPT_HAS_KINECT_FREENECT
549 using namespace std::chrono_literals;
550 const auto max_wait = 40ms;
553 m_latest_obs.hasPoints3D =
false;
554 m_latest_obs.hasRangeImage =
false;
555 m_latest_obs.hasIntensityImage =
false;
556 m_latest_obs.hasConfidenceImage =
false;
562 m_latest_obs_cs.lock();
563 m_tim_latest_rgb = 0;
564 m_tim_latest_depth = 0;
565 m_latest_obs_cs.unlock();
567 while (freenect_process_events(f_ctx) >= 0 &&
572 m_tim_latest_rgb != 0) &&
575 m_tim_latest_depth != 0)
594 m_latest_obs.hasRangeImage =
true;
595 m_latest_obs.range_is_depth =
true;
597 m_latest_obs_cs.lock();
600 m_latest_obs.rangeImage.setSize(
602 m_latest_obs.rangeImage.setConstant(0);
603 m_latest_obs_cs.unlock();
607 if (!there_is_obs)
return;
612 m_latest_obs_cs.lock();
613 _out_obs.
swap(m_latest_obs);
614 m_latest_obs_cs.unlock();
650 mrpt::make_aligned_shared<mrpt::gui::CDisplayWindow>(
671 mrpt::make_aligned_shared<mrpt::gui::CDisplayWindow>(
672 "Preview INTENSITY");
692 bool& hardware_error)
700 double acc_x = 0, acc_y = 0, acc_z = 0;
701 bool has_good_acc =
false;
703 #if MRPT_HAS_KINECT_FREENECT
705 freenect_update_tilt_state(f_dev);
706 freenect_raw_tilt_state* state = freenect_get_tilt_state(f_dev);
711 freenect_get_mks_accel(state, &lx, &ly, &lz);
731 for (
size_t i = 0; i < out_obs_imu.
dataIsPresent.size(); i++)
770 #if MRPT_HAS_KINECT_FREENECT
771 freenect_set_tilt_degs(f_dev, angle);
781 #if MRPT_KINECT_WITH_FREENECT
782 freenect_update_tilt_state(f_dev);
783 freenect_raw_tilt_state* ts = freenect_get_tilt_state(f_dev);
784 return freenect_get_tilt_degs(ts);
#define IMPLEMENTS_GENERIC_SENSOR(class_name, NameSpace)
This must be inserted in all CGenericSensor classes implementation files:
#define KINECT_RANGES_TABLE_MASK
#define KINECT_RANGES_TABLE_LEN
This class allows loading and storing values and vectors of different types from a configuration text...
ENUMTYPE read_enum(const std::string §ion, const std::string &name, const ENUMTYPE &defaultValue, bool failIfNotFound=false) const
Reads an "enum" value, where the value in the config file can be either a numerical value or the symb...
bool read_bool(const std::string §ion, const std::string &name, bool defaultValue, bool failIfNotFound=false) const
std::string read_string(const std::string §ion, const std::string &name, const std::string &defaultValue, bool failIfNotFound=false) const
int read_int(const std::string §ion, const std::string &name, int defaultValue, bool failIfNotFound=false) const
float read_float(const std::string §ion, const std::string &name, float defaultValue, bool failIfNotFound=false) const
void appendObservations(const std::vector< mrpt::serialization::CSerializable::Ptr > &obj)
This method must be called by derived classes to enqueue a new observation in the list to be returned...
std::string m_sensorLabel
See CGenericSensor.
A class for grabing "range images", intensity images (either RGB or IR) and other information from an...
void close()
Close the Connection to the sensor (not need to call it manually unless desired for some reason,...
void open()
Try to open the camera (set all the parameters before calling this) - users may also call initialize(...
void getNextObservation(mrpt::obs::CObservation3DRangeScan &out_obs, bool &there_is_obs, bool &hardware_error)
The main data retrieving function, to be called after calling loadConfig() and initialize().
int m_user_device_number
Number of device to open (0:first,...)
bool m_preview_window
Show preview window while grabbing.
mrpt::poses::CPose3D m_relativePoseIntensityWRTDepth
See mrpt::obs::CObservation3DRangeScan for a diagram of this pose.
void calculate_range2meters()
Compute m_range2meters at construction.
void setTiltAngleDegrees(double angle)
Change tilt angle.
void setVideoChannel(const TVideoChannel vch)
Changes the video channel to open (RGB or IR) - you can call this method before start grabbing or in ...
TDepth2RangeArray m_range2meters
The table raw depth -> range in meters.
size_t m_preview_decim_counter_rgb
mrpt::img::TCamera m_cameraParamsDepth
Params for the Depth camera.
mrpt::img::TCamera m_cameraParamsRGB
Params for the RGB camera.
std::vector< uint8_t > m_buf_depth
Temporary buffers for image grabbing.
double m_maxRange
Sensor max range (meters)
virtual void loadConfig_sensorSpecific(const mrpt::config::CConfigFileBase &configSource, const std::string §ion)
See the class documentation at the top for expected parameters.
double getTiltAngleDegrees()
virtual void setPathForExternalImages(const std::string &directory)
Set the path where to save off-rawlog image files (this class DOES take into account this path).
TVideoChannel m_video_channel
The video channel to open: RGB or IR.
size_t m_preview_decim_counter_range
float[KINECT_RANGES_TABLE_LEN] TDepth2RangeArray
A type for an array that converts raw depth to ranges in meters.
mrpt::gui::CDisplayWindow::Ptr m_win_range
virtual void doProcess()
To be called at a high rate (>XX Hz), this method populates the internal buffer of received observati...
mrpt::poses::CPose3D m_sensorPoseOnRobot
virtual void initialize()
Initializes the 3D camera - should be invoked after calling loadConfig() or setting the different par...
bool isOpen() const
Whether there is a working connection to the sensor.
std::vector< uint8_t > m_buf_rgb
TVideoChannel
RGB or IR video channel identifiers.
size_t m_preview_window_decimation
If preview is enabled, only show 1 out of N images.
bool m_grab_image
Default: all true.
int m_initial_tilt_angle
Set Kinect tilt to an initial deegre (it should be take in account in the sensor pose by the user)
mrpt::gui::CDisplayWindow::Ptr m_win_int
A class for storing images as grayscale or RGB bitmaps.
const T * getAs() const
Returns a pointer to a const T* containing the image - the idea is to call like "img....
void loadFromMemoryBuffer(unsigned int width, unsigned int height, bool color, unsigned char *rawpixels, bool swapRedBlue=false)
Reads the image from raw pixels buffer in memory.
void resize(unsigned int width, unsigned int height, TImageChannels nChannels, bool originTopLeft)
Changes the size of the image, erasing previous contents (does NOT scale its current content,...
std::array< double, 5 > dist
[k1 k2 t1 t2 k3] -> k_i: parameters of radial distortion, t_i: parameters of tangential distortion (d...
double fx() const
Get the value of the focal length x-value (in pixels).
double fy() const
Get the value of the focal length y-value (in pixels).
double cx() const
Get the value of the principal point x-coordinate (in pixels).
uint32_t ncols
Camera resolution.
double cy() const
Get the value of the principal point y-coordinate (in pixels).
Structure to hold the parameters of a pinhole stereo camera model.
mrpt::math::TPose3DQuat rightCameraPose
Pose of the right camera with respect to the coordinate origin of the left camera.
void loadFromConfigFile(const std::string §ion, const mrpt::config::CConfigFileBase &cfg)
Load all the params from a config source, in the same format that used in saveToConfigFile().
TCamera leftCamera
Intrinsic and distortion parameters of the left and right cameras.
A matrix of dynamic size.
Declares a class derived from "CObservation" that encapsules a 3D range scan measurement,...
TIntensityChannelID intensityImageChannel
The source of the intensityImage; typically the visible channel.
mrpt::img::TCamera cameraParams
Projection parameters of the depth camera.
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 swap(CObservation3DRangeScan &o)
Very efficient method to swap the contents of two observations.
mrpt::img::CImage intensityImage
If hasIntensityImage=true, a color or gray-level intensity image of the same size than "rangeImage".
void project3DPointsFromDepthImage(const bool PROJ3D_USE_LUT=true)
This method is equivalent to project3DPointsFromDepthImageInto() storing the projected 3D points (wit...
bool hasRangeImage
true means the field rangeImage contains valid data
mrpt::math::CMatrix rangeImage
If hasRangeImage=true, a matrix of floats with the range data as captured by the camera (in meters)
@ CH_IR
Infrarred (IR) channel.
@ CH_VISIBLE
Grayscale or RGB visible channel of the camera sensor.
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 ...
std::shared_ptr< CObservation3DRangeScan > Ptr
mrpt::poses::CPose3D sensorPose
The 6D pose of the sensor on the robot.
mrpt::img::TCamera cameraParamsIntensity
Projection parameters of the intensity (graylevel or RGB) camera.
bool range_is_depth
true: Kinect-like ranges: entries of rangeImage are distances along the +X axis; false: Ranges in ran...
std::string sensorLabel
An arbitrary label that can be used to identify the sensor.
mrpt::system::TTimeStamp timestamp
The associated UTC time-stamp.
This class stores measurements from an Inertial Measurement Unit (IMU) (attitude estimation,...
std::vector< double > rawMeasurements
The accelerometer and/or gyroscope measurements taken by the IMU at the given timestamp.
mrpt::poses::CPose3D sensorPose
The pose of the sensor on the robot.
std::vector< bool > dataIsPresent
Each entry in this vector is true if the corresponding data index contains valid data (the IMU unit s...
std::shared_ptr< CObservationIMU > Ptr
A class used to store a 3D pose (a 3D translation + a rotation in 3D).
void setFromValues(const double x0, const double y0, const double z0, const double yaw=0, const double pitch=0, const double roll=0)
Set the pose from a 3D position (meters) and yaw/pitch/roll angles (radians) - This method recomputes...
void fromString(const std::string &s)
Set the current object value from a string generated by 'asString' (eg: "[x y z yaw pitch roll]",...
A class used to store a 3D pose as a translation (x,y,z) and a quaternion (qr,qx,qy,...
mrpt::math::TPose3DQuat asTPose() const
A versatile "profiler" that logs the time spent within each pair of calls to enter(X)-leave(X),...
void enter(const char *func_name)
Start of a named section.
double leave(const char *func_name)
End of a named section.
#define MRPT_UNUSED_PARAM(a)
Determines whether this is an X86 or AMD64 platform.
#define THROW_EXCEPTION(msg)
#define ASSERTMSG_(f, __ERROR_MSG)
Defines an assertion mechanism.
#define THROW_EXCEPTION_FMT(_FORMAT_STRING,...)
GLsizei GLsizei GLuint * obj
GLint GLint GLsizei GLsizei GLsizei depth
GLdouble GLdouble GLdouble r
GLsizei const GLchar ** string
@ IMU_X_ACC
x-axis acceleration (local/vehicle frame) (m/sec2)
@ IMU_Z_ACC
z-axis acceleration (local/vehicle frame) (m/sec2)
@ IMU_Y_ACC
y-axis acceleration (local/vehicle frame) (m/sec2)
mrpt::Clock::time_point TTimeStamp
A system independent time type, it holds the the number of 100-nanosecond intervals since January 1,...
mrpt::system::TTimeStamp now()
A shortcut for system::getCurrentTime.
Contains classes for various device interfaces.
This base provides a set of functions for maths stuff.
This namespace contains representation of robot actions and observations.
Classes for 2D/3D geometry representation, both of single values and probability density distribution...
double DEG2RAD(const double x)
Degrees to radians.
unsigned __int16 uint16_t
unsigned __int32 uint32_t