Search code examples
c++jpegros

Saving JPG encoded array from a ROS sensor_msgs/CompressedImage to a file in roscpp


I have a Robot Operating System (ROS) .bag file containing .jpg compressed images in the form of sensor_msgs/CompressedImage messages. I have written a roscpp program that can access the raw data in the individual messages, but I'm having a hard time saving the array of raw jpg encoded data into a file.

Unfortunately, the bag files I have are very large and contain thousands of images, and I am working under a time constraint. I tried using rosbag play -i and image_view export to save off the images, but it's way too slow. I also tried using Python, but Python is slow, and I don't have a way to save the images (same problem as in C++).

Essentially, I need a way to prepend a valid jpg header to my data and save it in a file. Any suggestions are appreciated!


Solution

  • Creating an image header for a chunk of data that should already be an image is probably not the right approach. After all, jpegs are complex and the datastream should have all the information needed to decode them... how else would those tools be able to display them to you?

    You can get a good idea of whether or not a binary blob contains an image by looking at the first and last bytes. Jpegs start with FF D8 and end with FF D9, for example. Some of the magic numbers for other files can be found here: https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files