jacodd commited on
Commit
d46d640
·
verified ·
1 Parent(s): a022872

Upload 2 files

Browse files
Files changed (2) hide show
  1. utils/bag_extractor.py +238 -0
  2. utils/scene_generator.py +296 -0
utils/bag_extractor.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ import cv2
4
+ import numpy as np
5
+ import yaml
6
+ import json
7
+ import rosbag2_py
8
+ from rclpy.serialization import deserialize_message
9
+ from rosidl_runtime_py.utilities import get_message
10
+ import sensor_msgs_py.point_cloud2 as pc2
11
+
12
+ class BagDatasetExtractor:
13
+ def __init__(self, bag_path, output_dir, lidar_transform_path, camera_transform_path, start_frame_idx=0):
14
+ self.bag_path = bag_path
15
+ self.output_dir = output_dir
16
+ self.lidar_transform_path = lidar_transform_path
17
+ self.camera_transform_path = camera_transform_path
18
+ self.frame_idx = start_frame_idx
19
+
20
+ self.prepare_folders()
21
+
22
+ # ROS 2 Bag Reader Setup
23
+ self.reader = rosbag2_py.SequentialReader()
24
+ storage_options = rosbag2_py.StorageOptions(uri=self.bag_path, storage_id='sqlite3')
25
+ converter_options = rosbag2_py.ConverterOptions(
26
+ input_serialization_format='cdr',
27
+ output_serialization_format='cdr'
28
+ )
29
+ self.reader.open(storage_options, converter_options)
30
+
31
+ self.topic_types = {topic.name: topic.type for topic in self.reader.get_all_topics_and_types()}
32
+ self.transforms = self._load_transforms()
33
+
34
+ # Dynamic Mappings
35
+ '''
36
+ 11225069610@A70i:~/Desktop/BEV_EDL/data/bags$ ros2 topic echo --once /bev/semantic_labels
37
+ data: '{"0":{"class":"BACKGROUND"},"1":{"class":"UNLABELLED"},"2":{"class":"leaf"},"3":{"class":"branch"},"4":{"class":"weed"},"5":{"cl...'
38
+ ---
39
+ 11225069610@A70i:~/Desktop/BEV_EDL/data/bags$ ros2 topic echo --once /bev/semantic_labels_bb
40
+ data: '{"0":{"class":"ground"},"1":{"class":"leaf"},"2":{"class":"branch"},"3":{"class":"weed"},"4":{"class":"obstacle"},"time_stamp":{...'
41
+ ---
42
+
43
+ '''
44
+ self.target_classes = {"ground": 0, "leaf": 1, "branch": 2, "weed": 3, "obstacle": 4}
45
+ self.semantic_mapping = {}
46
+ self.bb_mapping = {}
47
+
48
+ def _create_matrix_from_yaml(self, transform_data):
49
+ t = transform_data['transformation']['translation']
50
+ q = transform_data['transformation']['rotation']
51
+
52
+ translation = np.array([t['x'], t['y'], t['z']])
53
+
54
+ x, y, z, w = q['x'], q['y'], q['z'], q['w']
55
+
56
+ # Normalize quaternion
57
+ norm = np.sqrt(x*x + y*y + z*z + w*w)
58
+ if norm == 0:
59
+ # Handle zero-norm quaternion (invalid rotation)
60
+ x, y, z, w = 0, 0, 0, 1
61
+ else:
62
+ x /= norm
63
+ y /= norm
64
+ z /= norm
65
+ w /= norm
66
+
67
+ # Rotation matrix from quaternion
68
+ rotation_matrix = np.array([
69
+ [1 - 2*y*y - 2*z*z, 2*x*y - 2*z*w, 2*x*z + 2*y*w],
70
+ [2*x*y + 2*z*w, 1 - 2*x*x - 2*z*z, 2*y*z - 2*x*w],
71
+ [2*x*z - 2*y*w, 2*y*z + 2*x*w, 1 - 2*x*x - 2*y*y]
72
+ ])
73
+
74
+ # Create 4x4 homogeneous matrix
75
+ matrix = np.eye(4)
76
+ matrix[:3, :3] = rotation_matrix
77
+ matrix[:3, 3] = translation
78
+
79
+ return matrix
80
+
81
+ def _load_transforms(self):
82
+ transforms = {}
83
+ try:
84
+ with open(self.lidar_transform_path, 'r') as f:
85
+ lidar_transform_data = yaml.safe_load(f)
86
+ transforms['lidar_to_parent'] = self._create_matrix_from_yaml(lidar_transform_data)
87
+ with open(self.camera_transform_path, 'r') as f:
88
+ camera_transform_data = yaml.safe_load(f)
89
+ transforms['camera_to_parent'] = self._create_matrix_from_yaml(camera_transform_data)
90
+ except Exception as e:
91
+ print(f"Warning: Transform file issue: {e}")
92
+ return transforms
93
+
94
+ def prepare_folders(self):
95
+ for sub in ['rgb', 'depth', 'lidar', 'bev_label', 'extrinsics']:
96
+ os.makedirs(os.path.join(self.output_dir, sub), exist_ok=True)
97
+
98
+ def _parse_label_json(self, json_str):
99
+ """Extracts the mapping from Isaac Sim JSON string to our fixed IDs."""
100
+ mapping = {}
101
+ try:
102
+ data = json.loads(json_str)
103
+ for key, val in data.items():
104
+ if isinstance(val, dict) and "class" in val:
105
+ class_name = val["class"].lower()
106
+ if class_name in self.target_classes:
107
+ mapping[int(key)] = self.target_classes[class_name]
108
+ except json.JSONDecodeError:
109
+ print(f"Warning: Failed to parse JSON label string: {json_str}")
110
+ return mapping
111
+
112
+ def process_bev_logic(self, semantic_msg, bbox_msg):
113
+ height, width = semantic_msg.height, semantic_msg.width
114
+ semantic_raw = np.frombuffer(semantic_msg.data, dtype=np.int32).reshape((height, width))
115
+
116
+ # 1. Remap Semantic Image
117
+ remapped_semantic = np.full_like(semantic_raw, 3, dtype=np.uint8) # Default 3 (Other/Background)
118
+ for isaac_id, target_id in self.semantic_mapping.items():
119
+ remapped_semantic[semantic_raw == isaac_id] = target_id
120
+
121
+ # 2. Add bounding box centers for branches
122
+ for detection in bbox_msg.detections:
123
+ if detection.results:
124
+ try:
125
+ isaac_class_id = int(detection.results[0].hypothesis.class_id)
126
+ # Use the BB mapping specifically for the bounding boxes
127
+ if self.bb_mapping.get(isaac_class_id) == 2: # 2 is Branch
128
+ center_x = int(detection.bbox.center.position.x)
129
+ center_y = int(detection.bbox.center.position.y)
130
+ cv2.circle(remapped_semantic, (center_x, center_y), radius=3, color=2, thickness=-1)
131
+ except Exception as e:
132
+ continue
133
+
134
+ return remapped_semantic
135
+
136
+ def run(self):
137
+ print(f"Starting extraction for bag: {os.path.basename(self.bag_path)}")
138
+ sync_data = {}
139
+
140
+ # Added the label topics to the filter
141
+ self.reader.set_filter(rosbag2_py.StorageFilter(topics=[
142
+ '/camera_front/rgb', '/camera_front/depth', '/lidar_front/point_cloud',
143
+ '/bev/semantic_segmentation', '/bev/bbox_2d',
144
+ '/bev/semantic_labels', '/bev/semantic_labels_bb'
145
+ ]))
146
+
147
+ while self.reader.has_next():
148
+ (topic, data, t_msg) = self.reader.read_next()
149
+ msg_type = get_message(self.topic_types[topic])
150
+ msg = deserialize_message(data, msg_type)
151
+
152
+ # Update Mappings dynamically if we see the label topics
153
+ if topic == '/bev/semantic_labels':
154
+ self.semantic_mapping = self._parse_label_json(msg.data)
155
+ continue
156
+ elif topic == '/bev/semantic_labels_bb':
157
+ self.bb_mapping = self._parse_label_json(msg.data)
158
+ continue
159
+
160
+ ts = msg.header.stamp.sec * 1e9 + msg.header.stamp.nanosec if hasattr(msg, 'header') else t_msg
161
+ time_key = int(ts / 100_000_000)
162
+
163
+ if time_key not in sync_data:
164
+ sync_data[time_key] = {}
165
+
166
+ sync_data[time_key][topic] = msg
167
+
168
+ # Only save the sample if we have all sensor data AND we have successfully captured our label mappings
169
+ required = ['/camera_front/rgb', '/camera_front/depth',
170
+ '/lidar_front/point_cloud', '/bev/semantic_segmentation', '/bev/bbox_2d']
171
+
172
+ if all(topic in sync_data[time_key] for topic in required):
173
+ if not self.semantic_mapping or not self.bb_mapping:
174
+ # Skip until we receive the label definitions
175
+ del sync_data[time_key]
176
+ continue
177
+
178
+ self.save_sample(sync_data[time_key])
179
+ del sync_data[time_key]
180
+
181
+ return self.frame_idx
182
+
183
+ def save_sample(self, data):
184
+ prefix = f"{self.frame_idx:06d}"
185
+
186
+ if not self.transforms or 'lidar_to_parent' not in self.transforms:
187
+ return
188
+
189
+ lidar_matrix = self.transforms['lidar_to_parent']
190
+ cam_matrix = self.transforms['camera_to_parent']
191
+
192
+ np.save(f"{self.output_dir}/extrinsics/{prefix}_lidar_to_base.npy", lidar_matrix)
193
+ np.save(f"{self.output_dir}/extrinsics/{prefix}_cam_to_base.npy", cam_matrix)
194
+
195
+ rgb_img = np.frombuffer(data['/camera_front/rgb'].data, dtype=np.uint8).reshape((480, 640, 3))
196
+ cv2.imwrite(f"{self.output_dir}/rgb/{prefix}.jpg", cv2.cvtColor(rgb_img, cv2.COLOR_RGB2BGR))
197
+
198
+ depth_img = np.frombuffer(data['/camera_front/depth'].data, dtype=np.float32).reshape((480, 640))
199
+ np.save(f"{self.output_dir}/depth/{prefix}.npy", depth_img)
200
+
201
+ points = pc2.read_points_numpy(data['/lidar_front/point_cloud'], field_names=("x", "y", "z"))
202
+ points_hom = np.hstack((points, np.ones((points.shape[0], 1))))
203
+ points_transformed = (lidar_matrix @ points_hom.T).T[:, :3]
204
+ np.save(f"{self.output_dir}/lidar/{prefix}.npy", points_transformed)
205
+
206
+ processed_label = self.process_bev_logic(data['/bev/semantic_segmentation'], data['/bev/bbox_2d'])
207
+ cv2.imwrite(f"{self.output_dir}/bev_label/{prefix}.png", processed_label)
208
+
209
+ if self.frame_idx % 50 == 0:
210
+ print(f" Saved {self.frame_idx} samples...")
211
+ self.frame_idx += 1
212
+
213
+ if __name__ == "__main__":
214
+ BAGS_DIR = "/home/11225069610/Desktop/BEV_EDL/data/bags"
215
+ OUTPUT_DIR = "/home/11225069610/Desktop/bag_extract/"
216
+ LIDAR_TRANSFORM_PATH = "/home/11225069610/Desktop/BEV_EDL/data/lidar.yaml"
217
+ CAMERA_TRANSFORM_PATH = "/home/11225069610/Desktop/BEV_EDL/data/camera.yaml"
218
+
219
+ # Find all bags in the directory
220
+ bag_paths = sorted(glob.glob(os.path.join(BAGS_DIR, "*")))
221
+
222
+ if not bag_paths:
223
+ print(f"No bags found in {BAGS_DIR}")
224
+
225
+ bag_paths = ["/home/11225069610/Desktop/rosbag2_2026_03_27-16_05_37"]
226
+
227
+ current_frame_idx = 0
228
+ for bag_path in bag_paths:
229
+ extractor = BagDatasetExtractor(
230
+ bag_path=bag_path,
231
+ output_dir=OUTPUT_DIR,
232
+ lidar_transform_path=LIDAR_TRANSFORM_PATH,
233
+ camera_transform_path=CAMERA_TRANSFORM_PATH,
234
+ start_frame_idx=current_frame_idx
235
+ )
236
+ current_frame_idx = extractor.run()
237
+
238
+ print(f"Finished extracting! Total frames processed: {current_frame_idx}")
utils/scene_generator.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import omni
3
+ import random
4
+ import numpy as np
5
+ from pxr import Usd, UsdGeom, Gf, Sdf, UsdShade
6
+ from scipy.spatial.transform import Rotation
7
+
8
+ # --- Asset and Scene Configuration ---
9
+
10
+ CROP_ASSETS = {
11
+ "soybean": ["_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9"],
12
+ "sorghum": ["_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9"],
13
+ "cotton": ["_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9"],
14
+ "corn": ["_1", "_2", "_3", "_4", "_5", "_6", "_61", "_62", "_7", "_71", "_72", "_8", "_81", "_9", "_91", "_92"],
15
+ "cane": ["_1", "_2"]
16
+ }
17
+
18
+ CROP_AGES = {
19
+ "y": ["_1", "_2"],
20
+ "y-m": ["_3", "_4", "_5"],
21
+ "m-l": ["_5", "_6", "_7"],
22
+ "l": ["_8", "_9"]
23
+ }
24
+
25
+ ROW_SPACING = {
26
+ "corn": 0.45,
27
+ "soybean": 0.45,
28
+ "sorghum": 0.45,
29
+ "cotton": 0.9,
30
+ "cane": 1.0
31
+ }
32
+
33
+ WEED_ASSETS = [
34
+ "/World/base/weed/broadleaf_1",
35
+ "/World/base/weed/broadleaf_2",
36
+ "/World/base/weed/grass_1",
37
+ "/World/base/weed/grass_2"
38
+ ]
39
+
40
+ OBSTACLE_ASSETS = [
41
+ "/World/ood/cones/c1",
42
+ "/World/ood/cones/c2",
43
+ "/World/ood/cones/c3",
44
+ "/World/ood/cones/c4",
45
+ "/World/ood/female_adult_police_01_new",
46
+ "/World/ood/male_adult_construction_01_new",
47
+ # "/World/ood/Tractor"
48
+ ]
49
+
50
+ # Weed
51
+ VOLUME_MAPPING = {
52
+ "none": 0,
53
+ "some": 50, # Number of assets to spawn
54
+ "lot": 500
55
+ }
56
+
57
+ OBSTACLE_VOLUME_MAPPING = {
58
+ "none": 0,
59
+ "some": 5,
60
+ "lot": 15
61
+ }
62
+
63
+ TIME_OF_DAY_MAPPING = {
64
+ "early": 85,
65
+ "noon": 0,
66
+ "late": -75
67
+ }
68
+
69
+ #
70
+ GROUND_MATERIALS = [
71
+ "/FlatGrid/Looks/Dirt",
72
+ "/FlatGrid/Looks/Mulch_Brown",
73
+ "/FlatGrid/Looks/Mulch_Dry"
74
+ ]
75
+
76
+ # --- Helper Functions ---
77
+
78
+ def change_ground_material(stage):
79
+ """Changes the ground material using the MaterialBindingAPI."""
80
+ ground_path = "/FlatGrid/Environment"
81
+ ground_prim = stage.GetPrimAtPath(ground_path)
82
+
83
+ if not ground_prim:
84
+ print(f"Ground prim not found at {ground_path}.")
85
+ return
86
+
87
+ material_path = random.choice(GROUND_MATERIALS)
88
+ material_prim = stage.GetPrimAtPath(material_path)
89
+
90
+ if not material_prim:
91
+ print(f"Material prim not found at {material_path}.")
92
+ return
93
+
94
+ # Ensure the target prim is actually a Material
95
+ material = UsdShade.Material(material_prim)
96
+ if not material:
97
+ print(f"Prim at {material_path} is not a valid UsdShadeMaterial.")
98
+ return
99
+
100
+ # Apply the MaterialBindingAPI to the ground prim
101
+ binding_api = UsdShade.MaterialBindingAPI.Apply(ground_prim)
102
+
103
+ # Bind the material.
104
+ # UsdShade.Tokens.strongerThanDescendants ensures this material
105
+ # overrides any materials assigned to child prims.
106
+ binding_api.Bind(material, bindingStrength=UsdShade.Tokens.strongerThanDescendants)
107
+
108
+ print(f"Successfully bound {ground_path} to {material_path}")
109
+
110
+
111
+ def set_time_of_day(stage, time_of_day):
112
+ """Sets the absolute time of day by finding or creating the rotation op."""
113
+ sun_path = "/World/CumulusLight/AxisNorth/AxisLatitude/AxisSHA"
114
+ sun_prim = stage.GetPrimAtPath(sun_path)
115
+
116
+ if not sun_prim:
117
+ print(f"Warning: Sun prim not found at {sun_path}.")
118
+ return
119
+
120
+ angle = TIME_OF_DAY_MAPPING.get(time_of_day, 180)
121
+ xform = UsdGeom.Xformable(sun_prim)
122
+
123
+ # 1. Look for an existing RotateX operation in the stack
124
+ rotate_op = None
125
+ for op in xform.GetOrderedXformOps():
126
+ if op.GetOpType() == UsdGeom.XformOp.TypeRotateX:
127
+ rotate_op = op
128
+ break
129
+
130
+ # 2. If it exists, set the absolute value. If not, create it.
131
+ if rotate_op:
132
+ rotate_op.Set(float(angle))
133
+ else:
134
+ # This adds the op to the stack and sets the initial absolute value
135
+ xform.AddRotateXOp(precision=UsdGeom.XformOp.PrecisionFloat).Set(float(angle))
136
+
137
+ def set_robust_transform(prim, translation=None, rotation_euler=None, scale=None):
138
+ """
139
+ Robustly updates or adds transform operations to a prim.
140
+ Handles existing Ops, different precisions, and Quaternion vs Euler rotations.
141
+ """
142
+ xform = UsdGeom.Xformable(prim)
143
+ # We use this to track which ops we've updated to avoid duplicates
144
+ found_ops = {"translate": None, "rotate": None, "scale": None}
145
+
146
+ for op in xform.GetOrderedXformOps():
147
+ op_type = op.GetOpType()
148
+ if op_type in [UsdGeom.XformOp.TypeTranslate]:
149
+ found_ops["translate"] = op
150
+ elif op_type in [UsdGeom.XformOp.TypeRotateXYZ, UsdGeom.XformOp.TypeOrient]:
151
+ found_ops["rotate"] = op
152
+ elif op_type in [UsdGeom.XformOp.TypeScale]:
153
+ found_ops["scale"] = op
154
+
155
+ # --- Handle Translation ---
156
+ if translation is not None:
157
+ if found_ops["translate"]:
158
+ found_ops["translate"].Set(translation)
159
+ else:
160
+ xform.AddTranslateOp().Set(translation)
161
+
162
+ # --- Handle Rotation (Euler Z to XYZ or Quat) ---
163
+ if rotation_euler is not None:
164
+ z_deg = rotation_euler[2] # Assuming we mostly care about Z for plants
165
+ if found_ops["rotate"]:
166
+ op = found_ops["rotate"]
167
+ attr_type = op.GetAttr().GetTypeName()
168
+
169
+ if attr_type in (Sdf.ValueTypeNames.Quatf, Sdf.ValueTypeNames.Quatd):
170
+ # Convert Euler to Quat
171
+ r = Rotation.from_euler('z', z_deg, degrees=True)
172
+ q = r.as_quat() # x, y, z, w
173
+ quat_val = Gf.Quatd(q[3], q[0], q[1], q[2]) if attr_type == Sdf.ValueTypeNames.Quatd else Gf.Quatf(q[3], q[0], q[1], q[2])
174
+ op.Set(quat_val)
175
+ else:
176
+ # Standard Euler (Vec3f or Vec3d)
177
+ current_rot = op.Get() or Gf.Vec3f(0)
178
+ op.Set(Gf.Vec3f(current_rot[0], current_rot[1], z_deg))
179
+ else:
180
+ xform.AddRotateXYZOp().Set(Gf.Vec3f(0, 0, z_deg))
181
+
182
+ # --- Handle Scale ---
183
+ if scale is not None:
184
+ if found_ops["scale"]:
185
+ found_ops["scale"].Set(scale)
186
+ else:
187
+ xform.AddScaleOp().Set(scale)
188
+
189
+ def scatter_assets(stage, asset_paths, num_assets, area_min, area_max, root_path):
190
+ if num_assets == 0: return
191
+ stage.DefinePrim(root_path, "Xform")
192
+
193
+ for i in range(num_assets):
194
+ asset_path = random.choice(asset_paths)
195
+ new_path = f"{root_path}/item_{i}"
196
+ omni.usd.duplicate_prim(stage, asset_path, new_path)
197
+
198
+ prim = stage.GetPrimAtPath(new_path)
199
+ pos = Gf.Vec3f(random.uniform(area_min[0], area_max[0]),
200
+ random.uniform(area_min[1], area_max[1]), 0)
201
+ rot = Gf.Vec3f(0, 0, random.uniform(0, 360))
202
+
203
+ set_robust_transform(prim, translation=pos, rotation_euler=rot, scale=Gf.Vec3f(1.0))
204
+
205
+ def get_crop_paths (crop_type, crop_age):
206
+ """Get valid prim paths for the selected crop type and age."""
207
+ base_path = f"/World/base/{crop_type}"
208
+ age_suffixes = CROP_AGES.get(crop_age, [])
209
+ available_suffixes = CROP_ASSETS.get(crop_type, [])
210
+ valid_suffixes = [s for s in age_suffixes if s in available_suffixes]
211
+ if not valid_suffixes:
212
+ raise ValueError(f"No assets found for crop {crop_type} with age {crop_age}'.")
213
+ return [f"{base_path}/{suffix}" for suffix in valid_suffixes]
214
+
215
+ def generate_scene(config):
216
+ stage = omni.usd.get_context().get_stage()
217
+ # ... [Config parsing logic] ...
218
+
219
+ # --- Field Generation ---
220
+ root_crop_path = Sdf.Path(f"/root/{config['crop_type']}_{config['crop_age']}_field")
221
+ if stage.GetPrimAtPath(root_crop_path): stage.RemovePrim(root_crop_path)
222
+ stage.DefinePrim(root_crop_path, "Xform")
223
+
224
+ curve_effect = np.sin(np.linspace(0, 6 * np.pi, config["num_plants_in_row"])) * 0.35 if config["curve"] else np.zeros(config["num_plants_in_row"])
225
+
226
+ print(f"Generating {config['num_rows']} rows with {config['num_plants_in_row']} plants each (Curve: {config['curve']})")
227
+
228
+ for i in range(config["num_rows"]):
229
+ for j in range(config["num_plants_in_row"]):
230
+ if random.random() < 0.1: continue
231
+
232
+ new_prim_path = f"{root_crop_path}/row_{i}_plant_{j}"
233
+ omni.usd.duplicate_prim(stage, random.choice(get_crop_paths(config["crop_type"], config["crop_age"])), new_prim_path)
234
+
235
+ prim = stage.GetPrimAtPath(new_prim_path)
236
+
237
+ # Position logic
238
+ offset = random.uniform(-0.02, 0.02)
239
+ x_pos = i * ROW_SPACING.get(config["crop_type"], 0.45) + offset + curve_effect[j]
240
+ y_pos = j * 0.1 + offset
241
+
242
+ # Scale logic
243
+ s = 1.0 + random.uniform(-0.05, 0.05)
244
+
245
+ set_robust_transform(
246
+ prim,
247
+ translation=Gf.Vec3f(x_pos, y_pos, 0),
248
+ rotation_euler=Gf.Vec3f(0, 0, random.uniform(0, 360)),
249
+ scale=Gf.Vec3f(s, s, s)
250
+ )
251
+
252
+ # Scatter Weeds/Obstacles
253
+ field_w = config["num_rows"] * ROW_SPACING.get(config["crop_type"], 0.45)
254
+ field_l = config["num_plants_in_row"] * 0.1
255
+
256
+ print(f"Scattering weeds and obstacles (Weeds: {config['weed_volume']}, Obstacles: {config['obstacle_volume']})")
257
+ scatter_assets(stage, WEED_ASSETS, VOLUME_MAPPING[config["weed_volume"]], (0,0), (field_w, field_l), Sdf.Path("/root/Weeds"))
258
+ print(f"Scattering obstacles (Volume: {config['obstacle_volume']})")
259
+ scatter_assets(stage, OBSTACLE_ASSETS, OBSTACLE_VOLUME_MAPPING[config["obstacle_volume"]], (0,0), (field_w, field_l), Sdf.Path("/root/Obstacles"))
260
+ # print(f"Setting time of day to {config['time_of_day']}")
261
+ # set_time_of_day(stage, config["time_of_day"])
262
+ # print("Changing ground material")
263
+ # change_ground_material(stage)
264
+ print("Scene generation complete!")
265
+
266
+
267
+ # --- USER CONFIGURATION ---
268
+ # Modify the values in this dictionary to change the generated scene.
269
+ CONFIG = {
270
+ "crop_type": "cane", # Options: "soybean", "sorghum", "cotton", "corn"
271
+ "crop_age": "y", # Options: "y", "y-m", "m-l", "l"
272
+ "curve": False, # Options: True or False
273
+ "num_plants_in_row": 250, # Number of plants in each row
274
+ "num_rows": 20, # Number of rows in the field
275
+ "weed_volume": "none", # Options: "none", "some", "lot"
276
+ "obstacle_volume": "none", # Options: "none", "some", "lot"
277
+ "time_of_day": "noon" # Options: "early", "noon", "late"
278
+ }
279
+ # --- END USER CONFIGURATION ---
280
+
281
+ # Execute the scene generation
282
+ generate_scene(CONFIG)
283
+
284
+ # for crop_type in ["soybean", "sorghum", "cotton", "corn"]:
285
+ # for crop_age in ["y", "y-m", "m-l", "l"]:
286
+ # CONFIG = {
287
+ # "crop_type": crop_type,
288
+ # "crop_age": crop_age,
289
+ # "curve": False,
290
+ # "num_plants_in_row": 250,
291
+ # "num_rows": 20,
292
+ # "weed_volume": "some",
293
+ # "obstacle_volume": "some",
294
+ # "time_of_day": "noon"
295
+ # }
296
+ # generate_scene(CONFIG)