File size: 9,992 Bytes
d46d640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db29aad
d46d640
 
db29aad
d46d640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db29aad
 
 
 
d46d640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import os
import glob
import cv2
import numpy as np
import yaml
import json
import rosbag2_py
from rclpy.serialization import deserialize_message
from rosidl_runtime_py.utilities import get_message
import sensor_msgs_py.point_cloud2 as pc2

class BagDatasetExtractor:
    def __init__(self, bag_path, output_dir, lidar_transform_path, camera_transform_path, start_frame_idx=0):
        self.bag_path = bag_path
        self.output_dir = output_dir
        self.lidar_transform_path = lidar_transform_path
        self.camera_transform_path = camera_transform_path
        self.frame_idx = start_frame_idx   
        
        self.prepare_folders()
        
        # ROS 2 Bag Reader Setup
        self.reader = rosbag2_py.SequentialReader()
        storage_options = rosbag2_py.StorageOptions(uri=self.bag_path, storage_id='sqlite3')
        converter_options = rosbag2_py.ConverterOptions(
            input_serialization_format='cdr',
            output_serialization_format='cdr'
        )
        self.reader.open(storage_options, converter_options)
        
        self.topic_types = {topic.name: topic.type for topic in self.reader.get_all_topics_and_types()}
        self.transforms = self._load_transforms()

        # Dynamic Mappings
        '''
        $ ros2 topic echo --once /bev/semantic_labels
            data: '{"0":{"class":"BACKGROUND"},"1":{"class":"UNLABELLED"},"2":{"class":"leaf"},"3":{"class":"branch"},"4":{"class":"weed"},"5":{"cl...'
            ---
        $ ros2 topic echo --once /bev/semantic_labels_bb 
            data: '{"0":{"class":"ground"},"1":{"class":"leaf"},"2":{"class":"branch"},"3":{"class":"weed"},"4":{"class":"obstacle"},"time_stamp":{...'
            ---

        '''
        self.target_classes = {"ground": 0, "leaf": 1, "branch": 2, "weed": 3, "obstacle": 4}
        self.semantic_mapping = {}
        self.bb_mapping = {}

    def _create_matrix_from_yaml(self, transform_data):
        t = transform_data['transformation']['translation']
        q = transform_data['transformation']['rotation']
        
        translation = np.array([t['x'], t['y'], t['z']])
        
        x, y, z, w = q['x'], q['y'], q['z'], q['w']

        # Normalize quaternion
        norm = np.sqrt(x*x + y*y + z*z + w*w)
        if norm == 0:
            # Handle zero-norm quaternion (invalid rotation)
            x, y, z, w = 0, 0, 0, 1
        else:
            x /= norm
            y /= norm
            z /= norm
            w /= norm

        # Rotation matrix from quaternion
        rotation_matrix = np.array([
            [1 - 2*y*y - 2*z*z, 2*x*y - 2*z*w, 2*x*z + 2*y*w],
            [2*x*y + 2*z*w, 1 - 2*x*x - 2*z*z, 2*y*z - 2*x*w],
            [2*x*z - 2*y*w, 2*y*z + 2*x*w, 1 - 2*x*x - 2*y*y]
        ])

        # Create 4x4 homogeneous matrix
        matrix = np.eye(4)
        matrix[:3, :3] = rotation_matrix
        matrix[:3, 3] = translation
        
        return matrix
        
    def _load_transforms(self):
        transforms = {}
        try:
            with open(self.lidar_transform_path, 'r') as f:
                lidar_transform_data = yaml.safe_load(f)
                transforms['lidar_to_parent'] = self._create_matrix_from_yaml(lidar_transform_data)
            with open(self.camera_transform_path, 'r') as f:
                camera_transform_data = yaml.safe_load(f)
                transforms['camera_to_parent'] = self._create_matrix_from_yaml(camera_transform_data)
        except Exception as e:
            print(f"Warning: Transform file issue: {e}")
        return transforms

    def prepare_folders(self):
        for sub in ['rgb', 'depth', 'lidar', 'bev_label', 'extrinsics']:
            os.makedirs(os.path.join(self.output_dir, sub), exist_ok=True)

    def _parse_label_json(self, json_str):
        """Extracts the mapping from Isaac Sim JSON string to our fixed IDs."""
        mapping = {}
        try:
            data = json.loads(json_str)
            for key, val in data.items():
                if isinstance(val, dict) and "class" in val:
                    class_name = val["class"].lower()
                    if class_name in self.target_classes:
                        mapping[int(key)] = self.target_classes[class_name]
        except json.JSONDecodeError:
            print(f"Warning: Failed to parse JSON label string: {json_str}")
        return mapping

    def process_bev_logic(self, semantic_msg, bbox_msg):
        height, width = semantic_msg.height, semantic_msg.width
        semantic_raw = np.frombuffer(semantic_msg.data, dtype=np.int32).reshape((height, width))
        
        # 1. Remap Semantic Image
        remapped_semantic = np.full_like(semantic_raw, 3, dtype=np.uint8) # Default 3 (Other/Background)
        for isaac_id, target_id in self.semantic_mapping.items():
            remapped_semantic[semantic_raw == isaac_id] = target_id
            
        # 2. Add bounding box centers for branches
        for detection in bbox_msg.detections:
            if detection.results:
                try:
                    isaac_class_id = int(detection.results[0].hypothesis.class_id)
                    # Use the BB mapping specifically for the bounding boxes
                    if self.bb_mapping.get(isaac_class_id) == 2: # 2 is Branch
                        center_x = int(detection.bbox.center.position.x)
                        center_y = int(detection.bbox.center.position.y)
                        cv2.circle(remapped_semantic, (center_x, center_y), radius=3, color=2, thickness=-1)
                except Exception as e: 
                    continue
                
        return remapped_semantic

    def run(self):
        print(f"Starting extraction for bag: {os.path.basename(self.bag_path)}")
        sync_data = {}

        # Added the label topics to the filter
        self.reader.set_filter(rosbag2_py.StorageFilter(topics=[
            '/camera_front/rgb', '/camera_front/depth', '/lidar_front/point_cloud', 
            '/bev/semantic_segmentation', '/bev/bbox_2d',
            '/bev/semantic_labels', '/bev/semantic_labels_bb'
        ]))

        while self.reader.has_next():
            (topic, data, t_msg) = self.reader.read_next()
            msg_type = get_message(self.topic_types[topic])
            msg = deserialize_message(data, msg_type)

            # Update Mappings dynamically if we see the label topics
            if topic == '/bev/semantic_labels':
                self.semantic_mapping = self._parse_label_json(msg.data)
                continue
            elif topic == '/bev/semantic_labels_bb':
                self.bb_mapping = self._parse_label_json(msg.data)
                continue

            ts = msg.header.stamp.sec * 1e9 + msg.header.stamp.nanosec if hasattr(msg, 'header') else t_msg
            time_key = int(ts / 100_000_000) 

            if time_key not in sync_data:
                sync_data[time_key] = {}
            
            sync_data[time_key][topic] = msg

            # Only save the sample if we have all sensor data AND we have successfully captured our label mappings
            required = ['/camera_front/rgb', '/camera_front/depth', 
                        '/lidar_front/point_cloud', '/bev/semantic_segmentation', '/bev/bbox_2d']
            
            if all(topic in sync_data[time_key] for topic in required):
                if not self.semantic_mapping or not self.bb_mapping:
                    # Skip until we receive the label definitions
                    del sync_data[time_key]
                    continue
                
                self.save_sample(sync_data[time_key])
                del sync_data[time_key]
                
        return self.frame_idx

    def save_sample(self, data):
        prefix = f"{self.frame_idx:06d}"

        if not self.transforms or 'lidar_to_parent' not in self.transforms:
            return

        lidar_matrix = self.transforms['lidar_to_parent']
        cam_matrix = self.transforms['camera_to_parent']

        np.save(f"{self.output_dir}/extrinsics/{prefix}_lidar_to_base.npy", lidar_matrix)
        np.save(f"{self.output_dir}/extrinsics/{prefix}_cam_to_base.npy", cam_matrix)

        rgb_img = np.frombuffer(data['/camera_front/rgb'].data, dtype=np.uint8).reshape((480, 640, 3))
        cv2.imwrite(f"{self.output_dir}/rgb/{prefix}.jpg", cv2.cvtColor(rgb_img, cv2.COLOR_RGB2BGR))

        depth_img = np.frombuffer(data['/camera_front/depth'].data, dtype=np.float32).reshape((480, 640))
        np.save(f"{self.output_dir}/depth/{prefix}.npy", depth_img)

        points = pc2.read_points_numpy(data['/lidar_front/point_cloud'], field_names=("x", "y", "z"))
        points_hom = np.hstack((points, np.ones((points.shape[0], 1))))
        points_transformed = (lidar_matrix @ points_hom.T).T[:, :3]
        np.save(f"{self.output_dir}/lidar/{prefix}.npy", points_transformed)

        processed_label = self.process_bev_logic(data['/bev/semantic_segmentation'], data['/bev/bbox_2d'])
        cv2.imwrite(f"{self.output_dir}/bev_label/{prefix}.png", processed_label)

        if self.frame_idx % 50 == 0:
            print(f"  Saved {self.frame_idx} samples...")
        self.frame_idx += 1

if __name__ == "__main__":
    BAGS_DIR = "bags" 
    OUTPUT_DIR = "dataset/"
    LIDAR_TRANSFORM_PATH = "lidar.yaml"
    CAMERA_TRANSFORM_PATH = "camera.yaml"
    
    # Find all bags in the directory
    bag_paths = sorted(glob.glob(os.path.join(BAGS_DIR, "*")))
    
    if not bag_paths:
        print(f"No bags found in {BAGS_DIR}")
    
    current_frame_idx = 0
    for bag_path in bag_paths:
        extractor = BagDatasetExtractor(
            bag_path=bag_path, 
            output_dir=OUTPUT_DIR,
            lidar_transform_path=LIDAR_TRANSFORM_PATH,
            camera_transform_path=CAMERA_TRANSFORM_PATH,
            start_frame_idx=current_frame_idx
        )
        current_frame_idx = extractor.run() 
        
    print(f"Finished extracting! Total frames processed: {current_frame_idx}")