================================================================================ Huhb3D ROS Deployment Manual cv_bridge + image_transport + depth_image_proc ================================================================================ SECTION 1: PREREQUISITES -------------------------------------------------------------------------------- ROS2 packages required: sudo apt install ros-${ROS_DISTRO}-cv-bridge \ ros-${ROS_DISTRO}-image-transport \ ros-${ROS_DISTRO}-depth-image-proc \ ros-${ROS_DISTRO}-image-pipeline Python dependencies: pip install opencv-python numpy rosbag2 Dataset structure on ROS workstation: ~/huhb3d_dataset/ |-- dataset_metadata.json |-- flange/ | |-- scene_camera.json | |-- scene_gt.json | |-- rgb/rgb_0001.png ... rgb_0010.png | |-- depth/depth_0001.png ... depth_0010.png | |-- mask/ ... | |-- mask_instance/ ... |-- bearing_block/ |-- ... SECTION 2: READING DEPTH MAPS - THE CRITICAL PATH -------------------------------------------------------------------------------- *** THE #1 CAUSE OF BLACK DEPTH IMAGES IS WRONG imread FLAG *** CORRECT: import cv2 depth = cv2.imread('depth_0001.png', cv2.IMREAD_UNCHANGED) # depth.shape = (600, 800), depth.dtype = uint16 # depth values: 730-844 (mm) WRONG - produces BLACK IMAGE: depth = cv2.imread('depth_0001.png') # default = IMREAD_COLOR # depth.shape = (600, 800, 3), depth.dtype = uint8 # depth values: 2-3 (high byte LOST!) WRONG - produces WRONG VALUES: depth = cv2.imread('depth_0001.png', cv2.IMREAD_GRAYSCALE) # depth.shape = (600, 800), depth.dtype = uint8 # depth values: 2-3 (high byte LOST, 99.7% error!) Why this happens: Our depth PNGs are 16-bit grayscale (bit_depth=16, color_type=0). - IMREAD_UNCHANGED preserves the original 16-bit format - IMREAD_COLOR converts to 8-bit BGR (3 channels) - IMREAD_GRAYSCALE converts to 8-bit (high byte truncated) Values 730-844 in uint16 become 2-3 in uint8 (730>>8=2, 844>>8=3) SECTION 3: DISPLAYING DEPTH MAPS WITH imshow -------------------------------------------------------------------------------- *** cv2.imshow CANNOT directly display uint16 depth maps *** WRONG - shows black image: depth = cv2.imread('depth_0001.png', cv2.IMREAD_UNCHANGED) cv2.imshow('depth', depth) # BLACK! values 730-844 look near-zero vs 65535 cv2.waitKey(0) CORRECT - normalize before display: depth = cv2.imread('depth_0001.png', cv2.IMREAD_UNCHANGED) depth_display = cv2.normalize(depth, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U) cv2.imshow('depth', depth_display) cv2.waitKey(0) CORRECT - colormap for better visualization: depth = cv2.imread('depth_0001.png', cv2.IMREAD_UNCHANGED) depth_display = cv2.normalize(depth, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U) depth_color = cv2.applyColorMap(depth_display, cv2.COLORMAP_JET) cv2.imshow('depth_colormap', depth_color) cv2.waitKey(0) CORRECT - with background masking: depth = cv2.imread('depth_0001.png', cv2.IMREAD_UNCHANGED) mask = depth > 0 depth_norm = np.zeros_like(depth, dtype=np.uint8) depth_norm[mask] = ((depth[mask] - depth[mask].min()) / (depth[mask].max() - depth[mask].min()) * 255).astype(np.uint8) cv2.imshow('depth_masked', depth_norm) cv2.waitKey(0) SECTION 4: cv_bridge - DEPTH TO sensor_msgs/Image -------------------------------------------------------------------------------- Publishing depth as ROS Image: import rclpy from rclpy.node import Node from sensor_msgs.msg import Image from cv_bridge import CvBridge import cv2 class DepthPublisher(Node): def __init__(self): super().__init__('depth_publisher') self.bridge = CvBridge() self.pub = self.create_publisher(Image, '/camera/depth/image_raw', 10) def publish_depth(self, path): depth = cv2.imread(path, cv2.IMREAD_UNCHANGED) # MUST use UNCHANGED! if depth is None: self.get_logger().error(f'Failed to read: {path}') return msg = self.bridge.cv2_to_imgmsg(depth, encoding='16UC1') self.pub.publish(msg) Resulting sensor_msgs/Image fields: header.frame_id: 'camera_depth_optical_frame' height: 600 width: 800 encoding: '16UC1' is_bigendian: 0 step: 1600 data: <960000 bytes, little-endian uint16> SECTION 5: cv_bridge - DEPTH FROM sensor_msgs/Image -------------------------------------------------------------------------------- Subscribing to depth in ROS: class DepthSubscriber(Node): def __init__(self): super().__init__('depth_subscriber') self.bridge = CvBridge() self.sub = self.create_subscription( Image, '/camera/depth/image_raw', self.callback, 10) def callback(self, msg): depth = self.bridge.imgmsg_to_cv2(msg, desired_encoding='16UC1') # depth.shape = (600, 800), depth.dtype = uint16 # depth values in mm # Convert to meters for ROS convention depth_m = depth.astype(np.float32) / 1000.0 # Publish as 32FC1 (float, meters) msg_float = self.bridge.cv2_to_imgmsg(depth_m, encoding='32FC1') SECTION 6: CAMERA INFO PUBLICATION -------------------------------------------------------------------------------- Reading BOP cam_K and publishing as CameraInfo: from sensor_msgs.msg import CameraInfo import json def load_camera_info(scene_camera_path, frame_id): with open(scene_camera_path) as f: sc = json.load(f) cam = sc[str(frame_id)] K = cam['cam_K'] # [fx,0,cx,0,fy,cy,0,0,1] info = CameraInfo() info.header.frame_id = 'camera_depth_optical_frame' info.height = 600 info.width = 800 info.distortion_model = 'plumb_bob' info.d = [] # no distortion info.k = [K[0], K[1], K[2], K[3], K[4], K[5], K[6], K[7], K[8]] info.r = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] info.p = [K[0], K[1], K[2], 0.0, K[3], K[4], K[5], 0.0, K[6], K[7], K[8], 0.0] return info SECTION 7: 6DoF POSE PUBLISHING -------------------------------------------------------------------------------- Converting BOP GT to ROS PoseStamped: from geometry_msgs.msg import PoseStamped import numpy as np def bop_to_pose(scene_gt_path, frame_id, obj_id=1): with open(scene_gt_path) as f: sg = json.load(f) gt = sg[str(frame_id)][0] R = np.array(gt['cam_R_m2c']).reshape(3, 3) t = np.array(gt['cam_t_m2c']) # mm # Convert mm to meters for ROS t_m = t / 1000.0 pose = PoseStamped() pose.header.frame_id = 'camera_depth_optical_frame' pose.pose.position.x = float(t_m[0]) pose.pose.position.y = float(t_m[1]) pose.pose.position.z = float(t_m[2]) # Rotation matrix to quaternion from scipy.spatial.transform import Rotation quat = Rotation.from_matrix(R).as_quat() # [x, y, z, w] pose.pose.orientation.x = float(quat[0]) pose.pose.orientation.y = float(quat[1]) pose.pose.orientation.z = float(quat[2]) pose.pose.orientation.w = float(quat[3]) return pose SECTION 8: depth_image_proc PIPELINE -------------------------------------------------------------------------------- Launch depth_image_proc for point cloud generation: # Launch file: huhb3d_depth.launch.py from launch import LaunchDescription from launch_ros.actions import Node def generate_launch_description(): return LaunchDescription([ Node( package='depth_image_proc', executable='depth_image_proc', name='depth_image_proc', remappings=[ ('image_raw', '/camera/depth/image_raw'), ('camera_info', '/camera/depth/camera_info'), ], output='screen'), ]) This converts 16UC1 depth + CameraInfo -> PointCloud2 Zero pixels (background) are automatically filtered SECTION 9: COMMON PITFALLS REFERENCE TABLE -------------------------------------------------------------------------------- +----+----------------------------------+---------------------------+---------------------------+ | # | Pitfall | Symptom | Fix | +----+----------------------------------+---------------------------+---------------------------+ | 1 | cv2.imread() without | Black image, values 2-3 | Use cv2.IMREAD_UNCHANGED | | | IMREAD_UNCHANGED | instead of 730-844 | | +----+----------------------------------+---------------------------+---------------------------+ | 2 | cv2.imshow() with uint16 | Black image (730/65535 | Normalize to 0-255 first | | | | looks near-zero) | or use applyColorMap | +----+----------------------------------+---------------------------+---------------------------+ | 3 | cv_bridge encoding='mono16' | May work but '16UC1' is | Use encoding='16UC1' | | | instead of '16UC1' | the ROS standard | | +----+----------------------------------+---------------------------+---------------------------+ | 4 | Forgetting mm->m conversion | Depth 800x too large | Divide by 1000.0 | | | | for point cloud | | +----+----------------------------------+---------------------------+---------------------------+ | 5 | Not handling zero (background) | Background appears as | Mask depth > 0 or use | | | pixels | 0m depth point cloud | depth_image_proc | +----+----------------------------------+---------------------------+---------------------------+ | 6 | cam_K as flat array not 3x3 | Wrong camera matrix | np.array(K).reshape(3,3) | | | | shape | | +----+----------------------------------+---------------------------+---------------------------+ | 7 | OpenGL vs OpenCV coordinates | Pose appears flipped | Our data is already in | | | | | OpenCV convention | +----+----------------------------------+---------------------------+---------------------------+ | 8 | is_bigendian=1 on x86 | Byte-swapped depth | Set is_bigendian=0 | | | | values | (cv_bridge default) | +----+----------------------------------+---------------------------+---------------------------+ SECTION 10: COMPLETE ROS2 NODE TEMPLATE -------------------------------------------------------------------------------- # huhb3d_ros_publisher.py import rclpy from rclpy.node import Node from sensor_msgs.msg import Image, CameraInfo from geometry_msgs.msg import PoseStamped from cv_bridge import CvBridge import cv2, json, numpy as np from scipy.spatial.transform import Rotation class Huhb3DPublisher(Node): def __init__(self, dataset_path, obj_name='flange'): super().__init__('huhb3d_publisher') self.bridge = CvBridge() self.obj_dir = f'{dataset_path}/{obj_name}' self.frame = 1 self.rgb_pub = self.create_publisher(Image, '/camera/rgb/image_raw', 10) self.depth_pub = self.create_publisher(Image, '/camera/depth/image_raw', 10) self.info_pub = self.create_publisher(CameraInfo, '/camera/depth/camera_info', 10) self.pose_pub = self.create_publisher(PoseStamped, '/object/pose', 10) self.timer = self.create_timer(0.5, self.publish_frame) def publish_frame(self): f = str(self.frame) # RGB rgb = cv2.imread(f'{self.obj_dir}/rgb/rgb_{self.frame:04d}.png') if rgb is not None: self.rgb_pub.publish(self.bridge.cv2_to_imgmsg(rgb, 'bgr8')) # Depth - MUST use IMREAD_UNCHANGED! depth = cv2.imread(f'{self.obj_dir}/depth/depth_{self.frame:04d}.png', cv2.IMREAD_UNCHANGED) if depth is not None: self.depth_pub.publish(self.bridge.cv2_to_imgmsg(depth, '16UC1')) # Camera Info with open(f'{self.obj_dir}/scene_camera.json') as fp: sc = json.load(fp) K = sc[f]['cam_K'] info = CameraInfo() info.header.frame_id = 'camera_depth_optical_frame' info.height, info.width = 600, 800 info.k = [float(x) for x in K] info.p = [K[0],K[1],K[2],0, K[3],K[4],K[5],0, K[6],K[7],K[8],0] self.info_pub.publish(info) # 6DoF Pose with open(f'{self.obj_dir}/scene_gt.json') as fp: sg = json.load(fp) gt = sg[f][0] R = np.array(gt['cam_R_m2c']).reshape(3,3) t = np.array(gt['cam_t_m2c']) / 1000.0 pose = PoseStamped() pose.header.frame_id = 'camera_depth_optical_frame' pose.pose.position.x, pose.pose.position.y, pose.pose.position.z = t q = Rotation.from_matrix(R).as_quat() pose.pose.orientation.x, pose.pose.orientation.y = q[0], q[1] pose.pose.orientation.z, pose.pose.orientation.w = q[2], q[3] self.pose_pub.publish(pose) self.frame = self.frame % 10 + 1 if __name__ == '__main__': rclpy.init() node = Huhb3DPublisher('/path/to/sell_Huhb3D-Test-Precision-v4') rclpy.spin(node) ================================================================================ END OF ROS DEPLOYMENT MANUAL ================================================================================