diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ce11a82 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +recorddata/ \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index eb32030..420a73e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -98,8 +98,9 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON) # Find common dependencies find_package(PkgConfig REQUIRED) -find_package(OpenCV REQUIRED COMPONENTS core imgproc highgui) +find_package(OpenCV REQUIRED) find_package(Eigen3 REQUIRED) +find_package(PCL REQUIRED) find_package(yaml-cpp REQUIRED) find_package(OpenSSL REQUIRED) pkg_check_modules(LIBUSB REQUIRED libusb-1.0) @@ -109,6 +110,7 @@ include_directories( include ${EIGEN3_INCLUDE_DIRS} ${OpenCV_INCLUDE_DIRS} + ${PCL_INCLUDE_DIRS} ${yaml-cpp_INCLUDE_DIR} ${LIBUSB_INCLUDE_DIRS} ${CMAKE_CURRENT_SOURCE_DIR}/include @@ -117,6 +119,7 @@ include_directories( # Shared library list set(COMMON_LIBS ${OpenCV_LIBS} + ${PCL_LIBRARIES} ${yaml-cpp_LIBRARIES} ${OPENSSL_LIBRARIES} ${LIBUSB_LIBRARIES} @@ -166,7 +169,27 @@ if(ROS_VERSION STREQUAL "ROS1") pthread usb-1.0 ) - + + add_library(pointcloud_depth_converter src/pointcloud_depth_converter.cpp) + target_link_libraries(pointcloud_depth_converter + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + ) + add_library(depth_image_ros_node src/depth_image_ros_node.cpp) + target_link_libraries(depth_image_ros_node + pointcloud_depth_converter + ${catkin_LIBRARIES} + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + ) + add_executable(pcd2depth_node src/pcd2depth_ros.cpp) + target_link_libraries(pcd2depth_node + depth_image_ros_node + ${catkin_LIBRARIES} + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + ) + # Installation rules install(TARGETS host_sdk_sample RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} @@ -194,6 +217,8 @@ elseif(ROS_VERSION STREQUAL "ROS2") find_package(nav_msgs REQUIRED) find_package(cv_bridge REQUIRED) find_package(image_transport REQUIRED) + find_package(pcl_conversions REQUIRED) + find_package(message_filters REQUIRED) # Create executable add_executable(host_sdk_sample @@ -220,9 +245,53 @@ elseif(ROS_VERSION STREQUAL "ROS2") image_transport ) + + add_library(pointcloud_depth_converter_ros2 src/pointcloud_depth_converter.cpp) + target_link_libraries(pointcloud_depth_converter_ros2 + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + ) + + add_library(depth_image_ros2_node_lib src/depth_image_ros2_node.cpp) + target_link_libraries(depth_image_ros2_node_lib + pointcloud_depth_converter_ros2 + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + ) + + ament_target_dependencies(depth_image_ros2_node_lib + rclcpp + sensor_msgs + std_msgs + cv_bridge + image_transport + pcl_conversions + message_filters + ) + + add_executable(pcd2depth_ros2_node src/pcd2depth_ros2.cpp) + target_link_libraries(pcd2depth_ros2_node + depth_image_ros2_node_lib + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + yaml-cpp + ) + + ament_target_dependencies(pcd2depth_ros2_node + rclcpp + sensor_msgs + std_msgs + cv_bridge + image_transport + pcl_conversions + message_filters + ) + # Installation rules - ensure all install targets are defined before ament_package() # Install executable - install(TARGETS host_sdk_sample + install(TARGETS + host_sdk_sample + pcd2depth_ros2_node EXPORT export_${PROJECT_NAME} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib @@ -269,6 +338,8 @@ elseif(ROS_VERSION STREQUAL "ROS2") nav_msgs cv_bridge image_transport + pcl_conversions + message_filters ) ament_package() diff --git a/README.md b/README.md index 9da957a..f4cc2d8 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ This driver package provides core functionality for point cloud SLAM application ## 1. Version -Current Version: v0.4.0 +Current Version: v0.4.1 ## 2. Preparation @@ -30,7 +30,7 @@ Current Version: v0.4.0 ### 2.2 Dependencies -● Opencv +● Opencv >= 4.5.0(recommand 4.5.5/4.8.0) ● yaml-cpp @@ -123,7 +123,7 @@ source /opt/ros/foxy/setup.bash ```shell source [ros_workspace]/install/setup.bash -ros2 launch odin_ros_driver [launch file] +roslaunch odin_ros_driver [launch file] ``` ● odin_ros_driver: package name; @@ -158,6 +158,11 @@ Odin_ROS_Driver/ // ROS1/ROS2 driver package host_sdk_sample.cpp // Example source code yaml_parser.cpp // Source code for reading yaml parameters rawCloudRender.cpp // Source code for RenderCloud + depth_image_ros_node.cpp //depth_image_ros_node + depth_image_ros2_node.cpp //depth_image_ros2_node + pcd2depth_ros.cpp //Source code for pcd2depth_ros + pcd2depth_ros2.cpp //Source code for pcd2depth_ros2 + pointcloud_depth_converter.cpp //Source code for pointcloud_depth_converter lib/ liblydHostApi_amd.a // Static library for AMD platform liblydHostApi_arm.a // Static library for ARM platform @@ -167,6 +172,10 @@ Odin_ROS_Driver/ // ROS1/ROS2 driver package lidar_api.h // API function declarations yaml_parser.h // Parameter file reading header file rawCloudRender.h // API about RenderCloud + data_logger.h // LOG about save_data + depth_image_ros_node.hpp // depth_image_ros_node + depth_image_ros2_node.hpp // depth_image_ros2_node + pointcloud_depth_converter.hpp // pointcloud_depth_convert config/ control_command.yaml // Control parameter file for driver calib.yaml //Machine calibration yaml @@ -200,6 +209,8 @@ Internal parameters of the Odin ROS driver are defined in config/control_command | odin1/cloud_render | Render_Cloud Topic | | odin1/cloud_slam | Slam_PointCloud Topic | | odin1/odometry | Odom Topic | +| odin1/depth_img_competetion | Dense depth image Topic | +| odin1/depth_img_competetion_cloud | Dense Depth_Cloud Topic | ## 5. FAQ ### 5.1 Segmentation fault upon re-launching host SDK diff --git a/config/control_command.yaml b/config/control_command.yaml index 32102c9..21e8235 100644 --- a/config/control_command.yaml +++ b/config/control_command.yaml @@ -7,4 +7,6 @@ register_keys: sendcloudslam: 1 sendcloudrender: 1 sendrgbcompressed: 1 + senddepth: 0 + recorddata: 0 diff --git a/config/odin_ros.rviz b/config/odin_ros.rviz index 78f2e72..bd6b87c 100644 --- a/config/odin_ros.rviz +++ b/config/odin_ros.rviz @@ -1,11 +1,11 @@ Panels: - Class: rviz/Displays - Help Height: 78 + Help Height: 138 Name: Displays Property Tree Widget: Expanded: ~ Splitter Ratio: 0.5 - Tree Height: 489 + Tree Height: 767 - Class: rviz/Selection Name: Selection - Class: rviz/Tool Properties @@ -61,6 +61,18 @@ Visualization Manager: Transport Hint: raw Unreliable: false Value: true + - Class: rviz/Image + Enabled: false + Image Topic: /odin1/depth_img_competetion + Max Value: 1 + Median window: 5 + Min Value: 0 + Name: dense_depth_image + Normalize Range: true + Queue Size: 2 + Transport Hint: raw + Unreliable: false + Value: false - Angle Tolerance: 0.10000000149011612 Class: rviz/Odometry Covariance: @@ -180,6 +192,34 @@ Visualization Manager: Use Fixed Frame: true Use rainbow: true Value: false + - Alpha: 1 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 10 + Min Value: -10 + Value: true + Axis: Z + Channel Name: intensity + Class: rviz/PointCloud2 + Color: 255; 255; 255 + Color Transformer: RGB8 + Decay Time: 0 + Enabled: false + Invert Rainbow: false + Max Color: 255; 255; 255 + Min Color: 0; 0; 0 + Name: dense_depth_cloud + Position Transformer: XYZ + Queue Size: 10 + Selectable: true + Size (Pixels): 3 + Size (m): 0.009999999776482582 + Style: Flat Squares + Topic: /odin1/depth_img_competetion_cloud + Unreliable: false + Use Fixed Frame: true + Use rainbow: true + Value: false Enabled: true Global Options: Background Color: 48; 48; 48 @@ -231,12 +271,12 @@ Visualization Manager: Window Geometry: Displays: collapsed: false - Height: 1029 + Height: 1672 Hide Left Dock: false Hide Right Dock: false Image: collapsed: false - QMainWindow State: 000000ff00000000fd00000004000000000000015600000367fc0200000009fb0000001200530065006c0065006300740069006f006e00000001e10000009b0000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000a3fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000003d00000274000000c900fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261fb0000000a0049006d00610067006501000002b7000000ed0000001600ffffff000000010000010f00000367fc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073010000003d00000367000000a400fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e10000019700000003000007800000003efc0100000002fb0000000800540069006d00650100000000000007800000033700fffffffb0000000800540069006d006501000000000000045000000000000000000000050f0000036700000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 + QMainWindow State: 000000ff00000000fd0000000400000000000002d100000582fc020000000afb0000001200530065006c0065006300740069006f006e00000001e10000009b000000b000fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000b0fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000006e000003f70000018200fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261fb0000000a0049006d00610067006501000004710000017f0000002600fffffffb0000002200640065006e00730065005f00640065007000740068005f0069006d006100670065000000047d000001730000002600ffffff000000010000015f00000582fc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073010000006e000005820000013200fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e1000001970000000300000ab00000005efc0100000002fb0000000800540069006d0065010000000000000ab0000006dc00fffffffb0000000800540069006d00650100000000000004500000000000000000000006680000058200000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 Selection: collapsed: false Time: @@ -245,6 +285,8 @@ Window Geometry: collapsed: false Views: collapsed: false - Width: 1920 - X: 0 - Y: 27 + Width: 2736 + X: 144 + Y: 54 + dense_depth_image: + collapsed: false diff --git a/config/odin_ros2.rviz b/config/odin_ros2.rviz index c7f2e27..6d0c3c1 100644 --- a/config/odin_ros2.rviz +++ b/config/odin_ros2.rviz @@ -8,7 +8,7 @@ Panels: - /Status1 - /Image1/Topic1 Splitter Ratio: 0.5 - Tree Height: 472 + Tree Height: 548 - Class: rviz_common/Selection Name: Selection - Class: rviz_common/Tool Properties @@ -57,6 +57,20 @@ Visualization Manager: Reliability Policy: Reliable Value: /odin1/image Value: true + - Class: rviz_default_plugins/Image + Enabled: false + Max Value: 1 + Median window: 5 + Min Value: 0 + Name: dense_depth_image + Normalize Range: true + Topic: + Depth: 5 + Durability Policy: Volatile + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/depth_img_competetion + Value: false - Angle Tolerance: 0.10000000149011612 Class: rviz_default_plugins/Odometry Covariance: @@ -91,6 +105,7 @@ Visualization Manager: Topic: Depth: 5 Durability Policy: Volatile + Filter size: 10 History Policy: Keep Last Reliability Policy: Reliable Value: /odin1/odometry @@ -110,7 +125,7 @@ Visualization Manager: Enabled: false Invert Rainbow: false Max Color: 255; 255; 255 - Max Intensity: 49 + Max Intensity: 239 Min Color: 0; 0; 0 Min Intensity: 0 Name: raw @@ -122,6 +137,7 @@ Visualization Manager: Topic: Depth: 5 Durability Policy: Volatile + Filter size: 10 History Policy: Keep Last Reliability Policy: Reliable Value: /odin1/cloud_raw @@ -155,6 +171,7 @@ Visualization Manager: Topic: Depth: 5 Durability Policy: Volatile + Filter size: 10 History Policy: Keep Last Reliability Policy: Reliable Value: /odin1/cloud_render @@ -171,7 +188,7 @@ Visualization Manager: Channel Name: intensity Class: rviz_default_plugins/PointCloud2 Color: 255; 255; 255 - Color Transformer: "" + Color Transformer: RGB8 Decay Time: 0 Enabled: false Invert Rainbow: false @@ -180,7 +197,7 @@ Visualization Manager: Min Color: 0; 0; 0 Min Intensity: 0 Name: slam - Position Transformer: "" + Position Transformer: XYZ Selectable: true Size (Pixels): 3 Size (m): 0.009999999776482582 @@ -188,12 +205,47 @@ Visualization Manager: Topic: Depth: 5 Durability Policy: Volatile + Filter size: 10 History Policy: Keep Last Reliability Policy: Reliable Value: /odin1/cloud_slam Use Fixed Frame: true Use rainbow: true Value: false + - Alpha: 1 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 10 + Min Value: -10 + Value: true + Axis: Z + Channel Name: intensity + Class: rviz_default_plugins/PointCloud2 + Color: 255; 255; 255 + Color Transformer: RGB8 + Decay Time: 0 + Enabled: false + Invert Rainbow: false + Max Color: 255; 255; 255 + Max Intensity: 4096 + Min Color: 0; 0; 0 + Min Intensity: 0 + Name: dense_depth_cloud + Position Transformer: XYZ + Selectable: true + Size (Pixels): 3 + Size (m): 0.009999999776482582 + Style: Flat Squares + Topic: + Depth: 5 + Durability Policy: Volatile + Filter size: 10 + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/depth_img_competetion_cloud + Use Fixed Frame: true + Use rainbow: true + Value: false Enabled: true Global Options: Background Color: 48; 48; 48 @@ -209,6 +261,9 @@ Visualization Manager: - Class: rviz_default_plugins/Measure Line color: 128; 128; 0 - Class: rviz_default_plugins/SetInitialPose + Covariance x: 0.25 + Covariance y: 0.25 + Covariance yaw: 0.06853891909122467 Topic: Depth: 5 Durability Policy: Volatile @@ -237,7 +292,7 @@ Visualization Manager: Views: Current: Class: rviz_default_plugins/Orbit - Distance: 3.231567859649658 + Distance: 7.086822509765625 Enable Stereo Rendering: Stereo Eye Separation: 0.05999999865889549 Stereo Focal Distance: 1 @@ -252,10 +307,10 @@ Visualization Manager: Invert Z Axis: false Name: Current View Near Clip Distance: 0.009999999776482582 - Pitch: 0.16039875149726868 + Pitch: 0.3503986895084381 Target Frame: Value: Orbit (rviz) - Yaw: 2.625401258468628 + Yaw: 3.4554057121276855 Saved: ~ Window Geometry: Displays: @@ -265,7 +320,7 @@ Window Geometry: Hide Right Dock: false Image: collapsed: false - QMainWindow State: 000000ff00000000fd000000040000000000000242000003abfc0200000009fb0000001200530065006c0065006300740069006f006e00000001e10000009b0000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000a3fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000003d00000263000000c900fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261fb0000000a0049006d00610067006501000002a6000001420000002800ffffff000000010000010f000003abfc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073010000003d000003ab000000a400fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e10000019700000003000004420000003efc0100000002fb0000000800540069006d00650100000000000004420000000000000000fb0000000800540069006d0065010000000000000450000000000000000000000423000003ab00000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 + QMainWindow State: 000000ff00000000fd000000040000000000000242000003abfc020000000afb0000001200530065006c0065006300740069006f006e00000001e10000009b0000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000a3fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000003d000002af000000c900fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261fb0000000a0049006d00610067006501000002f2000000f60000002800fffffffb0000002200640065006e00730065005f00640065007000740068005f0069006d00610067006500000002cd0000011b0000002800ffffff000000010000010f000003abfc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073010000003d000003ab000000a400fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e10000019700000003000004420000003efc0100000002fb0000000800540069006d00650100000000000004420000000000000000fb0000000800540069006d0065010000000000000450000000000000000000000423000003ab00000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 Selection: collapsed: false Tool Properties: @@ -273,5 +328,7 @@ Window Geometry: Views: collapsed: false Width: 1920 - X: 0 + X: 70 Y: 27 + dense_depth_image: + collapsed: false diff --git a/include/data_logger.h b/include/data_logger.h new file mode 100644 index 0000000..89ff832 --- /dev/null +++ b/include/data_logger.h @@ -0,0 +1,179 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class BinaryDataLogger { +public: + struct Options { + public: + // Number of frames per batch before flushing to disk + size_t batch_size = 20; + // Base directory to place time-stamped run directory under + // If empty, will use $ODIN_DATA_DIR or default to $HOME/OdinData + std::filesystem::path base_dir; + }; + + explicit BinaryDataLogger(const Options& opts) { + namespace fs = std::filesystem; + // Determine base dir + fs::path base = opts.base_dir; + if (base.empty()) { + const char* env_dir = std::getenv("ODIN_DATA_DIR"); + if (env_dir && *env_dir) { + base = fs::path(env_dir); + } else { + const char* home = std::getenv("HOME"); + base = home && *home ? fs::path(home) / "OdinData" : fs::current_path() / "OdinData"; + } + } + // Make timestamp folder name: YYYYMMDD_HHMMSS + auto now = std::chrono::system_clock::now(); + std::time_t t = std::chrono::system_clock::to_time_t(now); + std::tm tm{}; + #ifdef _WIN32 + localtime_s(&tm, &t); + #else + localtime_r(&t, &tm); + #endif + char buf[32]; + std::strftime(buf, sizeof(buf), "%Y%m%d_%H%M%S", &tm); + root_dir_ = base / buf; + fs::create_directories(root_dir_); + fs::create_directories(root_dir_ / "image"); + // 转成 std::string + std::string timestamp(buf); + // 拼接文件名 + std::filesystem::path pcFile = root_dir_ / ("MT" + timestamp + ".olx"); + // Create placeholder files + write_text_file(root_dir_ / "image" / "info.txt", "device=OdinOne\ncreated_at=" + std::string(buf) + "\n"); + write_text_file(root_dir_ / "image" / "cam_in_ex.txt", "# camera intrinsics/extrinsics TBD\n"); + + // Init writers + pose_writer_ = std::make_unique(root_dir_ / "OdinPose.bin", opts.batch_size); + cloud_writer_ = std::make_unique(pcFile, opts.batch_size); + //cloud_writer_ = std::make_unique(root_dir_ / "OdinPointCloud.olx", opts.batch_size); + image_writer_ = std::make_unique(root_dir_ / "OdinImage.bin", opts.batch_size); + } + + ~BinaryDataLogger() { + // Ensure all writers flush on destruction + if (pose_writer_) pose_writer_->shutdown(); + if (cloud_writer_) cloud_writer_->shutdown(); + if (image_writer_) image_writer_->shutdown(); + } + + const std::filesystem::path& root_dir() const { return root_dir_; } + + // Enqueue ready-to-write frame blobs (already formatted as per spec) + void enqueuePoseFrame(std::vector&& blob) { + if (pose_writer_) pose_writer_->enqueue(std::move(blob)); + } + void enqueuePointCloudFrame(std::vector&& blob) { + if (cloud_writer_) cloud_writer_->enqueue(std::move(blob)); + } + void enqueueImageFrame(std::vector&& blob) { + if (image_writer_) image_writer_->enqueue(std::move(blob)); + } + +private: + struct Writer { + explicit Writer(const std::filesystem::path& filepath, size_t batch) + : file_path(filepath), batch_size(batch), stop(false) { + worker = std::thread([this]() { this->run(); }); + } + ~Writer() { + shutdown(); + } + void enqueue(std::vector&& frame) { + { + std::lock_guard lk(mtx); + pending.emplace_back(std::move(frame)); + if (pending.size() >= batch_size) { + swap_pending_unlocked(); + } + } + cv.notify_one(); + } + void shutdown() { + { + std::lock_guard lk(mtx); + if (stop) return; + // Move leftovers to write buffer + if (!pending.empty()) { + swap_pending_unlocked(); + } + stop = true; + } + cv.notify_one(); + if (worker.joinable()) worker.join(); + } + private: + void swap_pending_unlocked() { + if (!pending.empty()) { + write_queue.emplace_back(std::move(pending)); + pending.clear(); + } + } + void run() { + std::ofstream out(file_path, std::ios::binary | std::ios::app); + if (!out.is_open()) { + // If file can't be opened, silently drop (or could add logging hook) + return; + } + for (;;) { + std::vector> batch; + { + std::unique_lock lk(mtx); + cv.wait(lk, [&]{ return stop || !write_queue.empty(); }); + if (!write_queue.empty()) { + batch = std::move(write_queue.front()); + write_queue.pop_front(); + } else if (stop) { + break; + } + } + if (!batch.empty()) { + for (auto& frame : batch) { + if (!frame.empty()) { + out.write(reinterpret_cast(frame.data()), static_cast(frame.size())); + } + } + out.flush(); + } + } + } + std::filesystem::path file_path; + size_t batch_size; + std::mutex mtx; + std::condition_variable cv; + std::vector> pending; // accumulate frames + std::deque>> write_queue; // queued batches + std::thread worker; + bool stop; + }; + + static void write_text_file(const std::filesystem::path& p, const std::string& content) { + std::ofstream f(p, std::ios::out | std::ios::trunc); + if (f.is_open()) { + f << content; + } + } + + std::filesystem::path root_dir_; + std::unique_ptr pose_writer_; + std::unique_ptr cloud_writer_; + std::unique_ptr image_writer_; +}; diff --git a/include/depth_image_ros2_node.hpp b/include/depth_image_ros2_node.hpp new file mode 100644 index 0000000..26d9a7f --- /dev/null +++ b/include/depth_image_ros2_node.hpp @@ -0,0 +1,81 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include + +#include "pointcloud_depth_converter.hpp" + +#include +#include + +class DepthImageRos2Node : public rclcpp::Node +{ +public: + explicit DepthImageRos2Node(const rclcpp::NodeOptions & options = rclcpp::NodeOptions()); + + void initialize(); + +private: + std::string cloud_raw_topic_; + std::string color_compressed_topic_; + std::string depth_image_topic_; + std::string depth_cloud_topic_; + + message_filters::Subscriber cloud_sub_; + message_filters::Subscriber color_compressed_sub_; + + typedef message_filters::sync_policies::ApproximateTime< + sensor_msgs::msg::PointCloud2, + sensor_msgs::msg::CompressedImage> MySyncPolicy; + typedef message_filters::Synchronizer Sync; + std::shared_ptr sync_; + + std::shared_ptr it_; + image_transport::Publisher depth_image_pub_; + rclcpp::Publisher::SharedPtr depth_cloud_pub_; + + std::unique_ptr depth_converter_; + + + PointCloudToDepthConverter::CameraParams loadCameraParams(); + + void syncCallback(const sensor_msgs::msg::PointCloud2::ConstSharedPtr cloud_msg, + const sensor_msgs::msg::CompressedImage::ConstSharedPtr image_msg); + + + void publishDepthImage(const cv::Mat &img, + const std_msgs::msg::Header &header, + const std::string &encoding = "32FC1"); + + void publishDepthCloud(const pcl::PointCloud &colored_cloud, + const std_msgs::msg::Header &header); +}; diff --git a/include/depth_image_ros_node.hpp b/include/depth_image_ros_node.hpp new file mode 100644 index 0000000..84f0105 --- /dev/null +++ b/include/depth_image_ros_node.hpp @@ -0,0 +1,81 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include + +#include "pointcloud_depth_converter.hpp" + +#include +#include + + +class DepthImageRosNode +{ +public: + DepthImageRosNode(ros::NodeHandle &nh, ros::NodeHandle &pnh); + +private: + ros::NodeHandle nh_, pnh_; + image_transport::ImageTransport it_; + + + std::string cloud_raw_topic_; + std::string color_compressed_topic_; + std::string depth_image_topic_; + std::string depth_cloud_topic_; + + message_filters::Subscriber cloud_sub_; + message_filters::Subscriber color_compressed_sub_; + + typedef message_filters::sync_policies::ApproximateTime MySyncPolicy; + typedef message_filters::Synchronizer Sync; + std::shared_ptr sync_; + + image_transport::Publisher depth_image_pub_; + ros::Publisher depth_cloud_pub_; + + std::unique_ptr depth_converter_; + + PointCloudToDepthConverter::CameraParams loadCameraParams(); + + + void syncCallback(const sensor_msgs::PointCloud2ConstPtr &cloud_msg, + const sensor_msgs::CompressedImageConstPtr &image_msg); + + + void publishDepthImage(const cv::Mat &img, + const std_msgs::Header &header, + const std::string &encoding = "32FC1"); + + + void publishDepthCloud(const pcl::PointCloud &colored_cloud, + const std_msgs::Header &header); +}; diff --git a/include/host_sdk_sample.h b/include/host_sdk_sample.h index 9452497..11675dd 100644 --- a/include/host_sdk_sample.h +++ b/include/host_sdk_sample.h @@ -24,10 +24,14 @@ limitations under the License. #include #include #include +#include #include #include #include #include +#include +#include +#include "data_logger.h" #include "lidar_api.h" #include "lidar_api_type.h" #include "rawCloudRender.h" @@ -53,17 +57,15 @@ extern int g_sendcloudrender; #include "rclcpp/rclcpp.hpp" #include "std_msgs/msg/string.hpp" + #include #include "sensor_msgs/msg/image.hpp" #include "sensor_msgs/msg/imu.hpp" #include "sensor_msgs/msg/point_cloud2.hpp" #include "sensor_msgs/point_cloud2_iterator.hpp" - #include + #include + #include #include - #include #include - #include - using ImageConstPtr = sensor_msgs::msg::Image::ConstSharedPtr; - using PointCloud2ConstPtr = sensor_msgs::msg::PointCloud2::ConstSharedPtr; namespace ros { using namespace rclcpp; using namespace std_msgs::msg; @@ -82,13 +84,13 @@ extern int g_sendcloudrender; #include #include #include + #include #include #include #include + #include #include #include - using ImageConstPtr = sensor_msgs::ImageConstPtr; - using PointCloud2ConstPtr = sensor_msgs::PointCloud2ConstPtr; namespace ros { using namespace ::ros; using namespace sensor_msgs; @@ -177,16 +179,36 @@ public: MultiSensorPublisher(rclcpp::Node::SharedPtr node) : node_(node) { initialize_publishers(); + // initialize_data_logger(); } #else MultiSensorPublisher(ros::NodeHandle& nh) { initialize_publishers(nh); + // initialize_data_logger(); } #endif + std::filesystem::path get_root_dir() const { return root_dir_; } + void set_log_level(int level) { g_log_level = level; } + // Optional external logger setter + void set_data_logger(std::shared_ptr logger) { + data_logger_ = std::move(logger); + } + + int get_pose_index() { + return pose_index_.load(); + } + + int get_cloud_index() { + return cloud_index_.load(); + } + + int get_image_index() { + return image_index_.load(); + } rawCloudRender render_; void publishImu(icm_6aixs_data_t *stream) { @@ -636,6 +658,8 @@ void process_pair(const ImageConstPtr &rgb_msg, const PointCloud2ConstPtr &pcd_m #ifdef ROS2 auto header = std::make_shared(); header->stamp = ns_to_ros_time(image.timestamp + 719060); // Offset compensation + + //RCLCPP_INFO(rclcpp::get_logger("device_cb"), "image rgb %ld",image.timestamp + 719060); header->frame_id = "camera_rgb_frame"; auto cv_image = std::make_shared(*header, "bgr8", bgr); @@ -664,7 +688,25 @@ void process_pair(const ImageConstPtr &rgb_msg, const PointCloud2ConstPtr &pcd_m compression_params.push_back(80); // Compress image - cv::imencode(".jpg", bgr, compressed_msg->data, compression_params); + cv::imencode(".JPEG", bgr, compressed_msg->data, compression_params); + + // Enqueue binary logging for image + if (data_logger_) { + const uint32_t idx_now = image_index_.fetch_add(1, std::memory_order_relaxed); + const double ts_sec = static_cast(image.timestamp + 719060) / 1e9; + const uint32_t jpeg_size = static_cast(compressed_msg->data.size()); + std::vector blob; + blob.reserve(sizeof(uint32_t) + sizeof(double) + sizeof(uint32_t) + jpeg_size); + auto append_pod = [&](const auto& v) { + const uint8_t* p = reinterpret_cast(&v); + blob.insert(blob.end(), p, p + sizeof(v)); + }; + append_pod(idx_now); + append_pod(ts_sec); + append_pod(jpeg_size); + blob.insert(blob.end(), compressed_msg->data.begin(), compressed_msg->data.end()); + data_logger_->enqueueImageFrame(std::move(blob)); + } compressed_rgb_pub_->publish(*compressed_msg); @@ -702,7 +744,25 @@ void process_pair(const ImageConstPtr &rgb_msg, const PointCloud2ConstPtr &pcd_m // Compress image cv::imencode(".jpg", bgr, compressed_msg->data, compression_params); - + + // Enqueue binary logging for image + if (data_logger_) { + const uint32_t idx_now = image_index_.fetch_add(1, std::memory_order_relaxed); + // Convert ROS1 header.stamp to seconds + const double ts_sec = static_cast(header.stamp.sec) + static_cast(header.stamp.nsec) / 1e9; + const uint32_t jpeg_size = static_cast(compressed_msg->data.size()); + std::vector blob; + blob.reserve(sizeof(uint32_t) + sizeof(double) + sizeof(uint32_t) + jpeg_size); + auto append_pod = [&](const auto& v) { + const uint8_t* p = reinterpret_cast(&v); + blob.insert(blob.end(), p, p + sizeof(v)); + }; + append_pod(idx_now); + append_pod(ts_sec); + append_pod(jpeg_size); + blob.insert(blob.end(), compressed_msg->data.begin(), compressed_msg->data.end()); + data_logger_->enqueueImageFrame(std::move(blob)); + } compressed_rgb_pub_.publish(compressed_msg); #endif @@ -737,6 +797,24 @@ void process_pair(const ImageConstPtr &rgb_msg, const PointCloud2ConstPtr &pcd_m rgb_image_queue_.push_back(cv_image.toImageMsg()); } + // Enqueue binary logging for image + if (data_logger_) { + const uint32_t idx_now = image_index_.fetch_add(1, std::memory_order_relaxed); + const double ts_sec = static_cast(stream->imageList[0].timestamp + 719060) / 1e9; + const uint32_t jpeg_size = static_cast(jpeg_data.size()); + std::vector blob; + blob.reserve(sizeof(uint32_t) + sizeof(double) + sizeof(uint32_t) + jpeg_size); + auto append_pod = [&](const auto& v) { + const uint8_t* p = reinterpret_cast(&v); + blob.insert(blob.end(), p, p + sizeof(v)); + }; + append_pod(idx_now); + append_pod(ts_sec); + append_pod(jpeg_size); + blob.insert(blob.end(), jpeg_data.begin(), jpeg_data.end()); + data_logger_->enqueueImageFrame(std::move(blob)); + } + #ifdef ROS2 { rgb_pub_->publish(*cv_image.toImageMsg()); @@ -775,6 +853,9 @@ void process_pair(const ImageConstPtr &rgb_msg, const PointCloud2ConstPtr &pcd_m sensor_msgs::msg::PointCloud2 msg; msg.header.frame_id = "map"; msg.header.stamp = ns_to_ros_time(stream->imageList[0].timestamp); + + //RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Point cloudrgba %ld",stream->imageList[0].timestamp); + size_t pt_size = sizeof(int32_t) * 3 + sizeof(int32_t) * 4; uint32_t points = stream->imageList[idx].length / pt_size; @@ -830,15 +911,15 @@ void process_pair(const ImageConstPtr &rgb_msg, const PointCloud2ConstPtr &pcd_m for(uint32_t i = 0; i < points; i++) { int32_t* ptr = xyz_data + 7*i; - #ifdef ROS2 +#ifdef ROS2 *iter_x = static_cast(ptr[0]) / 10000.0f; ++iter_x; *iter_y = static_cast(ptr[1]) / 10000.0f; ++iter_y; *iter_z = static_cast(ptr[2]) / 10000.0f; ++iter_z; - #else +#else *iter_x = (1.0 * ptr[0]) / 1e4; ++iter_x; *iter_y = (1.0 * ptr[1]) / 1e4; ++iter_y; *iter_z = (1.0 * ptr[2]) / 1e4; ++iter_z; - #endif +#endif uint8_t r = ptr[3] & 0xff; uint8_t g = ptr[4] & 0xff; @@ -853,25 +934,62 @@ void process_pair(const ImageConstPtr &rgb_msg, const PointCloud2ConstPtr &pcd_m *iter_rgb = rgb_float; ++iter_rgb; } + + // Enqueue binary logging for point cloud (XYZRGB per point) + if (data_logger_ && points > 0) { + const double ts_sec = static_cast(stream->imageList[0].timestamp) / 1e9; + const uint32_t idx_now = cloud_index_.fetch_add(1, std::memory_order_relaxed); + // Compute total blob size: header + per-point payload + const size_t header_size = sizeof(uint32_t) + sizeof(double) + sizeof(uint32_t); + const size_t point_size = sizeof(float) * 3 + sizeof(uint8_t) * 3; + std::vector blob; + blob.reserve(header_size + static_cast(points) * point_size); + auto append_pod = [&](const auto& v) { + const uint8_t* p = reinterpret_cast(&v); + blob.insert(blob.end(), p, p + sizeof(v)); + }; + append_pod(idx_now); + append_pod(ts_sec); + append_pod(points); + + for (uint32_t i = 0; i < points; ++i) { + int32_t* ptr = xyz_data + 7 * i; + float fx = static_cast(ptr[0]) / 10000.0f; + float fy = static_cast(ptr[1]) / 10000.0f; + float fz = static_cast(ptr[2]) / 10000.0f; + uint8_t r = static_cast(ptr[3] & 0xff); + uint8_t g = static_cast(ptr[4] & 0xff); + uint8_t b = static_cast(ptr[5] & 0xff); + append_pod(fx); + append_pod(fy); + append_pod(fz); + blob.push_back(r); + blob.push_back(g); + blob.push_back(b); + } + data_logger_->enqueuePointCloudFrame(std::move(blob)); + } - #ifdef ROS2 +#ifdef ROS2 xyzrgbacloud_pub_->publish(std::move(msg)); - #else +#else xyzrgbacloud_pub_.publish(msg); - #endif +#endif } void publishOdometry(capture_Image_List_t* stream) { - #ifdef ROS2 +#ifdef ROS2 auto msg = nav_msgs::msg::Odometry(); - #else +#else ros::Odometry msg; - #endif +#endif msg.header.frame_id = "map"; msg.child_frame_id = "base_link"; + //RCLCPP_INFO(rclcpp::get_logger("device_cb"), "odom %ld",odom_data->timestamp_ns); + uint32_t data_len = stream->imageList[0].length; if (data_len == sizeof(ros_odom_convert_complete_t)) { @@ -887,6 +1005,30 @@ void process_pair(const ImageConstPtr &rgb_msg, const PointCloud2ConstPtr &pcd_m msg.pose.pose.orientation.z = static_cast(odom_data->orient[2]) / 1e6; msg.pose.pose.orientation.w = static_cast(odom_data->orient[3]) / 1e6; + // Enqueue binary logging for pose + if (data_logger_) { + const uint32_t idx_now = pose_index_.fetch_add(1, std::memory_order_relaxed); + const double ts_sec = static_cast(odom_data->timestamp_ns) / 1e9; + float pose_arr[7]; + pose_arr[0] = static_cast(msg.pose.pose.position.x); + pose_arr[1] = static_cast(msg.pose.pose.position.y); + pose_arr[2] = static_cast(msg.pose.pose.position.z); + pose_arr[3] = static_cast(msg.pose.pose.orientation.x); + pose_arr[4] = static_cast(msg.pose.pose.orientation.y); + pose_arr[5] = static_cast(msg.pose.pose.orientation.z); + pose_arr[6] = static_cast(msg.pose.pose.orientation.w); + std::vector blob; + blob.reserve(sizeof(uint32_t) + sizeof(double) + sizeof(float) * 7); + auto append_pod = [&](const auto& v) { + const uint8_t* p = reinterpret_cast(&v); + blob.insert(blob.end(), p, p + sizeof(v)); + }; + append_pod(idx_now); + append_pod(ts_sec); + for (int i = 0; i < 7; ++i) append_pod(pose_arr[i]); + data_logger_->enqueuePoseFrame(std::move(blob)); + } + msg.twist.twist.linear.x = static_cast(odom_data->linear_velocity[0]) / 1e6; msg.twist.twist.linear.y = static_cast(odom_data->linear_velocity[1]) / 1e6; msg.twist.twist.linear.z = static_cast(odom_data->linear_velocity[2]) / 1e6; @@ -919,11 +1061,31 @@ void process_pair(const ImageConstPtr &rgb_msg, const PointCloud2ConstPtr &pcd_m msg.pose.pose.orientation.w = static_cast(odom_data->orient[3]) / 1e6; } - #ifdef ROS2 +#ifdef ROS2 odom_publisher_->publish(std::move(msg)); - #else +#else odom_publisher_.publish(msg); - #endif +#endif + } + + void initialize_data_logger(std::string data_dir = "") { + + try { + BinaryDataLogger::Options opts; + opts.batch_size = 100; + opts.base_dir = data_dir; + data_logger_ = std::make_shared(opts); + root_dir_ = data_logger_->root_dir(); + #ifdef ROS2 + RCLCPP_INFO(node_->get_logger(), "Data logger initialized at %s", root_dir_.c_str()); + #endif + } catch (...) { + // Swallow logger initialization failures to avoid affecting runtime + #ifdef ROS2 + RCLCPP_INFO(node_->get_logger(), "Failed to initialize data logger"); + #endif + data_logger_.reset(); + } } private: @@ -936,6 +1098,13 @@ private: std::deque pcd_queue_; const size_t max_pcd_queue_size_ = 10; // Maximum cache frames + // Binary logger and frame indices + std::shared_ptr data_logger_; + std::atomic pose_index_{0}; + std::atomic cloud_index_{0}; + std::atomic image_index_{0}; + + std::filesystem::path root_dir_; // Updated helper functions ImageConstPtr getLatestRgbImage() { diff --git a/include/pointcloud_depth_converter.hpp b/include/pointcloud_depth_converter.hpp new file mode 100644 index 0000000..94c12a5 --- /dev/null +++ b/include/pointcloud_depth_converter.hpp @@ -0,0 +1,94 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include + + +class PointCloudToDepthConverter +{ +public: + + struct CameraParams + { + int image_width; + int image_height; + double A11, A12, A22; + double u0, v0; + double k2, k3, k4, k5, k6, k7; + double scale; + int point_sampling_rate; + Eigen::Matrix4d Tcl; + }; + + + struct ProcessResult + { + cv::Mat depth_image; + pcl::PointCloud colored_cloud; + bool success; + std::string error_message; + }; + + + explicit PointCloudToDepthConverter(const CameraParams ¶ms); + + + ProcessResult processCloudAndImage(const pcl::PointCloud &cloud, + const cv::Mat &image); + + cv::Mat customResize(const cv::Mat& src, const cv::Size& size); + const CameraParams &getCameraParams() const { return params_; } + + + void updateCameraParams(const CameraParams ¶ms); + +private: + CameraParams params_; + + Eigen::Matrix3d K_; + Eigen::Matrix3d Kl_; + Eigen::Matrix4d K_4x4_; + Eigen::Matrix4d Kcl_; + + cv::Mat map_x_, map_y_; + cv::Mat inv_map_x_, inv_map_y_; + cv::Mat depth_undistorted_; + + int scaled_width_, scaled_height_; + + + void initializeInternalParams(); + + + void createDistortionMaps(); + + cv::Mat projectCloudToDepth(const pcl::PointCloud &cloud_in_cam); + + + cv::Mat postProcessDepthImage(const cv::Mat &depth_img); + + + pcl::PointCloud generateColoredCloud(const cv::Mat &depth_img, + const cv::Mat &color_img); + + + std::pair validateInputs(const pcl::PointCloud &cloud, + const cv::Mat &image); +}; \ No newline at end of file diff --git a/launch_ROS1/odin1_ros1.launch b/launch_ROS1/odin1_ros1.launch index 3567825..da14c97 100644 --- a/launch_ROS1/odin1_ros1.launch +++ b/launch_ROS1/odin1_ros1.launch @@ -16,6 +16,11 @@ + + + + + diff --git a/launch_ROS2/odin1_ros2.launch.py b/launch_ROS2/odin1_ros2.launch.py index c210624..34224f0 100644 --- a/launch_ROS2/odin1_ros2.launch.py +++ b/launch_ROS2/odin1_ros2.launch.py @@ -1,6 +1,7 @@ # USAGE: ros2 launch odin_ros_driver odin1_ros2.launch.py import os +import yaml from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import DeclareLaunchArgument @@ -36,7 +37,19 @@ def generate_launch_description(): 'config_file': LaunchConfiguration('config_file') }] ) - + + pcd2depth_config_path = os.path.join(package_dir, 'config', 'control_command.yaml') + with open(pcd2depth_config_path, 'r') as f: + pcd2depth_params = yaml.safe_load(f) + pcd2depth_calib_path = os.path.join(package_dir, 'config', 'calib.yaml') + pcd2depth_params['calib_file_path'] = pcd2depth_calib_path + pcd2depth_node = Node( + package='odin_ros_driver', + executable='pcd2depth_ros2_node', + name='pcd2depth_ros2_node', + output='screen', + parameters=[pcd2depth_params] + ) # Create RViz2 node - loads specified configuration file rviz_node = Node( package='rviz2', @@ -51,6 +64,7 @@ def generate_launch_description(): ld.add_action(config_file_arg) ld.add_action(rviz_config_arg) # Add RViz configuration argument ld.add_action(host_sdk_node) + ld.add_action(pcd2depth_node) ld.add_action(rviz_node) # Add RViz node - return ld \ No newline at end of file + return ld diff --git a/lib/liblydHostApi_arm.a b/lib/liblydHostApi_arm.a index aa9afa8..ed1b302 100644 Binary files a/lib/liblydHostApi_arm.a and b/lib/liblydHostApi_arm.a differ diff --git a/src/depth_image_ros2_node.cpp b/src/depth_image_ros2_node.cpp new file mode 100644 index 0000000..6e7b138 --- /dev/null +++ b/src/depth_image_ros2_node.cpp @@ -0,0 +1,153 @@ +#include "depth_image_ros2_node.hpp" +#include + +DepthImageRos2Node::DepthImageRos2Node(const rclcpp::NodeOptions & options) + : Node("depth_image_ros2_node", options) +{ + PointCloudToDepthConverter::CameraParams camera_params = loadCameraParams(); + + depth_converter_ = std::make_unique(camera_params); + + cloud_raw_topic_ = this->declare_parameter("cloud_raw_topic", "/odin1/cloud_raw"); + color_compressed_topic_ = this->declare_parameter("color_compressed_topic", "/odin1/image/compressed"); + depth_image_topic_ = this->declare_parameter("depth_image_topic", "/odin1/depth_img_competetion"); + depth_cloud_topic_ = this->declare_parameter("depth_cloud_topic", "/odin1/depth_img_competetion_cloud"); + + RCLCPP_INFO_STREAM(this->get_logger(), + "\n cloud_raw_topic: " << cloud_raw_topic_ + << "\n color_compressed_topic: " << color_compressed_topic_ + << "\n depth_image_topic: " << depth_image_topic_ + << "\n depth_cloud_topic: " << depth_cloud_topic_); +} + +void DepthImageRos2Node::initialize() +{ + cloud_sub_.subscribe(this, cloud_raw_topic_); + color_compressed_sub_.subscribe(this, color_compressed_topic_); + + sync_ = std::make_shared(MySyncPolicy(10), cloud_sub_, color_compressed_sub_); + sync_->registerCallback(std::bind(&DepthImageRos2Node::syncCallback, this, + std::placeholders::_1, std::placeholders::_2)); + + it_ = std::make_shared(shared_from_this()); + depth_image_pub_ = it_->advertise(depth_image_topic_, 1); + depth_cloud_pub_ = this->create_publisher(depth_cloud_topic_, 1); + + RCLCPP_INFO(this->get_logger(), "DepthImageRos2Node initialized successfully"); +} + +PointCloudToDepthConverter::CameraParams DepthImageRos2Node::loadCameraParams() +{ + PointCloudToDepthConverter::CameraParams params; + + params.image_width = this->declare_parameter("cam_0.image_width", 1600); + params.image_height = this->declare_parameter("cam_0.image_height", 1296); + params.A11 = this->declare_parameter("cam_0.A11", 0.0); + params.A12 = this->declare_parameter("cam_0.A12", 0.0); + params.A22 = this->declare_parameter("cam_0.A22", 0.0); + params.u0 = this->declare_parameter("cam_0.u0", 0.0); + params.v0 = this->declare_parameter("cam_0.v0", 0.0); + + params.k2 = this->declare_parameter("cam_0.k2", 0.0); + params.k3 = this->declare_parameter("cam_0.k3", 0.0); + params.k4 = this->declare_parameter("cam_0.k4", 0.0); + params.k5 = this->declare_parameter("cam_0.k5", 0.0); + params.k6 = this->declare_parameter("cam_0.k6", 0.0); + params.k7 = this->declare_parameter("cam_0.k7", 0.0); + + params.scale = this->declare_parameter("scale", 7.0); + params.point_sampling_rate = this->declare_parameter("point_sampling_rate", 5); + + std::vector Tcl_vec_param = this->declare_parameter>("Tcl_0", std::vector(16, 0.0)); + if (Tcl_vec_param.size() == 16) + { + for (int i = 0; i < 4; ++i) + { + for (int j = 0; j < 4; ++j) + { + params.Tcl(i, j) = Tcl_vec_param[i * 4 + j]; + } + } + } + else + { + RCLCPP_ERROR(this->get_logger(), "Tcl_0 param missing or invalid, colored reproject cloud disabled."); + rclcpp::shutdown(); + } + + if (params.A11 < 1e-6 || params.A22 < 1e-6 || params.u0 < 1e-6 || params.v0 < 1e-6) + { + RCLCPP_ERROR(this->get_logger(), "Invalid camera intrinsics A11 or A22"); + rclcpp::shutdown(); + } + + RCLCPP_INFO(this->get_logger(), "Camera intrinsics:"); + RCLCPP_INFO(this->get_logger(), "Image size: %dx%d", params.image_width, params.image_height); + RCLCPP_INFO(this->get_logger(), "Intrinsics: A11=%f A12=%f A22=%f u0=%f v0=%f", + params.A11, params.A12, params.A22, params.u0, params.v0); + RCLCPP_INFO(this->get_logger(), "Distortions: k2=%f k3=%f k4=%f k5=%f k6=%f k7=%f", + params.k2, params.k3, params.k4, params.k5, params.k6, params.k7); + RCLCPP_INFO(this->get_logger(), "Scale: %f, Point sampling rate: %d", params.scale, params.point_sampling_rate); + RCLCPP_INFO_STREAM(this->get_logger(), "Extrinsics (Tcl):\n" << params.Tcl); + + return params; +} + +void DepthImageRos2Node::syncCallback(const sensor_msgs::msg::PointCloud2::ConstSharedPtr cloud_msg, + const sensor_msgs::msg::CompressedImage::ConstSharedPtr image_msg) +{ + pcl::PointCloud cloud; + pcl::fromROSMsg(*cloud_msg, cloud); + if (cloud.empty()) + { + RCLCPP_WARN(this->get_logger(), "Empty point cloud received"); + return; + } + + cv::Mat img_raw; + try + { + img_raw = cv::imdecode(cv::Mat(image_msg->data), cv::IMREAD_COLOR); + if (img_raw.empty()) + { + RCLCPP_WARN(this->get_logger(), "Failed to decode compressed image"); + return; + } + } + catch (const cv_bridge::Exception &e) + { + RCLCPP_ERROR(this->get_logger(), "cv_bridge: %s", e.what()); + return; + } + + auto result = depth_converter_->processCloudAndImage(cloud, img_raw); + + if (!result.success) + { + RCLCPP_WARN(this->get_logger(), "Data processing failed: %s", result.error_message.c_str()); + return; + } + + publishDepthImage(result.depth_image, cloud_msg->header); + publishDepthCloud(result.colored_cloud, cloud_msg->header); +} + +void DepthImageRos2Node::publishDepthImage(const cv::Mat &img, + const std_msgs::msg::Header &header, + const std::string &encoding) +{ + sensor_msgs::msg::Image::SharedPtr depth_msg = cv_bridge::CvImage(header, encoding, img).toImageMsg(); + depth_image_pub_.publish(*depth_msg); +} + +void DepthImageRos2Node::publishDepthCloud(const pcl::PointCloud &colored_cloud, + const std_msgs::msg::Header &header) +{ + if (!colored_cloud.points.empty()) + { + sensor_msgs::msg::PointCloud2 cloud_msg; + pcl::toROSMsg(colored_cloud, cloud_msg); + cloud_msg.header = header; + depth_cloud_pub_->publish(cloud_msg); + } +} diff --git a/src/depth_image_ros_node.cpp b/src/depth_image_ros_node.cpp new file mode 100644 index 0000000..99d55e2 --- /dev/null +++ b/src/depth_image_ros_node.cpp @@ -0,0 +1,147 @@ +#include "depth_image_ros_node.hpp" +#include + +DepthImageRosNode::DepthImageRosNode(ros::NodeHandle &nh, ros::NodeHandle &pnh) + : nh_(nh), pnh_(pnh), it_(nh_) +{ + PointCloudToDepthConverter::CameraParams camera_params = loadCameraParams(); + + depth_converter_ = std::make_unique(camera_params); + pnh_.param("cloud_raw_topic", cloud_raw_topic_, std::string("/odin1/cloud_raw")); + pnh_.param("color_compressed_topic_", color_compressed_topic_, std::string("/odin1/image/compressed")); + pnh_.param("depth_image_topic", depth_image_topic_, std::string("/odin1/depth_img_competetion")); + pnh_.param("depth_cloud_topic", depth_cloud_topic_, std::string("/odin1/depth_img_competetion_cloud")); + + ROS_INFO_STREAM("\n cloud_raw_topic: " << cloud_raw_topic_ + << "\n color_compressed_topic: " << color_compressed_topic_ + << "\n depth_image_topic: " << depth_image_topic_ + << "\n depth_cloud_topic: " << depth_cloud_topic_); + + cloud_sub_.subscribe(nh_, cloud_raw_topic_, 1); + color_compressed_sub_.subscribe(nh_, color_compressed_topic_, 1); + + sync_ = std::make_shared(MySyncPolicy(10), cloud_sub_, color_compressed_sub_); + sync_->registerCallback(boost::bind(&DepthImageRosNode::syncCallback, this, _1, _2)); + + depth_image_pub_ = it_.advertise(depth_image_topic_, 1); + depth_cloud_pub_ = nh_.advertise(depth_cloud_topic_, 1); + + ROS_INFO("DepthImageRosNode initialized successfully"); +} + +PointCloudToDepthConverter::CameraParams DepthImageRosNode::loadCameraParams() +{ + PointCloudToDepthConverter::CameraParams params; + + pnh_.param("cam_0/image_width", params.image_width, 1600); + pnh_.param("cam_0/image_height", params.image_height, 1296); + pnh_.param("cam_0/A11", params.A11, 0.0); + pnh_.param("cam_0/A12", params.A12, 0.0); + pnh_.param("cam_0/A22", params.A22, 0.0); + pnh_.param("cam_0/u0", params.u0, 0.0); + pnh_.param("cam_0/v0", params.v0, 0.0); + + pnh_.param("cam_0/k2", params.k2, 0.0); + pnh_.param("cam_0/k3", params.k3, 0.0); + pnh_.param("cam_0/k4", params.k4, 0.0); + pnh_.param("cam_0/k5", params.k5, 0.0); + pnh_.param("cam_0/k6", params.k6, 0.0); + pnh_.param("cam_0/k7", params.k7, 0.0); + + pnh_.param("scale", params.scale, 7.0); + pnh_.param("point_sampling_rate", params.point_sampling_rate, 5); + + std::vector Tcl_vec_param; + if (pnh_.getParam("Tcl_0", Tcl_vec_param) && Tcl_vec_param.size() == 16) + { + for (int i = 0; i < 4; ++i) + { + for (int j = 0; j < 4; ++j) + { + params.Tcl(i, j) = Tcl_vec_param[i * 4 + j]; + } + } + } + else + { + ROS_ERROR("Tcl_0 param missing or invalid, colored reproject cloud disabled."); + ros::shutdown(); + } + + if (params.A11 < 1e-6 || params.A22 < 1e-6 || params.u0 < 1e-6 || params.v0 < 1e-6) + { + ROS_ERROR("Invalid camera intrinsics A11 or A22"); + ros::shutdown(); + } + + ROS_INFO("Camera intrinsics:"); + ROS_INFO("Image size: %dx%d", params.image_width, params.image_height); + ROS_INFO("Intrinsics: A11=%f A12=%f A22=%f u0=%f v0=%f", + params.A11, params.A12, params.A22, params.u0, params.v0); + ROS_INFO("Distortions: k2=%f k3=%f k4=%f k5=%f k6=%f k7=%f", + params.k2, params.k3, params.k4, params.k5, params.k6, params.k7); + ROS_INFO("Scale: %f, Point sampling rate: %d", params.scale, params.point_sampling_rate); + ROS_INFO_STREAM("Extrinsics (Tcl):\n" + << params.Tcl); + + return params; +} + +void DepthImageRosNode::syncCallback(const sensor_msgs::PointCloud2ConstPtr &cloud_msg, + const sensor_msgs::CompressedImageConstPtr &image_msg) +{ + pcl::PointCloud cloud; + pcl::fromROSMsg(*cloud_msg, cloud); + if (cloud.empty()) + { + ROS_WARN("Empty point cloud received"); + return; + } + + cv::Mat img_raw; + try + { + img_raw = cv::imdecode(cv::Mat(image_msg->data), cv::IMREAD_COLOR); + if (img_raw.empty()) + { + ROS_WARN("Failed to decode compressed image"); + return; + } + } + catch (const cv_bridge::Exception &e) + { + ROS_ERROR("cv_bridge: %s", e.what()); + return; + } + + auto result = depth_converter_->processCloudAndImage(cloud, img_raw); + + if (!result.success) + { + ROS_WARN("Data processing failed: %s", result.error_message.c_str()); + return; + } + + publishDepthImage(result.depth_image, cloud_msg->header); + publishDepthCloud(result.colored_cloud, cloud_msg->header); +} + +void DepthImageRosNode::publishDepthImage(const cv::Mat &img, + const std_msgs::Header &header, + const std::string &encoding) +{ + sensor_msgs::ImagePtr depth_msg = cv_bridge::CvImage(header, encoding, img).toImageMsg(); + depth_image_pub_.publish(depth_msg); +} + +void DepthImageRosNode::publishDepthCloud(const pcl::PointCloud &colored_cloud, + const std_msgs::Header &header) +{ + if (!colored_cloud.points.empty()) + { + sensor_msgs::PointCloud2 cloud_msg; + pcl::toROSMsg(colored_cloud, cloud_msg); + cloud_msg.header = header; + depth_cloud_pub_.publish(cloud_msg); + } +} diff --git a/src/host_sdk_sample.cpp b/src/host_sdk_sample.cpp index 1aa120f..d76217d 100644 --- a/src/host_sdk_sample.cpp +++ b/src/host_sdk_sample.cpp @@ -21,6 +21,8 @@ #include #include #include +#include +#include #ifdef ROS2 #include #include @@ -28,7 +30,7 @@ #include #include #endif -#define ros_driver_version "0.4.0" +#define ros_driver_version "0.4.1" // Global variable declarations static device_handle odinDevice = nullptr; static std::atomic deviceConnected(false); @@ -52,6 +54,7 @@ static bool g_has_rgb = false; static capture_Image_List_t g_latest_rgb; static bool g_renderer_initialized = false; static std::shared_ptr g_renderer = nullptr; +std::string calib_file_ = ""; // usb device static std::string TARGET_VENDOR = "2207"; @@ -64,6 +67,7 @@ int g_sendodom = 1; int g_sendcloudslam = 0; int g_sendcloudrender = 0; int g_sendrgb_compressed = 0; +int g_record_data = 0; class RosNodeControlImpl : public RosNodeControlInterface { public: @@ -168,6 +172,123 @@ bool isUsbDevicePresent(const std::string& vendorId, const std::string& productI } return false; } +// Convert calib.yaml to cam_in_ex.txt +static bool convert_calib_to_cam_in_ex(const std::string& calib_path, const std::filesystem::path& out_path) { + try { + if (calib_path.empty()) { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("device_cb"), "calib_file_ is empty, skip writing cam_in_ex.txt"); + #else + ROS_WARN("calib_file_ is empty, skip writing cam_in_ex.txt"); + #endif + return false; + } + + YAML::Node root = YAML::LoadFile(calib_path); + + // Read Tcl_0 matrix (16 values) + std::array Tcl{}; + YAML::Node tcl = root["Tcl_0"]; + for (size_t i = 0; i < 16; ++i) { + if (tcl && tcl.IsSequence() && i < tcl.size()) { + Tcl[i] = tcl[i].as(); + } else { + // Default last row to [0,0,0,1] if missing, others 0 + Tcl[i] = (i == 15) ? 1.0 : 0.0; + } + } + + // Read cam_0 parameters (with defaults) + YAML::Node cam0 = root["cam_0"]; + auto get_i = [&](const char* key, int def) -> int { + return (cam0 && cam0[key]) ? cam0[key].as() : def; + }; + auto get_d = [&](const char* key, double def) -> double { + return (cam0 && cam0[key]) ? cam0[key].as() : def; + }; + + int image_width = get_i("image_width", 0); + int image_height = get_i("image_height", 0); + double k2 = get_d("k2", 0.0); + double k3 = get_d("k3", 0.0); + double k4 = get_d("k4", 0.0); + double k5 = get_d("k5", 0.0); + double k6 = get_d("k6", 0.0); + double k7 = get_d("k7", 0.0); + double p1 = get_d("p1", 0.0); + double p2 = get_d("p2", 0.0); + double A11 = get_d("A11", 0.0); + double A12 = get_d("A12", 0.0); + double A22 = get_d("A22", 0.0); + double u0 = get_d("u0", 0.0); + double v0 = get_d("v0", 0.0); + + // Ensure parent directory exists + std::error_code ec; + std::filesystem::create_directories(out_path.parent_path(), ec); + + // Truncate file then write content + std::ofstream ofs(out_path, std::ios::out | std::ios::trunc); + if (!ofs.is_open()) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Failed to open cam_in_ex.txt for write: %s", out_path.string().c_str()); + #else + ROS_ERROR("Failed to open cam_in_ex.txt for write: %s", out_path.string().c_str()); + #endif + return false; + } + + auto fmt = [](double v) { + std::ostringstream ss; ss.setf(std::ios::fixed); ss << std::setprecision(6) << v; return ss.str(); + }; + + // Write Tcl_0 with line breaks every 4 elements + ofs << "Tcl_0: ["; + for (int i = 0; i < 16; ++i) { + if (i > 0) { + ofs << ", "; + if (i % 4 == 0) ofs << "\n "; + } + ofs << fmt(Tcl[i]); + } + ofs << "]\n"; + + // Write cam_0 block + ofs << "cam_0: \n"; + ofs << " image_width: " << image_width << "\n"; + ofs << " image_height: " << image_height << "\n"; + ofs << " k2: " << fmt(k2) << "\n"; + ofs << " k3: " << fmt(k3) << "\n"; + ofs << " k4: " << fmt(k4) << "\n"; + ofs << " k5: " << fmt(k5) << "\n"; + ofs << " k6: " << fmt(k6) << "\n"; + ofs << " k7: " << fmt(k7) << "\n"; + ofs << " p1: " << fmt(p1) << "\n"; + ofs << " p2: " << fmt(p2) << "\n"; + ofs << " A11: " << fmt(A11) << "\n"; + ofs << " A12: " << fmt(A12) << "\n"; + ofs << " A22: " << fmt(A22) << "\n"; + ofs << " u0: " << fmt(u0) << "\n"; + ofs << " v0: " << fmt(v0) << "\n"; + + ofs.flush(); + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Wrote cam_in_ex.txt to: %s", out_path.string().c_str()); + #else + ROS_INFO("Wrote cam_in_ex.txt to: %s", out_path.string().c_str()); + #endif + return true; + } catch (const std::exception& e) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Failed to convert calib.yaml: %s", e.what()); + #else + ROS_ERROR("Failed to convert calib.yaml: %s", e.what()); + #endif + return false; + } +} + // Get package share path std::string get_package_share_path(const std::string& package_name) { #ifdef ROS2 @@ -185,7 +306,24 @@ std::string get_package_share_path(const std::string& package_name) { #endif } -// Get package path +std::string get_package_source_directory() { + // 获取当前源文件的绝对路径 + std::filesystem::path current_file(__FILE__); + + // 回溯到包根目录(包含package.xml的目录) + auto path = current_file.parent_path(); + while (!path.empty() && !std::filesystem::exists(path / "package.xml")) { + path = path.parent_path(); + } + + if (path.empty()) { + throw std::runtime_error("Failed to locate package root directory"); + } + + return path.string(); +} + + std::string get_package_path(const std::string& package_name) { #ifdef ROS2 return ament_index_cpp::get_package_share_directory(package_name); @@ -322,7 +460,7 @@ static void lidar_device_callback(const lidar_device_info_t* device, bool attach #else config_dir = ros::package::getPath(package_name) + "/config"; #endif - + std::cout << "config_dir"<< config_dir <(); if (g_renderer->init(calib_config)) { @@ -504,7 +644,12 @@ int main(int argc, char *argv[]) #endif try { - std::string package_path = get_package_share_path("odin_ros_driver"); + #ifdef ROS2 + std::string package_path = get_package_source_directory(); + std::cout << "package_path: " << package_path << std::endl; + #else + std::string package_path = get_package_share_path("odin_ros_driver"); + #endif std::string config_file = package_path + "/config/control_command.yaml"; odin_ros_driver::YamlParser parser(config_file); @@ -532,9 +677,33 @@ int main(int argc, char *argv[]) g_sendcloudslam = get_key_value("sendcloudslam", 0); g_sendcloudrender = get_key_value("sendcloudrender", 1); g_sendrgb_compressed = get_key_value("sendrgbcompressed", 1); + g_record_data = get_key_value("recorddata", 0); g_log_level = get_key_value("log_devel", LOG_LEVEL_INFO); lidar_log_set_level(LIDAR_LOG_INFO); + if (g_record_data) { + const std::string package_name = "odin_ros_driver"; + std::string data_dir = ""; + #ifdef ROS2 + char* ros_workspace = std::getenv("COLCON_PREFIX_PATH"); + if (ros_workspace) { + std::string workspace_path(ros_workspace); + size_t pos = workspace_path.find("/install"); + if (pos != std::string::npos) { + data_dir = workspace_path.substr(0, pos) + "/src/odin_ros_driver/recorddata"; + } else { + data_dir = ament_index_cpp::get_package_share_directory(package_name) + "/recorddata"; + } + } else { + data_dir = ament_index_cpp::get_package_share_directory(package_name) + "/recorddata"; + } + #else + data_dir = ros::package::getPath(package_name) + "/recorddata"; + #endif + + g_ros_object->initialize_data_logger(data_dir); + } + if (lidar_system_init(lidar_device_callback)) { #ifdef ROS2 RCLCPP_ERROR(node->get_logger(), "Lidar system init failed"); @@ -639,13 +808,29 @@ int main(int argc, char *argv[]) // Cleanup on normal program exit if (odinDevice) { + // Convert calib.yaml to cam_in_ex.txt at program end + if (g_ros_object) { + const std::filesystem::path out_path = g_ros_object->get_root_dir() / "image" / "cam_in_ex.txt"; + (void)convert_calib_to_cam_in_ex(calib_file_, out_path); + } + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "pose_index: %d", g_ros_object->get_pose_index()); + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "cloud_index: %d", g_ros_object->get_cloud_index()); + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "image_index: %d", g_ros_object->get_image_index()); + #else + ROS_INFO("pose_index: %d", g_ros_object->get_pose_index()); + ROS_INFO("cloud_index: %d", g_ros_object->get_cloud_index()); + ROS_INFO("image_index: %d", g_ros_object->get_image_index()); + #endif // Perform cleanup on normal exit - lidar_stop_stream(odinDevice, LIDAR_MODE_SLAM); - lidar_unregister_stream_callback(odinDevice); - lidar_close_device(odinDevice); - lidar_destory_device(odinDevice); + // lidar_stop_stream(odinDevice, LIDAR_MODE_SLAM); + // lidar_unregister_stream_callback(odinDevice); + // lidar_close_device(odinDevice); + // lidar_destory_device(odinDevice); } - lidar_system_deinit(); + // lidar_system_deinit(); + + return 0; } diff --git a/src/pcd2depth_ros.cpp b/src/pcd2depth_ros.cpp new file mode 100644 index 0000000..2b42bf9 --- /dev/null +++ b/src/pcd2depth_ros.cpp @@ -0,0 +1,61 @@ +#include +#include +#include + +#include "depth_image_ros_node.hpp" + +bool fileExists(const std::string& filename) { + struct stat buffer; + return (stat(filename.c_str(), &buffer) == 0); +} + +int main(int argc, char **argv) +{ + ros::init(argc, argv, "depth_projector"); + ros::NodeHandle nh; + ros::NodeHandle pnh("~"); + int senddepth=0; + pnh.param("register_keys/senddepth", senddepth, 0); + if(senddepth==0) + { + ROS_INFO("Depth image will not be published."); + return 0; + } + + std::string calib_file_path; + pnh.param("calib_file_path", calib_file_path, ""); + + ROS_INFO("Waiting for calib.yaml file at: %s", calib_file_path.c_str()); + while(ros::ok() && !fileExists(calib_file_path)) + { + ROS_INFO_THROTTLE(5, "Still waiting for calib.yaml file..."); + ros::Duration(0.5).sleep(); + ros::spinOnce(); + } + + if(!ros::ok()) + { + ROS_INFO("Node shutdown before calib.yaml file was found."); + return 0; + } + + ROS_INFO("Found calib.yaml file! Loading parameters..."); + + std::string node_name = ros::this_node::getName(); + std::string rosparam_command = "rosparam load " + calib_file_path + " " + node_name; + int result = system(rosparam_command.c_str()); + + if(result == 0) + { + ROS_INFO("Successfully loaded parameters from calib.yaml to namespace: %s", node_name.c_str()); + } + else + { + ROS_ERROR("Failed to load parameters from calib.yaml"); + return 1; + } + + DepthImageRosNode projector(nh, pnh); + ros::spin(); + return 0; +} diff --git a/src/pcd2depth_ros2.cpp b/src/pcd2depth_ros2.cpp new file mode 100644 index 0000000..0ac5379 --- /dev/null +++ b/src/pcd2depth_ros2.cpp @@ -0,0 +1,225 @@ +#include +#include +#include +#include +#include +#include +#include +#include "depth_image_ros2_node.hpp" +#include +bool fileExists(const std::string& filename) { + struct stat buffer; + return (stat(filename.c_str(), &buffer) == 0); +} + +bool loadCalibParameters(std::shared_ptr node, const std::string& calib_file_path) { + try { + RCLCPP_INFO(node->get_logger(), "Loading parameters from calib.yaml file: %s", calib_file_path.c_str()); + + YAML::Node config = YAML::LoadFile(calib_file_path); + + if (config["cam_num"]) { + int cam_num = config["cam_num"].as(); + node->declare_parameter("cam_num", cam_num); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_num = %d", cam_num); + } + + if (config["img_topic_0"]) { + std::string img_topic = config["img_topic_0"].as(); + node->declare_parameter("img_topic_0", img_topic); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: img_topic_0 = %s", img_topic.c_str()); + } + + if (config["Tcl_0"]) { + std::vector tcl_matrix = config["Tcl_0"].as>(); + node->declare_parameter("Tcl_0", tcl_matrix); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: Tcl_0 (transform matrix with %zu elements)", tcl_matrix.size()); + } + + if (config["cam_0"]) { + YAML::Node cam_0 = config["cam_0"]; + + if (cam_0["cam_model"]) { + std::string cam_model = cam_0["cam_model"].as(); + node->declare_parameter("cam_0.cam_model", cam_model); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.cam_model = %s", cam_model.c_str()); + } + + if (cam_0["image_width"]) { + int image_width = cam_0["image_width"].as(); + node->declare_parameter("cam_0.image_width", image_width); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.image_width = %d", image_width); + } + + if (cam_0["image_height"]) { + int image_height = cam_0["image_height"].as(); + node->declare_parameter("cam_0.image_height", image_height); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.image_height = %d", image_height); + } + + std::vector distortion_params = {"k2", "k3", "k4", "k5", "k6", "k7", "p1", "p2"}; + for (const auto& param : distortion_params) { + if (cam_0[param]) { + double value = cam_0[param].as(); + node->declare_parameter("cam_0." + param, value); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.%s = %f", param.c_str(), value); + } + } + + std::vector intrinsic_params = {"A11", "A12", "A22", "u0", "v0"}; + for (const auto& param : intrinsic_params) { + if (cam_0[param]) { + double value = cam_0[param].as(); + node->declare_parameter("cam_0." + param, value); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.%s = %f", param.c_str(), value); + } + } + + if (cam_0["isFast"]) { + int is_fast = cam_0["isFast"].as(); + node->declare_parameter("cam_0.isFast", is_fast); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.isFast = %d", is_fast); + } + + if (cam_0["numDiff"]) { + int num_diff = cam_0["numDiff"].as(); + node->declare_parameter("cam_0.numDiff", num_diff); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.numDiff = %d", num_diff); + } + + if (cam_0["maxIncidentAngle"]) { + int max_incident_angle = cam_0["maxIncidentAngle"].as(); + node->declare_parameter("cam_0.maxIncidentAngle", max_incident_angle); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.maxIncidentAngle = %d", max_incident_angle); + } + } + + RCLCPP_INFO(node->get_logger(), "Successfully loaded all parameters from calib.yaml"); + return true; + + } catch (const YAML::Exception& e) { + RCLCPP_ERROR(node->get_logger(), "YAML parsing error: %s", e.what()); + return false; + } catch (const std::exception& e) { + RCLCPP_ERROR(node->get_logger(), "Error loading calib parameters: %s", e.what()); + return false; + } +} +std::string get_package_source_directory() { + // 使用 rcpputils::fs::path 替代 std::filesystem::path + rcpputils::fs::path current_file(__FILE__); + + // 回溯到包根目录 + auto path = current_file.parent_path(); + + // 使用 rcpputils::fs::exists 替代 std::filesystem::exists + while (!path.empty() && !rcpputils::fs::exists(path / "package.xml")) { + path = path.parent_path(); + } + + if (path.empty()) { + throw std::runtime_error("Failed to locate package root directory"); + } + + return path.string(); +} +int main(int argc, char **argv) +{ + rclcpp::init(argc, argv); + + + auto node = std::make_shared("pcd2depth_node"); + RCLCPP_INFO(node->get_logger(), "Node created"); + std::string package_path = get_package_source_directory(); + RCLCPP_INFO(node->get_logger(), "Package path: %s", package_path.c_str()); + + std::string config_file = package_path + "/config/control_command.yaml"; + RCLCPP_INFO(node->get_logger(), "Loading config from: %s", config_file.c_str()); + + YAML::Node config = YAML::LoadFile(config_file); + + if (!config["register_keys"]) { + throw std::runtime_error("Missing 'register_keys' section"); + } + + if (!config["register_keys"]["senddepth"]) { + throw std::runtime_error("Missing 'senddepth' parameter"); + } + int senddepth = config["register_keys"]["senddepth"].as(); + std::cout << "senddepth: " << senddepth << std::endl; + if(senddepth == 0) + { + RCLCPP_INFO(node->get_logger(), "Depth image will not be published."); + return 0; + } + + std::string calib_file_path = node->declare_parameter("calib_file_path", ""); + + RCLCPP_INFO(node->get_logger(), "Waiting for calib.yaml file at: %s", calib_file_path.c_str()); + while(rclcpp::ok() && !fileExists(calib_file_path)) + { + RCLCPP_INFO_THROTTLE(node->get_logger(), *node->get_clock(), 5000, "Still waiting for calib.yaml file..."); + rclcpp::sleep_for(std::chrono::milliseconds(500)); // 等待0.5秒后再检查 + rclcpp::spin_some(node); + } + + if(!rclcpp::ok()) + { + RCLCPP_INFO(node->get_logger(), "Node shutdown before calib.yaml file was found."); + return 0; + } + + RCLCPP_INFO(node->get_logger(), "Found calib.yaml file! Loading parameters..."); + + if (!loadCalibParameters(node, calib_file_path)) { + RCLCPP_ERROR(node->get_logger(), "Failed to load parameters from calib.yaml file"); + return 1; + } + + rclcpp::NodeOptions depth_node_options; + + std::vector params_override; + + try { + params_override.push_back(rclcpp::Parameter("cam_0.image_width", node->get_parameter("cam_0.image_width").as_int())); + params_override.push_back(rclcpp::Parameter("cam_0.image_height", node->get_parameter("cam_0.image_height").as_int())); + params_override.push_back(rclcpp::Parameter("cam_0.A11", node->get_parameter("cam_0.A11").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.A12", node->get_parameter("cam_0.A12").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.A22", node->get_parameter("cam_0.A22").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.u0", node->get_parameter("cam_0.u0").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.v0", node->get_parameter("cam_0.v0").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.k2", node->get_parameter("cam_0.k2").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.k3", node->get_parameter("cam_0.k3").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.k4", node->get_parameter("cam_0.k4").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.k5", node->get_parameter("cam_0.k5").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.k6", node->get_parameter("cam_0.k6").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.k7", node->get_parameter("cam_0.k7").as_double())); + params_override.push_back(rclcpp::Parameter("Tcl_0", node->get_parameter("Tcl_0").as_double_array())); + + depth_node_options.parameter_overrides(params_override); + + RCLCPP_INFO(node->get_logger(), "Parameters successfully prepared for DepthImageRos2Node"); + } + catch (const std::exception& e) { + RCLCPP_ERROR(node->get_logger(), "Error preparing parameters for DepthImageRos2Node: %s", e.what()); + return 1; + } + try + { + auto depth_node = std::make_shared(depth_node_options); + + depth_node->initialize(); + + rclcpp::executors::MultiThreadedExecutor executor; + executor.add_node(depth_node); + executor.spin(); + } + catch (const std::exception& e) + { + RCLCPP_ERROR(node->get_logger(), "Error creating depth node: %s", e.what()); + return 1; + } + + rclcpp::shutdown(); + return 0; +} diff --git a/src/pointcloud_depth_converter.cpp b/src/pointcloud_depth_converter.cpp new file mode 100644 index 0000000..09b200c --- /dev/null +++ b/src/pointcloud_depth_converter.cpp @@ -0,0 +1,373 @@ +#include "pointcloud_depth_converter.hpp" +#include +#include + +PointCloudToDepthConverter::PointCloudToDepthConverter(const CameraParams ¶ms) + : params_(params) +{ + initializeInternalParams(); + createDistortionMaps(); +} + +void PointCloudToDepthConverter::initializeInternalParams() +{ + scaled_width_ = static_cast(params_.image_width / params_.scale); + scaled_height_ = static_cast(params_.image_height / params_.scale); + + K_ = Eigen::Matrix3d::Identity(); + K_(0, 0) = params_.A11; + K_(0, 1) = params_.A12; + K_(0, 2) = params_.u0; + K_(1, 1) = params_.A22; + K_(1, 2) = params_.v0; + + Kl_ = Eigen::Matrix3d::Identity(); + Kl_(0, 0) = params_.A11 / params_.scale; + Kl_(0, 1) = params_.A12 / params_.scale; + Kl_(0, 2) = params_.u0 / params_.scale; + Kl_(1, 1) = params_.A22 / params_.scale; + Kl_(1, 2) = params_.v0 / params_.scale; + + K_4x4_ = Eigen::Matrix4d::Identity(); + K_4x4_.block<3, 3>(0, 0) = Kl_; + + Kcl_ = K_4x4_ * params_.Tcl; +} + +void PointCloudToDepthConverter::createDistortionMaps() +{ + map_x_ = cv::Mat::zeros(params_.image_height, params_.image_width, CV_32FC1); + map_y_ = cv::Mat::zeros(params_.image_height, params_.image_width, CV_32FC1); + + + for (int u = 0; u < params_.image_width; ++u) + { + for (int v = 0; v < params_.image_height; ++v) + { + double y = (v - params_.v0) / params_.A22; + double x = (u - params_.u0 - params_.A12 * y) / params_.A11; + + double r = sqrt(x * x + y * y); + double theta = atan(r); + + double theta_d = theta + params_.k2 * pow(theta, 2) + params_.k3 * pow(theta, 3) + + params_.k4 * pow(theta, 4) + params_.k5 * pow(theta, 5) + + params_.k6 * pow(theta, 6) + params_.k7 * pow(theta, 7); + + double x_distorted = x * (r / theta_d); + double y_distorted = y * (r / theta_d); + + map_x_.at(v, u) = static_cast(x_distorted * params_.A11 + params_.A12 * y_distorted + params_.u0); + map_y_.at(v, u) = static_cast(y_distorted * params_.A22 + params_.v0); + } + } + + inv_map_x_ = cv::Mat::zeros(params_.image_height, params_.image_width, CV_32FC1); + inv_map_y_ = cv::Mat::zeros(params_.image_height, params_.image_width, CV_32FC1); + for (int u = 0; u < params_.image_width; ++u) + { + for (int v = 0; v < params_.image_height; ++v) + { + double y = (v - params_.v0) / params_.A22; + double x = (u - params_.u0 - params_.A12 * y) / params_.A11; + + double r = sqrt(x * x + y * y); + double theta = atan(r); + + double theta_d = theta + params_.k2 * pow(theta, 2) + params_.k3 * pow(theta, 3) + + params_.k4 * pow(theta, 4) + params_.k5 * pow(theta, 5) + + params_.k6 * pow(theta, 6) + params_.k7 * pow(theta, 7); + + double x_distorted = x * (theta_d / r); + double y_distorted = y * (theta_d / r); + + inv_map_x_.at(v, u) = static_cast(x_distorted * params_.A11 + params_.A12 * y_distorted + params_.u0); + inv_map_y_.at(v, u) = static_cast(y_distorted * params_.A22 + params_.v0); + } + } +} + +PointCloudToDepthConverter::ProcessResult PointCloudToDepthConverter::processCloudAndImage( + const pcl::PointCloud &cloud, + const cv::Mat &image) +{ + ProcessResult result; + result.success = false; + + auto validation_result = validateInputs(cloud, image); + if (!validation_result.first) + { + result.error_message = validation_result.second; + return result; + } + + try + { + pcl::PointCloud cloud_in_cam; + pcl::transformPointCloud(cloud, cloud_in_cam, Kcl_); + + cv::Mat depth_img = projectCloudToDepth(cloud_in_cam); + + cv::Mat processed_depth = postProcessDepthImage(depth_img); + + pcl::PointCloud colored_cloud = generateColoredCloud(processed_depth, image); + + result.depth_image = processed_depth; + result.colored_cloud = colored_cloud; + result.success = true; + } + catch (const std::exception &e) + { + result.error_message = std::string("Processing error: ") + e.what(); + } + + return result; +} + +cv::Mat PointCloudToDepthConverter::projectCloudToDepth(const pcl::PointCloud &cloud_in_cam) +{ + cv::Mat depth_img = cv::Mat::zeros(scaled_height_, scaled_width_, CV_32FC1); + + for (const auto &camera_point : cloud_in_cam) + { + if (camera_point.z <= 0) + continue; + + int u = static_cast(std::round(camera_point.x / camera_point.z)); + int v = static_cast(std::round(camera_point.y / camera_point.z)); + + if (u >= 0 && u < scaled_width_ && v >= 0 && v < scaled_height_) + { + depth_img.at(v, u) = static_cast(camera_point.z); + + for (int du = -1; du <= 1; ++du) + { + for (int dv = -1; dv <= 1; ++dv) + { + int nu = u + du; + int nv = v + dv; + if (nu >= 0 && nu < scaled_width_ && nv >= 0 && nv < scaled_height_) + { + if (depth_img.at(nv, nu) == 0.0f) + { + depth_img.at(nv, nu) = static_cast(camera_point.z); + } + } + } + } + } + } + + return depth_img; +} + +cv::Mat PointCloudToDepthConverter::postProcessDepthImage(const cv::Mat &depth_img) { + if (depth_img.empty()) { + std::cerr << "ERROR: Input depth image is empty!" << std::endl; + return cv::Mat(); + } + + if (depth_img.data == nullptr) { + std::cerr << "ERROR: Input depth image has null data pointer!" << std::endl; + return cv::Mat(); + } + + if (depth_img.rows <= 0 || depth_img.cols <= 0) { + std::cerr << "ERROR: Invalid input dimensions: " + << depth_img.rows << "x" << depth_img.cols << std::endl; + return cv::Mat(); + } + + if (params_.image_width <= 0 || params_.image_height <= 0) { + std::cerr << "ERROR: Invalid target size: " + << params_.image_width << "x" << params_.image_height << std::endl; + return cv::Mat(); + } + + cv::Mat safe_input = depth_img.clone(); + if (safe_input.empty()) { + std::cerr << "ERROR: Failed to create safe copy of input image!" << std::endl; + return cv::Mat(); + } + + + cv::Mat depth_img_upsampled; + try { + depth_img_upsampled = customResize(safe_input, cv::Size(1600, 1296)); + } catch (const std::exception& e) { + std::cerr << "ERROR: Custom resize failed: " << e.what() << std::endl; + return cv::Mat(); + } + + if (depth_img_upsampled.empty()) { + std::cerr << "ERROR: Resized image is empty!" << std::endl; + return cv::Mat(); + } + + if (depth_img_upsampled.rows != 1296 || depth_img_upsampled.cols != 1600) { + std::cerr << "ERROR: Resized image has wrong dimensions: " + << depth_img_upsampled.cols << "x" << depth_img_upsampled.rows + << " (expected " << 1600 << "x" << 1296 << ")" << std::endl; + return cv::Mat(); + } + + + cv::Mat grad_x, grad_y, grad_magnitude; + try { + cv::Sobel(depth_img_upsampled, grad_x, CV_32F, 1, 0, 3); + cv::Sobel(depth_img_upsampled, grad_y, CV_32F, 0, 1, 3); + cv::magnitude(grad_x, grad_y, grad_magnitude); + } catch (const cv::Exception& e) { + std::cerr << "ERROR: Sobel/magnitude failed: " << e.what() << std::endl; + return cv::Mat(); + } + + if (grad_magnitude.type() != CV_32F) { + std::cerr << "ERROR: grad_magnitude has wrong type: " + << grad_magnitude.type() << " (expected CV_32F)" << std::endl; + return cv::Mat(); + } + + + cv::Mat threshold_mask; + try { + cv::threshold(grad_magnitude, threshold_mask, 0.75, 1, cv::THRESH_BINARY); + threshold_mask.convertTo(threshold_mask, CV_8U); + + + depth_img_upsampled.setTo(0, threshold_mask); + } catch (const cv::Exception& e) { + std::cerr << "ERROR: Threshold mask failed: " << e.what() << std::endl; + return cv::Mat(); + } + + cv::Mat depth_img_distorted; + try { + depth_undistorted_ = depth_img_upsampled.clone(); + cv::remap(depth_img_upsampled, depth_img_distorted, map_x_, map_y_, cv::INTER_LINEAR); + } catch (const cv::Exception& e) { + std::cerr << "ERROR: Remap failed: " << e.what() << std::endl; + return cv::Mat(); + } + + return depth_img_distorted; +} + +cv::Mat PointCloudToDepthConverter::customResize(const cv::Mat& src, const cv::Size& size) { + if (src.empty()) { + throw std::runtime_error("Source image is empty"); + } + + if (size.width <= 0 || size.height <= 0) { + throw std::runtime_error("Invalid target size"); + } + + + cv::Mat dst(size.height, size.width, src.type()); + + float scale_x = src.cols / static_cast(size.width); + float scale_y = src.rows / static_cast(size.height); + + if (src.channels() != 1 || src.type() != CV_32F) { + throw std::runtime_error("Unsupported image type - expected single channel float"); + } + + + for (int y = 0; y < dst.rows; y++) { + + int src_y = static_cast(y * scale_y); + src_y = std::min(src_y, src.rows - 1); + + for (int x = 0; x < dst.cols; x++) { + int src_x = static_cast(x * scale_x); + src_x = std::min(src_x, src.cols - 1); + dst.at(y, x) = src.at(src_y, src_x); + } + } + + return dst; +} +pcl::PointCloud PointCloudToDepthConverter::generateColoredCloud( + const cv::Mat &depth_img, const cv::Mat &color_img) +{ + cv::Mat depth_undistorted, color_undistorted; + depth_undistorted = depth_undistorted_.clone(); + cv::remap(color_img, color_undistorted, inv_map_x_, inv_map_y_, cv::INTER_LINEAR); + + + pcl::PointCloud cloud_colored; + + Eigen::Matrix4d Tlc = params_.Tcl.inverse(); + + for (int v = 0; v < depth_undistorted.rows; v += params_.point_sampling_rate) + { + for (int u = 0; u < depth_undistorted.cols; u += params_.point_sampling_rate) + { + float depth = depth_undistorted.at(v, u); + if (depth > 0.1f && depth < 100.0f) + { + double y_cam = (v - params_.v0) * depth / params_.A22; + double x_cam = ((u - params_.u0) * depth - params_.A12 * y_cam)/ params_.A11; + + double z_cam = depth; + + Eigen::Vector4d point_cam(x_cam, y_cam, z_cam, 1.0); + + Eigen::Vector4d point_lidar = Tlc * point_cam; + + pcl::PointXYZRGB point; + point.x = static_cast(point_lidar[0]); + point.y = static_cast(point_lidar[1]); + point.z = static_cast(point_lidar[2]); + + if (u < color_undistorted.cols && v < color_undistorted.rows) + { + cv::Vec3b color = color_undistorted.at(v, u); + point.b = color[0]; + point.g = color[1]; + point.r = color[2]; + } + else + { + point.r = point.g = point.b = 255; + } + + cloud_colored.points.push_back(point); + } + } + } + + cloud_colored.width = cloud_colored.points.size(); + cloud_colored.height = 1; + cloud_colored.is_dense = false; + + return cloud_colored; +} + +std::pair PointCloudToDepthConverter::validateInputs( + const pcl::PointCloud &cloud, const cv::Mat &image) +{ + if (cloud.empty()) + { + return {false, "Empty point cloud"}; + } + + if (image.empty()) + { + return {false, "Empty image"}; + } + + if (params_.A11 < 1e-6 || params_.A22 < 1e-6) + { + return {false, "Invalid camera intrinsics"}; + } + + return {true, ""}; +} + +void PointCloudToDepthConverter::updateCameraParams(const CameraParams ¶ms) +{ + params_ = params; + initializeInternalParams(); + createDistortionMaps(); +}