ROSBag#

class ROSBag(filename: str, release: str = 'auto', topicfilter: str | list[str] | None = None, msgfilter: str | list[str] | None = 'Image', dtype: dtype | str | dict | None = None, colororder: str | dict | None = None, verbose: bool = False, depth_units: str | float | None = None, **kwargs: Any)[source][source]#

Iterate images and point clouds from a ROS 1 bag file.

Parameters:
  • filename (str or Path) – path to a .bag file, or an http(s):// URL

  • release (str) – ROS release (distribution) whose message definitions are used to parse the bag file, a name or unique substring such as "noetic" or "humble", or "auto" to detect it, defaults to "auto"

  • topicfilter (str or list of str or None) – only yield messages from this topic or list of topics; None accepts all topics

  • msgfilter (str or list of str or None) – only yield messages whose type contains this substring or matches any entry in the list; None accepts all types, defaults to "Image"

  • dtype (str or dict) – override the numpy dtype for all image pixel data, or by topic {topic: dtype}

  • colororder (str or dict or None) – override the color-plane order for all image, or by topic {topic: colororder}

  • verbose (bool) – print progress and decoding problems, defaults to False

  • depth_units (None, "auto" or float) – convert depth images to float32 metres, see below; None leaves them as recorded, "auto" finds the scale, a number is the scale in metres per unit, defaults to None

  • kwargs – options applied to image frames, see convert

Raises:
  • ImportError – if the rosbags package is not installed

  • ValueError – if depth_units is not None, "auto" or a positive number

The resulting object is an iterator that yields:

  • Image for messages whose type ends in Image, which includes CompressedImage.

  • PointCloud for PointCloud2 messages (requires open3d)

  • the raw deserialised message object for all other types

Each yielded object carries a timestamp attribute (ROS nanosecond epoch from the message header) and a topic attribute (the topic on which it was published).

Intel RealSense bags

The RealSense SDK records a ROS 1 bag in which every image message is followed by 4 bytes that are not part of sensor_msgs/Image: a float32 holding the depth scale, in metres per unit, for a depth image and 0.0 for a color image. A message type defines its own length, so a reader that does not know about the extra bytes cannot decode the images.

The end of the pixel data is found from the layout of the image message, whose data array must be height * step bytes long. The extra bytes are therefore never mistaken for pixels, and bags without them (such as Intel’s own sample bags) are read correctly too. The pixel values are not changed unless depth_units is given, see below.

Depth in metres

ROS has a standard for depth images, REP 118 (a ROS Enhancement Proposal). A depth image is either float32 in metres (32FC1, where NaN means no measurement) or, as a camera driver publishes it before conversion, uint16 in millimetres (16UC1, where 0 means no measurement). With depth_units="auto" an image in either form is returned as float32 metres, since the standard says what the unit is, and an integer image has its zeros replaced by NaN, so that “no measurement” means the same in both.

By default a depth image is returned as recorded. With depth_units it is returned as float32 in metres, so that the value of a pixel does not depend on the camera or driver that recorded it. depth_units is the scale in metres per unit, as in librealsense, for example 0.001 for millimetres. Note that this is the reciprocal of the depth_scale of Open3D and TUM RGB-D, which are units per metre: 1000 and 5000 respectively.

  • a number is used as the scale for every depth image. A 32FC1 image is already in metres, so the number is then a gain

  • "auto" finds the scale for each image: the footer of a RealSense bag if it has one, otherwise the unit that REP 118 gives for the encoding, which is 0.001 for 16UC1 and 1.0 for 32FC1. The RealSense SDK writes depth as mono16, which REP 118 does not cover, so without a footer (Intel’s sample bags have none) the scale is not known. The image is then returned as recorded, with a RuntimeWarning once for the topic, rather than guess: give the number instead

An image is taken to be a depth image if it has a footer scale, or if it is 16UC1, mono16 or 32FC1 and its topic name contains depth, in any case. Other images are never converted. A converted image has depth_units set to 1.0, since it is now in metres. In a converted integer image, pixels that are 0 become NaN. A 32FC1 image already uses NaN, so only its scale changes.

The extra bytes are interpreted as a depth scale only if the bag is recognised as coming from the RealSense SDK (it has a realsense_msgs connection) and they are a positive, finite float32. The second test alone would prove nothing, since about half of all 4-byte patterns pass it, so it is the first that justifies it. A depth image carrying a scale has a depth_units attribute, for example 0.001 for pixels in millimetres. Other images do not have the attribute.

Any other bytes after an image are ignored, and a RuntimeWarning is issued, once for each topic. This covers bytes in a bag that is not recognised as RealSense, and bytes in one that are not a positive 4-byte scale or 0.0. We do not guess what they are. All other message types must be exactly as long as their type says.

Filters

The message and topic filters can be a single string, or a list of strings. If a single string is provided, it is treated as a list with one element. The filter passes if any of the strings in the list are a substring of the message type (for the message filter) or topic name (for the topic filter). It is an OR condition.

Usage modes

Implicit — iterating directly over the object opens and closes the bag file automatically around the loop:

from machinevisiontoolbox import ROSBag
for img in ROSBag("mybag.bag", release="noetic"):
    img.disp()

Explicit context manager — use a with statement when you need to make multiple passes over the bag, call helper methods such as topics or print, or simply want a guaranteed close even if an exception is raised:

bag = ROSBag("mybag.bag", release="noetic", msgfilter=None)
with bag:
    bag.print()                     # inspect topics
    for msg in bag:                 # iterate messages
        print(msg.topic, msg.timestamp)

Note

filename may be an http:// or https:// URL, in which case the bag file is downloaded to a temporary file on first use and that file is reused for the lifetime of the ROSBag object. The temporary file is deleted automatically when the object is garbage collected or when the script exits.

Note

If filename is a relative path that does not exist in the current working directory, it is looked up in the mvtb-data companion package automatically. Bag files placed there can therefore be referenced by their bare name, e.g. ROSBag("forest.bag").

Note

The release argument selects the ROS release (distribution) whose message definitions are used to parse the bag file. Message definitions can change between releases, and using the wrong ones can lead to incorrect parsing of the data.

The default "auto" tries the known releases on the first message of the bag and keeps the first that decodes it, for both ROS 1 and ROS 2 (CDR) encoded messages. The choice is then available as the release attribute. Pass verbose=True to see what was tried.

Alternatively name a release. The string is matched case-insensitively against the member names of Stores, so short names such as "noetic" or "humble" are accepted in addition to the full enum name (e.g. "ROS1_NOETIC").

Base constructor for image sources.

Parameters:

kwargs (Any) – source-specific keyword arguments