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 393 394 395 396 397
| """ 基于3D渲染的DMS合成数据生成
使用Blender/Unity等工具渲染车内场景 """
import numpy as np import bpy from typing import Dict, List, Tuple import json
class SyntheticDMSDataGenerator: """ 合成DMS数据生成器 使用Blender渲染车内驾驶员场景 """ def __init__(self, config: dict): self.config = config self.vehicle_interior = None self.driver_model = None self.camera = None self.lighting = None self.output_dir = config.get('output_dir', './synthetic_data') self.resolution = config.get('resolution', (1920, 1080)) def setup_scene(self): """ 设置渲染场景 包括:车内环境、驾驶员模型、摄像头、光照 """ bpy.ops.import_scene.obj(filepath='assets/car_interior.obj') self.vehicle_interior = bpy.context.selected_objects[0] bpy.ops.import_scene.obj(filepath='assets/driver_model.obj') self.driver_model = bpy.context.selected_objects[0] self.camera = self._setup_camera() self._setup_lighting() self._setup_materials() def _setup_camera(self): """设置DMS摄像头位置""" cam_data = bpy.data.cameras.new('DMS_Camera') cam_obj = bpy.data.objects.new('DMS_Camera', cam_data) bpy.context.collection.objects.link(cam_obj) cam_obj.location = (0.5, -0.3, 1.2) cam_obj.rotation_euler = (np.radians(15), 0, 0) cam_data.lens = 35 cam_data.sensor_width = 36 cam_data.sensor_height = 24 return cam_obj def _setup_lighting(self): """设置车内光照""" sun = bpy.data.lights.new('Sun', type='SUN') sun_obj = bpy.data.objects.new('Sun', sun) bpy.context.collection.objects.link(sun_obj) sun_obj.location = (5, -5, 10) ir_light = bpy.data.lights.new('IR_Light', type='POINT') ir_light.color = (0.8, 0.1, 0.1) ir_light.energy = 100 ir_obj = bpy.data.objects.new('IR_Light', ir_light) bpy.context.collection.objects.link(ir_obj) ir_obj.location = self.camera.location def _setup_materials(self): """设置材质""" skin_mat = bpy.data.materials.new('Skin') skin_mat.use_nodes = True bsdf = skin_mat.node_tree.nodes['Principled BSDF'] bsdf.inputs['Base Color'].default_value = (0.8, 0.6, 0.5, 1) for obj in self.driver_model.children: if 'skin' in obj.name.lower(): obj.data.materials.append(skin_mat) def generate_drowsiness_sequence(self, duration_sec: int = 30, drowsiness_level: float = 0.5) -> Dict: """ 生成疲劳驾驶序列 Args: duration_sec: 序列时长(秒) drowsiness_level: 疲劳程度 (0-1) Returns: metadata: 序列元数据 """ fps = 30 total_frames = duration_sec * fps frames = [] labels = [] for frame_idx in range(total_frames): self._update_driver_pose(frame_idx, drowsiness_level) image_path = f'{self.output_dir}/frame_{frame_idx:06d}.png' self._render_frame(image_path) annotation = self._get_annotation() frames.append(image_path) labels.append(annotation) metadata = { 'duration_sec': duration_sec, 'fps': fps, 'drowsiness_level': drowsiness_level, 'frames': frames, 'labels': labels } with open(f'{self.output_dir}/metadata.json', 'w') as f: json.dump(metadata, f, indent=2) return metadata def _update_driver_pose(self, frame_idx: int, drowsiness_level: float): """ 更新驾驶员姿态 根据疲劳程度调整: - 眼睛闭合度 - 头部位置 - 眨眼频率 """ eye_closure = drowsiness_level * (0.5 + 0.5 * np.sin(frame_idx * 0.1)) self.driver_model.shape_key_add(f'eye_closure_{eye_closure:.2f}') head_drop = drowsiness_level * 0.1 * frame_idx / 900 head_bone = self.driver_model.pose.bones['Head'] head_bone.rotation_euler = (np.radians(15 + head_drop * 30), 0, 0) jitter = drowsiness_level * np.random.normal(0, 0.01, 3) head_bone.location += jitter def _render_frame(self, output_path: str): """渲染单帧""" bpy.context.scene.render.resolution_x = self.resolution[0] bpy.context.scene.render.resolution_y = self.resolution[1] bpy.context.scene.render.filepath = output_path bpy.ops.render.render(write_still=True) def _get_annotation(self) -> Dict: """ 获取精确标注 3D模型自带精确的标注信息 """ landmarks_2d = self._project_landmarks_to_2d() gaze_direction = self._get_gaze_direction() head_pose = self._get_head_pose() eye_state = self._get_eye_state() return { 'landmarks': landmarks_2d.tolist(), 'gaze_direction': gaze_direction, 'head_pose': head_pose, 'eye_state': eye_state } def _project_landmarks_to_2d(self) -> np.ndarray: """将3D关键点投影到2D""" landmarks_3d = self._get_3d_landmarks() K = self._get_camera_intrinsics() R, t = self._get_camera_extrinsics() landmarks_2d = [] for point_3d in landmarks_3d: point_3d_h = np.append(point_3d, 1) point_2d_h = K @ (R @ point_3d_h + t) point_2d = point_2d_h[:2] / point_2d_h[2] landmarks_2d.append(point_2d) return np.array(landmarks_2d) def _get_3d_landmarks(self) -> np.ndarray: """获取面部68个关键点的3D坐标""" landmarks_template = np.load('assets/face_landmarks_template.npy') head_bone = self.driver_model.pose.bones['Head'] transform = head_bone.matrix landmarks_3d = [] for lm in landmarks_template: lm_h = np.append(lm, 1) lm_transformed = transform @ lm_h landmarks_3d.append(lm_transformed[:3]) return np.array(landmarks_3d) def _get_gaze_direction(self) -> Tuple[float, float]: """获取视线方向""" head_bone = self.driver_model.pose.bones['Head'] forward = head_bone.matrix @ np.array([0, 0, -1, 0]) yaw = np.arctan2(forward[0], forward[2]) pitch = np.arcsin(forward[1]) return (float(yaw), float(pitch)) def _get_head_pose(self) -> Tuple[float, float, float]: """获取头部姿态(欧拉角)""" head_bone = self.driver_model.pose.bones['Head'] return tuple(np.degrees(head_bone.rotation_euler)) def _get_eye_state(self) -> Dict: """获取眼睛状态""" left_eye_closure = self.driver_model.data.shape_keys.key_blocks['LeftEyeClosure'].value right_eye_closure = self.driver_model.data.shape_keys.key_blocks['RightEyeClosure'].value return { 'left_eye_closure': left_eye_closure, 'right_eye_closure': right_eye_closure, 'blink_rate': self._estimate_blink_rate() } def _estimate_blink_rate(self) -> float: """估计眨眼频率""" pass def _get_camera_intrinsics(self) -> np.ndarray: """获取相机内参矩阵""" fx = fy = 1000 cx, cy = self.resolution[0] / 2, self.resolution[1] / 2 K = np.array([ [fx, 0, cx], [0, fy, cy], [0, 0, 1] ]) return K def _get_camera_extrinsics(self) -> Tuple[np.ndarray, np.ndarray]: """获取相机外参(旋转和平移)""" cam_matrix = self.camera.matrix_world R = cam_matrix[:3, :3].T t = cam_matrix[:3, 3] return R, t
class SyntheticDataAugmentation: """ 合成数据增强 增加合成数据的多样性 """ def __init__(self): self.augmentations = [ self._randomize_skin_tone, self._randomize_hair_style, self._randomize_accessories, self._randomize_lighting, self._randomize_weather ] def apply_random_augmentations(self, driver_model, num_augmentations: int = 3): """随机应用增强""" selected = np.random.choice( self.augmentations, size=num_augmentations, replace=False ) for aug in selected: aug(driver_model) def _randomize_skin_tone(self, driver_model): """随机肤色""" skin_tones = [ (0.9, 0.7, 0.6), (0.8, 0.6, 0.5), (0.6, 0.4, 0.3), ] selected_tone = skin_tones[np.random.randint(len(skin_tones))] pass def _randomize_hair_style(self, driver_model): """随机发型""" pass def _randomize_accessories(self, driver_model): """随机配饰(眼镜、墨镜等)""" accessories = ['none', 'glasses', 'sunglasses', 'hat'] selected = np.random.choice(accessories) if selected != 'none': pass def _randomize_lighting(self, scene): """随机光照条件""" conditions = ['day', 'night', 'tunnel', 'dawn', 'dusk'] selected = np.random.choice(conditions) pass def _randomize_weather(self, scene): """随机天气""" weathers = ['clear', 'cloudy', 'rainy', 'sunny'] selected = np.random.choice(weathers) pass
if __name__ == "__main__": config = { 'output_dir': './synthetic_dms_data', 'resolution': (1920, 1080) } generator = SyntheticDMSDataGenerator(config) generator.setup_scene() for drowsiness in [0.2, 0.5, 0.8]: metadata = generator.generate_drowsiness_sequence( duration_sec=30, drowsiness_level=drowsiness ) print(f"生成序列: 疲劳程度={drowsiness}, 帧数={len(metadata['frames'])}")
|