# Copyright 2025 Robotics Group of the University of León (ULE) # 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. import rosbag2_py import cv2 import os import glob from cv_bridge import CvBridge from rclpy.serialization import deserialize_message from sensor_msgs.msg import Image import time bags_dir = "/media/robotica/681EC1401EC107D0/Salidas/SalidaBercianos2" output_root = os.path.join(bags_dir, "dataset") image_topic = "/camera/camera/color/image_raw" FRAME_INTERVAL = 10 MAX_WORKERS = 2 MAX_BATCH_SIZE = 5 os.makedirs(output_root, exist_ok=True) print(f"Output directory: {output_root} (exists: {os.path.exists(output_root)})") def extract_images_from_bag(bag_path, output_dir): """Extract images from a ROS2 bag file. Args: bag_path: Path to the ROS2 bag directory. output_dir: Directory where extracted images will be saved. Returns: Number of images successfully saved. """ bridge = CvBridge() saved_frame_count = 0 total_frame_count = 0 bag_name = os.path.basename(bag_path) print(f"Processing rosbag: {bag_name}, saving with prefix to: {output_dir}") try: reader = rosbag2_py.SequentialReader() reader.open( rosbag2_py.StorageOptions(uri=bag_path, storage_id="sqlite3"), rosbag2_py.ConverterOptions( input_serialization_format="cdr", output_serialization_format="cdr" ), ) topic_types = reader.get_all_topics_and_types() topic_type_map = {topic.name: topic.type for topic in topic_types} print(f"Available topics in {bag_name}: {list(topic_type_map.keys())}") if image_topic not in topic_type_map: print(f"ERROR: Topic {image_topic} does not exist in {bag_name}.") return 0 print(f"Processing topic {image_topic} in {bag_name}") is_depth = "depth" in image_topic start_time = time.time() while reader.has_next(): topic, data, timestamp = reader.read_next() if topic == image_topic: total_frame_count += 1 if (total_frame_count - 1) % FRAME_INTERVAL == 0: try: img_msg = deserialize_message(data, Image) if is_depth: cv_image = bridge.imgmsg_to_cv2(img_msg) cv_image = cv2.normalize(cv_image, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U) cv_image = cv2.applyColorMap(cv_image, cv2.COLORMAP_TURBO) else: cv_image = bridge.imgmsg_to_cv2(img_msg, desired_encoding="bgr8") frame_filename = f"{bag_name}_frame_{saved_frame_count:06d}.jpg" frame_path = os.path.join(output_dir, frame_filename) success = cv2.imwrite(frame_path, cv_image, [cv2.IMWRITE_JPEG_QUALITY, 85]) if not success: print(f"Error: Could not save {frame_path}") else: saved_frame_count += 1 if saved_frame_count % 5 == 0: print(f"Saved {frame_path} ({cv_image.shape})") except Exception as e: print(f"Error in frame {total_frame_count}: {str(e)}") if total_frame_count % 100 == 0: elapsed = time.time() - start_time print(f"{bag_name}: Processed {total_frame_count} frames, saved {saved_frame_count}") elapsed = time.time() - start_time rate = saved_frame_count / elapsed if elapsed > 0 else 0 print(f"Completed {bag_name}: {saved_frame_count} images saved from {total_frame_count} frames") print(f"Speed: {rate:.2f} img/s, total time: {elapsed:.2f}s") return saved_frame_count except Exception as e: print(f"Fatal error processing {bag_name}: {str(e)}") import traceback traceback.print_exc() return 0 def main(): """Main function to extract images from ROS2 bag files. Processes all rosbag2 directories found in the specified bags directory, extracting one frame every FRAME_INTERVAL frames from the configured image topic. """ print(f"Starting image extraction (1 every {FRAME_INTERVAL} frames)") bag_folders = glob.glob(os.path.join(bags_dir, "rosbag2_*")) print(f"Found {len(bag_folders)} rosbags: {[os.path.basename(b) for b in bag_folders]}") if not bag_folders: print(f"ERROR: No rosbags found in {bags_dir}") return total_frames = 0 start_time = time.time() for bag_folder in bag_folders: if os.path.isdir(bag_folder) and os.path.exists(os.path.join(bag_folder, "metadata.yaml")): print(f"\nProcessing {os.path.basename(bag_folder)}...") frames = extract_images_from_bag(bag_folder, output_root) total_frames += frames elapsed = time.time() - start_time rate = total_frames / elapsed if elapsed > 0 else 0 print(f"\nProcess completed. {total_frames} images extracted in {elapsed:.2f}s") print(f"Average speed: {rate:.2f} img/s") print(f"All images are in: {output_root}") if __name__ == "__main__": main()