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 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
| """ NVIDIA Isaac Sim - Omniverse Replicator数据生成示例 用于生成驾驶员监控模型训练数据 """
import omni.replicator.core as rep from omni.isaac.kit import SimulationApp from pxr import UsdGeom, Gf import numpy as np import json from typing import List, Dict, Any from dataclasses import dataclass, asdict from enum import Enum
class DriverState(Enum): """驾驶员状态""" NORMAL = "normal" FATIGUE = "fatigue" DISTRACTED = "distracted" PHONE_USE = "phone_use"
@dataclass class SyntheticDataConfig: """合成数据配置""" output_dir: str = "./output/dms_dataset" num_frames: int = 10000 image_width: int = 640 image_height: int = 480 num_cameras: int = 3 domain_randomization: bool = True
class DMSDataGenerator: """DMS合成数据生成器""" def __init__(self, config: SyntheticDataConfig = None): self.config = config or SyntheticDataConfig() self.simulation_app = None self.camera_positions = [ (0.3, -0.15, 1.2), (0.3, 0.0, 1.2), (0.3, 0.15, 1.2) ] def initialize(self) -> None: """初始化Isaac Sim""" self.simulation_app = SimulationApp({ "headless": True, "width": self.config.image_width, "height": self.config.image_height }) print("[Isaac Sim] 初始化完成") def create_driver_model(self, driver_id: str, state: DriverState) -> str: """创建驾驶员3D模型""" usd_path = f"/World/Drivers/{driver_id}" return usd_path def create_cabin_environment(self) -> str: """创建座舱环境""" cabin_path = "/World/Cabin" return cabin_path def setup_camera(self, camera_id: int) -> str: """设置摄像头""" camera_path = f"/World/Cameras/Camera_{camera_id}" return camera_path def randomize_environment(self) -> Dict[str, Any]: """环境随机化""" randomization_params = { "lighting": { "intensity": np.random.uniform(100, 500), "color_temperature": np.random.uniform(3000, 7000), "position": np.random.uniform(-5, 5, 3).tolist() }, "background": { "skybox": np.random.choice(["day", "night", "overcast"]), "sun_angle": np.random.uniform(0, 90) }, "cab_in_material": { "color": np.random.choice(["black", "gray", "beige"]), "roughness": np.random.uniform(0.3, 0.9) } } return randomization_params def randomize_driver_pose(self, state: DriverState) -> Dict[str, Any]: """驾驶员姿态随机化""" base_poses = { DriverState.NORMAL: { "head_pitch": np.random.uniform(-10, 10), "head_yaw": np.random.uniform(-15, 15), "eye_gaze": "forward", "eyelid_opening": np.random.uniform(0.8, 1.0) }, DriverState.FATIGUE: { "head_pitch": np.random.uniform(5, 25), "head_yaw": np.random.uniform(-5, 5), "eye_gaze": "down", "eyelid_opening": np.random.uniform(0.3, 0.6) }, DriverState.DISTRACTED: { "head_pitch": np.random.uniform(-20, 10), "head_yaw": np.random.uniform(30, 60), "eye_gaze": "side", "eyelid_opening": np.random.uniform(0.8, 1.0) }, DriverState.PHONE_USE: { "head_pitch": np.random.uniform(15, 35), "head_yaw": np.random.uniform(-30, -15), "eye_gaze": "down", "eyelid_opening": np.random.uniform(0.7, 0.9), "hand_position": "phone" } } pose = base_poses.get(state, base_poses[DriverState.NORMAL]) pose["head_pitch"] += np.random.normal(0, 2) pose["head_yaw"] += np.random.normal(0, 2) return pose def generate_single_frame(self, frame_id: int, driver_state: DriverState) -> Dict[str, Any]: """生成单帧数据""" env_params = self.randomize_environment() pose_params = self.randomize_driver_pose(driver_state) frame_data = { "frame_id": frame_id, "timestamp": frame_id / 30.0, "driver_state": driver_state.value, "environment": env_params, "pose": pose_params, "cameras": {}, "annotations": {} } for cam_id in range(self.config.num_cameras): cam_key = f"camera_{cam_id}" image_path = f"{self.config.output_dir}/images/{frame_id:06d}_cam{cam_id}.png" annotations = { "bounding_box_2d": { "driver": [100, 80, 300, 400], "head": [150, 100, 100, 120] }, "keypoints_2d": { "left_eye": [180, 140], "right_eye": [220, 140], "nose": [200, 170], "mouth_left": [180, 200], "mouth_right": [220, 200] }, "gaze_vector": self._compute_gaze_vector(pose_params), "eyelid_opening": pose_params["eyelid_opening"], "semantic_segmentation": f"{self.config.output_dir}/seg/{frame_id:06d}_cam{cam_id}.png" } frame_data["cameras"][cam_key] = { "image_path": image_path, "intrinsics": [[500, 0, 320], [0, 500, 240], [0, 0, 1]] } frame_data["annotations"][cam_key] = annotations return frame_data def _compute_gaze_vector(self, pose_params: Dict) -> List[float]: """计算注视向量""" gaze_directions = { "forward": [0, 0, -1], "down": [0, 0.3, -0.7], "side": [0.5, 0, -0.7], "up": [0, -0.3, -0.7] } base_gaze = gaze_directions.get(pose_params["eye_gaze"], [0, 0, -1]) noise = np.random.normal(0, 0.05, 3) gaze_vector = np.array(base_gaze) + noise gaze_vector = gaze_vector / np.linalg.norm(gaze_vector) return gaze_vector.tolist() def run_generation(self) -> List[Dict[str, Any]]: """运行数据生成""" print(f"[数据生成] 开始生成 {self.config.num_frames} 帧...") all_frames = [] state_distribution = { DriverState.NORMAL: 0.60, DriverState.FATIGUE: 0.20, DriverState.DISTRACTED: 0.15, DriverState.PHONE_USE: 0.05 } for frame_id in range(self.config.num_frames): driver_state = np.random.choice( list(state_distribution.keys()), p=list(state_distribution.values()) ) frame_data = self.generate_single_frame(frame_id, driver_state) all_frames.append(frame_data) if frame_id % 1000 == 0: print(f" 已生成 {frame_id}/{self.config.num_frames} 帧") print(f"[数据生成] 完成!") return all_frames def export_dataset(self, frames: List[Dict[str, Any]], format: str = "coco") -> None: """导出数据集""" if format == "coco": self._export_coco(frames) elif format == "yolo": self._export_yolo(frames) else: self._export_custom(frames) def _export_coco(self, frames: List[Dict[str, Any]]) -> None: """导出COCO格式""" coco_dataset = { "images": [], "annotations": [], "categories": [ {"id": 1, "name": "driver", "supercategory": "person"}, {"id": 2, "name": "head", "supercategory": "driver"}, {"id": 3, "name": "eye_left", "supercategory": "face"}, {"id": 4, "name": "eye_right", "supercategory": "face"} ] } annotation_id = 1 for frame in frames: for cam_id in range(self.config.num_cameras): cam_key = f"camera_{cam_id}" image_info = { "id": frame["frame_id"] * self.config.num_cameras + cam_id, "file_name": frame["cameras"][cam_key]["image_path"], "width": self.config.image_width, "height": self.config.image_height } coco_dataset["images"].append(image_info) annotations = frame["annotations"][cam_key] for obj_name, bbox in annotations["bounding_box_2d"].items(): category_id = 1 if obj_name == "driver" else 2 annotation = { "id": annotation_id, "image_id": image_info["id"], "category_id": category_id, "bbox": bbox, "area": bbox[2] * bbox[3], "iscrowd": 0, "attributes": { "driver_state": frame["driver_state"], "eyelid_opening": annotations["eyelid_opening"] } } coco_dataset["annotations"].append(annotation) annotation_id += 1 output_path = f"{self.config.output_dir}/annotations_coco.json" with open(output_path, 'w') as f: json.dump(coco_dataset, f, indent=2) print(f"[导出] COCO格式数据集已保存: {output_path}") def _export_yolo(self, frames: List[Dict[str, Any]]) -> None: """导出YOLO格式""" import os images_dir = f"{self.config.output_dir}/images" labels_dir = f"{self.config.output_dir}/labels" os.makedirs(images_dir, exist_ok=True) os.makedirs(labels_dir, exist_ok=True) for frame in frames: for cam_id in range(self.config.num_cameras): cam_key = f"camera_{cam_id}" label_file = f"{labels_dir}/{frame['frame_id']:06d}_cam{cam_id}.txt" annotations = frame["annotations"][cam_key] with open(label_file, 'w') as f: bbox = annotations["bounding_box_2d"]["driver"] x_center = (bbox[0] + bbox[2]/2) / self.config.image_width y_center = (bbox[1] + bbox[3]/2) / self.config.image_height w_norm = bbox[2] / self.config.image_width h_norm = bbox[3] / self.config.image_height f.write(f"0 {x_center:.6f} {y_center:.6f} {w_norm:.6f} {h_norm:.6f}\n") print(f"[导出] YOLO格式数据集已保存") def _export_custom(self, frames: List[Dict[str, Any]]) -> None: """导出自定义格式""" output_path = f"{self.config.output_dir}/dataset_custom.json" with open(output_path, 'w') as f: json.dump(frames, f, indent=2) print(f"[导出] 自定义格式数据集已保存: {output_path}") def shutdown(self) -> None: """关闭Isaac Sim""" if self.simulation_app: self.simulation_app.close() print("[Isaac Sim] 已关闭")
def test_data_generator(): """测试数据生成器""" config = SyntheticDataConfig( output_dir="./test_output/dms_dataset", num_frames=100 ) generator = DMSDataGenerator(config) print("模拟数据生成...") frames = generator.run_generation() print(f"\n生成统计:") print(f" 总帧数: {len(frames)}") state_counts = {} for frame in frames: state = frame["driver_state"] state_counts[state] = state_counts.get(state, 0) + 1 print(f" 状态分布:") for state, count in state_counts.items(): print(f" {state}: {count} ({count/len(frames)*100:.1f}%)") generator.export_dataset(frames, format="coco") generator.export_dataset(frames, format="yolo")
if __name__ == "__main__": test_data_generator()
|