rgbd_inertial_realsense_D435i.cc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. /**
  2. * This file is part of ORB-SLAM3
  3. *
  4. * Copyright (C) 2017-2021 Carlos Campos, Richard Elvira, Juan J. Gómez Rodríguez, José M.M. Montiel and Juan D. Tardós, University of Zaragoza.
  5. * Copyright (C) 2014-2016 Raúl Mur-Artal, José M.M. Montiel and Juan D. Tardós, University of Zaragoza.
  6. *
  7. * ORB-SLAM3 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
  8. * License as published by the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * ORB-SLAM3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
  12. * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along with ORB-SLAM3.
  16. * If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <signal.h>
  19. #include <stdlib.h>
  20. #include <iostream>
  21. #include <algorithm>
  22. #include <fstream>
  23. #include <chrono>
  24. #include <ctime>
  25. #include <sstream>
  26. #include <condition_variable>
  27. #include <opencv2/core/core.hpp>
  28. #include <librealsense2/rs.hpp>
  29. #include "librealsense2/rsutil.h"
  30. #include <System.h>
  31. using namespace std;
  32. bool b_continue_session;
  33. void exit_loop_handler(int s){
  34. cout << "Finishing session" << endl;
  35. b_continue_session = false;
  36. }
  37. rs2_stream find_stream_to_align(const std::vector<rs2::stream_profile>& streams);
  38. bool profile_changed(const std::vector<rs2::stream_profile>& current, const std::vector<rs2::stream_profile>& prev);
  39. void interpolateData(const std::vector<double> &vBase_times,
  40. std::vector<rs2_vector> &vInterp_data, std::vector<double> &vInterp_times,
  41. const rs2_vector &prev_data, const double &prev_time);
  42. rs2_vector interpolateMeasure(const double target_time,
  43. const rs2_vector current_data, const double current_time,
  44. const rs2_vector prev_data, const double prev_time);
  45. static rs2_option get_sensor_option(const rs2::sensor& sensor)
  46. {
  47. // Sensors usually have several options to control their properties
  48. // such as Exposure, Brightness etc.
  49. std::cout << "Sensor supports the following options:\n" << std::endl;
  50. // The following loop shows how to iterate over all available options
  51. // Starting from 0 until RS2_OPTION_COUNT (exclusive)
  52. for (int i = 0; i < static_cast<int>(RS2_OPTION_COUNT); i++)
  53. {
  54. rs2_option option_type = static_cast<rs2_option>(i);
  55. //SDK enum types can be streamed to get a string that represents them
  56. std::cout << " " << i << ": " << option_type;
  57. // To control an option, use the following api:
  58. // First, verify that the sensor actually supports this option
  59. if (sensor.supports(option_type))
  60. {
  61. std::cout << std::endl;
  62. // Get a human readable description of the option
  63. const char* description = sensor.get_option_description(option_type);
  64. std::cout << " Description : " << description << std::endl;
  65. // Get the current value of the option
  66. float current_value = sensor.get_option(option_type);
  67. std::cout << " Current Value : " << current_value << std::endl;
  68. //To change the value of an option, please follow the change_sensor_option() function
  69. }
  70. else
  71. {
  72. std::cout << " is not supported" << std::endl;
  73. }
  74. }
  75. uint32_t selected_sensor_option = 0;
  76. return static_cast<rs2_option>(selected_sensor_option);
  77. }
  78. int main(int argc, char **argv) {
  79. if (argc < 3 || argc > 4) {
  80. cerr << endl
  81. << "Usage: ./mono_inertial_realsense_D435i path_to_vocabulary path_to_settings (trajectory_file_name)"
  82. << endl;
  83. return 1;
  84. }
  85. string file_name;
  86. if (argc == 4) {
  87. file_name = string(argv[argc - 1]);
  88. }
  89. struct sigaction sigIntHandler;
  90. sigIntHandler.sa_handler = exit_loop_handler;
  91. sigemptyset(&sigIntHandler.sa_mask);
  92. sigIntHandler.sa_flags = 0;
  93. sigaction(SIGINT, &sigIntHandler, NULL);
  94. b_continue_session = true;
  95. double offset = 0; // ms
  96. rs2::context ctx;
  97. rs2::device_list devices = ctx.query_devices();
  98. rs2::device selected_device;
  99. if (devices.size() == 0)
  100. {
  101. std::cerr << "No device connected, please connect a RealSense device" << std::endl;
  102. return 0;
  103. }
  104. else
  105. selected_device = devices[0];
  106. std::vector<rs2::sensor> sensors = selected_device.query_sensors();
  107. int index = 0;
  108. // We can now iterate the sensors and print their names
  109. for (rs2::sensor sensor : sensors)
  110. if (sensor.supports(RS2_CAMERA_INFO_NAME)) {
  111. ++index;
  112. if (index == 1) {
  113. sensor.set_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE, 1);
  114. // sensor.set_option(RS2_OPTION_AUTO_EXPOSURE_LIMIT,50000);
  115. sensor.set_option(RS2_OPTION_EMITTER_ENABLED, 1); // emitter on for depth information
  116. }
  117. // std::cout << " " << index << " : " << sensor.get_info(RS2_CAMERA_INFO_NAME) << std::endl;
  118. get_sensor_option(sensor);
  119. if (index == 2){
  120. // RGB camera
  121. sensor.set_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE,1);
  122. // sensor.set_option(RS2_OPTION_EXPOSURE,80.f);
  123. }
  124. if (index == 3){
  125. sensor.set_option(RS2_OPTION_ENABLE_MOTION_CORRECTION,0);
  126. }
  127. }
  128. // Declare RealSense pipeline, encapsulating the actual device and sensors
  129. rs2::pipeline pipe;
  130. // Create a configuration for configuring the pipeline with a non default profile
  131. rs2::config cfg;
  132. // RGB stream
  133. cfg.enable_stream(RS2_STREAM_COLOR,640, 480, RS2_FORMAT_RGB8, 30);
  134. // Depth stream
  135. // cfg.enable_stream(RS2_STREAM_INFRARED, 1, 640, 480, RS2_FORMAT_Y8, 30);
  136. cfg.enable_stream(RS2_STREAM_DEPTH,640, 480, RS2_FORMAT_Z16, 30);
  137. // IMU stream
  138. cfg.enable_stream(RS2_STREAM_ACCEL, RS2_FORMAT_MOTION_XYZ32F);
  139. cfg.enable_stream(RS2_STREAM_GYRO, RS2_FORMAT_MOTION_XYZ32F);
  140. // IMU callback
  141. std::mutex imu_mutex;
  142. std::condition_variable cond_image_rec;
  143. vector<double> v_accel_timestamp;
  144. vector<rs2_vector> v_accel_data;
  145. vector<double> v_gyro_timestamp;
  146. vector<rs2_vector> v_gyro_data;
  147. double prev_accel_timestamp = 0;
  148. rs2_vector prev_accel_data;
  149. double current_accel_timestamp = 0;
  150. rs2_vector current_accel_data;
  151. vector<double> v_accel_timestamp_sync;
  152. vector<rs2_vector> v_accel_data_sync;
  153. cv::Mat imCV, depthCV;
  154. int width_img, height_img;
  155. double timestamp_image = -1.0;
  156. bool image_ready = false;
  157. int count_im_buffer = 0; // count dropped frames
  158. // start and stop just to get necessary profile
  159. rs2::pipeline_profile pipe_profile = pipe.start(cfg);
  160. pipe.stop();
  161. // Align depth and RGB frames
  162. //Pipeline could choose a device that does not have a color stream
  163. //If there is no color stream, choose to align depth to another stream
  164. rs2_stream align_to = find_stream_to_align(pipe_profile.get_streams());
  165. // Create a rs2::align object.
  166. // rs2::align allows us to perform alignment of depth frames to others frames
  167. //The "align_to" is the stream type to which we plan to align depth frames.
  168. rs2::align align(align_to);
  169. rs2::frameset fsSLAM;
  170. auto imu_callback = [&](const rs2::frame& frame)
  171. {
  172. std::unique_lock<std::mutex> lock(imu_mutex);
  173. if(rs2::frameset fs = frame.as<rs2::frameset>())
  174. {
  175. count_im_buffer++;
  176. double new_timestamp_image = fs.get_timestamp()*1e-3;
  177. if(abs(timestamp_image-new_timestamp_image)<0.001){
  178. count_im_buffer--;
  179. return;
  180. }
  181. if (profile_changed(pipe.get_active_profile().get_streams(), pipe_profile.get_streams()))
  182. {
  183. //If the profile was changed, update the align object, and also get the new device's depth scale
  184. pipe_profile = pipe.get_active_profile();
  185. align_to = find_stream_to_align(pipe_profile.get_streams());
  186. align = rs2::align(align_to);
  187. }
  188. //Align depth and rgb takes long time, move it out of the interruption to avoid losing IMU measurements
  189. fsSLAM = fs;
  190. timestamp_image = fs.get_timestamp()*1e-3;
  191. image_ready = true;
  192. while(v_gyro_timestamp.size() > v_accel_timestamp_sync.size())
  193. {
  194. int index = v_accel_timestamp_sync.size();
  195. double target_time = v_gyro_timestamp[index];
  196. v_accel_data_sync.push_back(current_accel_data);
  197. v_accel_timestamp_sync.push_back(target_time);
  198. }
  199. lock.unlock();
  200. cond_image_rec.notify_all();
  201. } else if (rs2::motion_frame m_frame = frame.as<rs2::motion_frame>())
  202. {
  203. if (m_frame.get_profile().stream_name() == "Gyro")
  204. {
  205. // It runs at 200Hz
  206. v_gyro_data.push_back(m_frame.get_motion_data());
  207. v_gyro_timestamp.push_back((m_frame.get_timestamp()+offset)*1e-3);
  208. }
  209. else if (m_frame.get_profile().stream_name() == "Accel")
  210. {
  211. // It runs at 60Hz
  212. prev_accel_timestamp = current_accel_timestamp;
  213. prev_accel_data = current_accel_data;
  214. current_accel_data = m_frame.get_motion_data();
  215. current_accel_timestamp = (m_frame.get_timestamp()+offset)*1e-3;
  216. while(v_gyro_timestamp.size() > v_accel_timestamp_sync.size())
  217. {
  218. int index = v_accel_timestamp_sync.size();
  219. double target_time = v_gyro_timestamp[index];
  220. rs2_vector interp_data = interpolateMeasure(target_time, current_accel_data, current_accel_timestamp,
  221. prev_accel_data, prev_accel_timestamp);
  222. v_accel_data_sync.push_back(interp_data);
  223. v_accel_timestamp_sync.push_back(target_time);
  224. }
  225. }
  226. }
  227. };
  228. pipe_profile = pipe.start(cfg, imu_callback);
  229. vector<ORB_SLAM3::IMU::Point> vImuMeas;
  230. rs2::stream_profile cam_stream = pipe_profile.get_stream(RS2_STREAM_COLOR);
  231. rs2::stream_profile imu_stream = pipe_profile.get_stream(RS2_STREAM_GYRO);
  232. float* Rbc = cam_stream.get_extrinsics_to(imu_stream).rotation;
  233. float* tbc = cam_stream.get_extrinsics_to(imu_stream).translation;
  234. std::cout << "Tbc = " << std::endl;
  235. for(int i = 0; i<3; i++){
  236. for(int j = 0; j<3; j++)
  237. std::cout << Rbc[i*3 + j] << ", ";
  238. std::cout << tbc[i] << "\n";
  239. }
  240. rs2_intrinsics intrinsics_cam = cam_stream.as<rs2::video_stream_profile>().get_intrinsics();
  241. width_img = intrinsics_cam.width;
  242. height_img = intrinsics_cam.height;
  243. std::cout << " fx = " << intrinsics_cam.fx << std::endl;
  244. std::cout << " fy = " << intrinsics_cam.fy << std::endl;
  245. std::cout << " cx = " << intrinsics_cam.ppx << std::endl;
  246. std::cout << " cy = " << intrinsics_cam.ppy << std::endl;
  247. std::cout << " height = " << intrinsics_cam.height << std::endl;
  248. std::cout << " width = " << intrinsics_cam.width << std::endl;
  249. std::cout << " Coeff = " << intrinsics_cam.coeffs[0] << ", " << intrinsics_cam.coeffs[1] << ", " <<
  250. intrinsics_cam.coeffs[2] << ", " << intrinsics_cam.coeffs[3] << ", " << intrinsics_cam.coeffs[4] << ", " << std::endl;
  251. std::cout << " Model = " << intrinsics_cam.model << std::endl;
  252. // Create SLAM system. It initializes all system threads and gets ready to process frames.
  253. ORB_SLAM3::System SLAM(argv[1],argv[2],ORB_SLAM3::System::IMU_RGBD, true, 0, file_name);
  254. float imageScale = SLAM.GetImageScale();
  255. double timestamp;
  256. cv::Mat im, depth;
  257. // Clear IMU vectors
  258. v_gyro_data.clear();
  259. v_gyro_timestamp.clear();
  260. v_accel_data_sync.clear();
  261. v_accel_timestamp_sync.clear();
  262. double t_resize = 0.f;
  263. double t_track = 0.f;
  264. while (!SLAM.isShutDown())
  265. {
  266. std::vector<rs2_vector> vGyro;
  267. std::vector<double> vGyro_times;
  268. std::vector<rs2_vector> vAccel;
  269. std::vector<double> vAccel_times;
  270. rs2::frameset fs;
  271. {
  272. std::unique_lock<std::mutex> lk(imu_mutex);
  273. if(!image_ready)
  274. cond_image_rec.wait(lk);
  275. #ifdef COMPILEDWITHC14
  276. std::chrono::steady_clock::time_point time_Start_Process = std::chrono::steady_clock::now();
  277. #else
  278. std::chrono::monotonic_clock::time_point time_Start_Process = std::chrono::monotonic_clock::now();
  279. #endif
  280. fs = fsSLAM;
  281. if(count_im_buffer>1)
  282. cout << count_im_buffer -1 << " dropped frs\n";
  283. count_im_buffer = 0;
  284. while(v_gyro_timestamp.size() > v_accel_timestamp_sync.size())
  285. {
  286. int index = v_accel_timestamp_sync.size();
  287. double target_time = v_gyro_timestamp[index];
  288. rs2_vector interp_data = interpolateMeasure(target_time, current_accel_data, current_accel_timestamp, prev_accel_data, prev_accel_timestamp);
  289. v_accel_data_sync.push_back(interp_data);
  290. v_accel_timestamp_sync.push_back(target_time);
  291. }
  292. // Copy the IMU data
  293. vGyro = v_gyro_data;
  294. vGyro_times = v_gyro_timestamp;
  295. vAccel = v_accel_data_sync;
  296. vAccel_times = v_accel_timestamp_sync;
  297. // Image
  298. timestamp = timestamp_image;
  299. // Clear IMU vectors
  300. v_gyro_data.clear();
  301. v_gyro_timestamp.clear();
  302. v_accel_data_sync.clear();
  303. v_accel_timestamp_sync.clear();
  304. image_ready = false;
  305. }
  306. // Perform alignment here
  307. auto processed = align.process(fs);
  308. // Trying to get both other and aligned depth frames
  309. rs2::video_frame color_frame = processed.first(align_to);
  310. rs2::depth_frame depth_frame = processed.get_depth_frame();
  311. im = cv::Mat(cv::Size(width_img, height_img), CV_8UC3, (void*)(color_frame.get_data()), cv::Mat::AUTO_STEP);
  312. depth = cv::Mat(cv::Size(width_img, height_img), CV_16U, (void*)(depth_frame.get_data()), cv::Mat::AUTO_STEP);
  313. /*cv::Mat depthCV_8U;
  314. depthCV.convertTo(depthCV_8U,CV_8U,0.01);
  315. cv::imshow("depth image", depthCV_8U);*/
  316. for(int i=0; i<vGyro.size(); ++i)
  317. {
  318. ORB_SLAM3::IMU::Point lastPoint(vAccel[i].x, vAccel[i].y, vAccel[i].z,
  319. vGyro[i].x, vGyro[i].y, vGyro[i].z,
  320. vGyro_times[i]);
  321. vImuMeas.push_back(lastPoint);
  322. }
  323. if(imageScale != 1.f)
  324. {
  325. #ifdef REGISTER_TIMES
  326. #ifdef COMPILEDWITHC14
  327. std::chrono::steady_clock::time_point t_Start_Resize = std::chrono::steady_clock::now();
  328. #else
  329. std::chrono::monotonic_clock::time_point t_Start_Resize = std::chrono::monotonic_clock::now();
  330. #endif
  331. #endif
  332. int width = im.cols * imageScale;
  333. int height = im.rows * imageScale;
  334. cv::resize(im, im, cv::Size(width, height));
  335. cv::resize(depth, depth, cv::Size(width, height));
  336. #ifdef REGISTER_TIMES
  337. #ifdef COMPILEDWITHC14
  338. std::chrono::steady_clock::time_point t_End_Resize = std::chrono::steady_clock::now();
  339. #else
  340. std::chrono::monotonic_clock::time_point t_End_Resize = std::chrono::monotonic_clock::now();
  341. #endif
  342. t_resize = std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(t_End_Resize - t_Start_Resize).count();
  343. SLAM.InsertResizeTime(t_resize);
  344. #endif
  345. }
  346. #ifdef REGISTER_TIMES
  347. #ifdef COMPILEDWITHC14
  348. std::chrono::steady_clock::time_point t_Start_Track = std::chrono::steady_clock::now();
  349. #else
  350. std::chrono::monotonic_clock::time_point t_Start_Track = std::chrono::monotonic_clock::now();
  351. #endif
  352. #endif
  353. // Pass the image to the SLAM system
  354. SLAM.TrackRGBD(im, depth, timestamp, vImuMeas);
  355. #ifdef REGISTER_TIMES
  356. #ifdef COMPILEDWITHC14
  357. std::chrono::steady_clock::time_point t_End_Track = std::chrono::steady_clock::now();
  358. #else
  359. std::chrono::monotonic_clock::time_point t_End_Track = std::chrono::monotonic_clock::now();
  360. #endif
  361. t_track = t_resize + std::chrono::duration_cast<std::chrono::duration<double,std::milli> >(t_End_Track - t_Start_Track).count();
  362. SLAM.InsertTrackTime(t_track);
  363. #endif
  364. // Clear the previous IMU measurements to load the new ones
  365. vImuMeas.clear();
  366. }
  367. cout << "System shutdown!\n";
  368. }
  369. rs2_stream find_stream_to_align(const std::vector<rs2::stream_profile>& streams)
  370. {
  371. //Given a vector of streams, we try to find a depth stream and another stream to align depth with.
  372. //We prioritize color streams to make the view look better.
  373. //If color is not available, we take another stream that (other than depth)
  374. rs2_stream align_to = RS2_STREAM_ANY;
  375. bool depth_stream_found = false;
  376. bool color_stream_found = false;
  377. for (rs2::stream_profile sp : streams)
  378. {
  379. rs2_stream profile_stream = sp.stream_type();
  380. if (profile_stream != RS2_STREAM_DEPTH)
  381. {
  382. if (!color_stream_found) //Prefer color
  383. align_to = profile_stream;
  384. if (profile_stream == RS2_STREAM_COLOR)
  385. {
  386. color_stream_found = true;
  387. }
  388. }
  389. else
  390. {
  391. depth_stream_found = true;
  392. }
  393. }
  394. if(!depth_stream_found)
  395. throw std::runtime_error("No Depth stream available");
  396. if (align_to == RS2_STREAM_ANY)
  397. throw std::runtime_error("No stream found to align with Depth");
  398. return align_to;
  399. }
  400. bool profile_changed(const std::vector<rs2::stream_profile>& current, const std::vector<rs2::stream_profile>& prev)
  401. {
  402. for (auto&& sp : prev)
  403. {
  404. //If previous profile is in current (maybe just added another)
  405. auto itr = std::find_if(std::begin(current), std::end(current), [&sp](const rs2::stream_profile& current_sp) { return sp.unique_id() == current_sp.unique_id(); });
  406. if (itr == std::end(current)) //If it previous stream wasn't found in current
  407. {
  408. return true;
  409. }
  410. }
  411. return false;
  412. }
  413. rs2_vector interpolateMeasure(const double target_time,
  414. const rs2_vector current_data, const double current_time,
  415. const rs2_vector prev_data, const double prev_time)
  416. {
  417. // If there are not previous information, the current data is propagated
  418. if(prev_time == 0)
  419. {
  420. return current_data;
  421. }
  422. rs2_vector increment;
  423. rs2_vector value_interp;
  424. if(target_time > current_time) {
  425. value_interp = current_data;
  426. }
  427. else if(target_time > prev_time)
  428. {
  429. increment.x = current_data.x - prev_data.x;
  430. increment.y = current_data.y - prev_data.y;
  431. increment.z = current_data.z - prev_data.z;
  432. double factor = (target_time - prev_time) / (current_time - prev_time);
  433. value_interp.x = prev_data.x + increment.x * factor;
  434. value_interp.y = prev_data.y + increment.y * factor;
  435. value_interp.z = prev_data.z + increment.z * factor;
  436. // zero interpolation
  437. value_interp = current_data;
  438. }
  439. else {
  440. value_interp = prev_data;
  441. }
  442. return value_interp;
  443. }