Ask Your Question

Constructing a float32 value from four uint8 bytes

asked 2016-07-25 14:09:26 -0500

skr_robo gravatar image

updated 2016-07-25 14:10:46 -0500

I am trying to read depth values from the topic /camera/depth/image_rect_color. The message is of the type sensor_msgs/Image and prints out 8 bit data (uint8) as elements of an image array. Since the image is encoded as 32FC1, I need to combine four of these elements to obtain depth information of a single pixel. A stack overflow answer contains the following code:

float f;
uchar b[] = {b3, b2, b1, b0};
memcpy(&f, &b, sizeof(f));
return f;

Is this the right approach to construct a float32 value from 4 bytes of uint8 values, without any data loss ?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2016-07-25 15:10:14 -0500

ahendrix gravatar image

Instead of trying to do that conversion by hand for each pixel, I recommend that you use the cv_bridge package to convert your sensor_msgs/Image into a cv::Mat, which should be easier to use. The cv_bridge tutorial is probably a good place to start, but obviously you'll need to change the image encoding parameters.

edit flag offensive delete link more


My intention is to find out any obstacle within 5m of a zed stereo camera. The data is basically depth value. I am planning to avoid using openCV. Is there any reference for data conversion by hand? I wouldn't mind writing additional lines of code for that.

skr_robo gravatar image skr_robo  ( 2016-07-25 15:24:55 -0500 )edit

The canonical reference is the implementation of the sensor_msgs/Image to cv::Mat conversion function that's underneath all of the cv_bridge conversions:

ahendrix gravatar image ahendrix  ( 2016-07-25 16:18:25 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2016-07-25 14:09:26 -0500

Seen: 428 times

Last updated: Jul 25 '16