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
| import json import numpy as np import cv2 from pathlib import Path from dataclasses import dataclass from typing import Dict, List, Optional
@dataclass class DMDFrame: """DMD 单帧数据""" frame_id: int timestamp: float distraction_label: Optional[str] drowsiness_level: int gaze_zone: Optional[str] hands_state: Optional[str] rgb_face_path: str rgb_body_path: str rgb_hands_path: str depth_path: Optional[str] ir_path: Optional[str]
class DMDLoader: """DMD 数据集加载器""" def __init__(self, data_root: str): """ Args: data_root: DMD 数据集根目录 """ self.data_root = Path(data_root) self.annotations = self._load_annotations() def _load_annotations(self) -> Dict: """加载标注文件""" annotation_file = self.data_root / 'annotations.json' if annotation_file.exists(): with open(annotation_file, 'r') as f: return json.load(f) return {} def get_frame(self, scenario: str, subject_id: int, frame_id: int) -> DMDFrame: """获取单帧数据 Args: scenario: 'distraction' | 'drowsiness' | 'gaze' | 'hands' subject_id: 受试者 ID frame_id: 帧 ID Returns: DMDFrame: 帧数据 """ subject_dir = self.data_root / scenario / f'subject_{subject_id:03d}' annotation = self.annotations.get(scenario, {}).get(f'subject_{subject_id:03d}', {}) frame_annotation = annotation.get('frames', {}).get(str(frame_id), {}) return DMDFrame( frame_id=frame_id, timestamp=frame_id / 30.0, distraction_label=frame_annotation.get('distraction_label'), drowsiness_level=frame_annotation.get('drowsiness_level', 0), gaze_zone=frame_annotation.get('gaze_zone'), hands_state=frame_annotation.get('hands_state'), rgb_face_path=str(subject_dir / 'face' / f'{frame_id:06d}.jpg'), rgb_body_path=str(subject_dir / 'body' / f'{frame_id:06d}.jpg'), rgb_hands_path=str(subject_dir / 'hands' / f'{frame_id:06d}.jpg'), depth_path=str(subject_dir / 'depth' / f'{frame_id:06d}.raw') if (subject_dir / 'depth').exists() else None, ir_path=str(subject_dir / 'ir' / f'{frame_id:06d}.raw') if (subject_dir / 'ir').exists() else None, ) def load_images(self, frame: DMDFrame) -> Dict[str, np.ndarray]: """加载图像数据 Returns: { 'rgb_face': np.ndarray, 'rgb_body': np.ndarray, 'rgb_hands': np.ndarray, 'depth': np.ndarray (可选), 'ir': np.ndarray (可选) } """ images = {} images['rgb_face'] = cv2.imread(frame.rgb_face_path) images['rgb_body'] = cv2.imread(frame.rgb_body_path) images['rgb_hands'] = cv2.imread(frame.rgb_hands_path) if frame.depth_path: depth_raw = np.fromfile(frame.depth_path, dtype=np.uint16) images['depth'] = depth_raw.reshape((480, 640)) if frame.ir_path: ir_raw = np.fromfile(frame.ir_path, dtype=np.uint8) images['ir'] = ir_raw.reshape((480, 640)) return images def get_sequence(self, scenario: str, subject_id: int, start_frame: int, length: int) -> List[DMDFrame]: """获取帧序列 Args: scenario: 场景类型 subject_id: 受试者 ID start_frame: 起始帧 length: 序列长度 Returns: List[DMDFrame]: 帧序列 """ return [ self.get_frame(scenario, subject_id, start_frame + i) for i in range(length) ]
import torch from torch.utils.data import Dataset, DataLoader
class DMDDataset(Dataset): """DMD PyTorch Dataset""" def __init__(self, data_root: str, scenario: str = 'distraction', transform=None): """ Args: data_root: 数据集根目录 scenario: 'distraction' | 'drowsiness' | 'gaze' | 'hands' transform: 图像变换 """ self.loader = DMDLoader(data_root) self.scenario = scenario self.transform = transform self.samples = self._build_sample_list() self.label_map = self._build_label_map() def _build_sample_list(self) -> List[tuple]: """构建样本列表""" samples = [] scenario_dir = self.loader.data_root / self.scenario if scenario_dir.exists(): for subject_dir in sorted(scenario_dir.glob('subject_*')): face_dir = subject_dir / 'face' if face_dir.exists(): for frame_file in sorted(face_dir.glob('*.jpg')): frame_id = int(frame_file.stem) subject_id = int(subject_dir.name.split('_')[1]) samples.append((subject_id, frame_id)) return samples def _build_label_map(self) -> Dict[str, int]: """构建标签映射""" if self.scenario == 'distraction': return { 'safe_driving': 0, 'talking_phone': 1, 'texting_phone': 2, 'operating_radio': 3, 'drinking': 4, 'eating': 5, 'reaching_behind': 6, 'hair_makeup': 7, 'talking_passenger': 8, } elif self.scenario == 'drowsiness': return { 'alert': 0, 'low_vigilance': 1, 'drowsy': 2, 'sleep': 3, } elif self.scenario == 'gaze': return { 'road': 0, 'left_mirror': 1, 'right_mirror': 2, 'dashboard': 3, 'center_console': 4, 'passenger': 5, } else: return {} def __len__(self): return len(self.samples) def __getitem__(self, idx): subject_id, frame_id = self.samples[idx] frame = self.loader.get_frame(self.scenario, subject_id, frame_id) images = self.loader.load_images(frame) rgb_face = images['rgb_face'] if self.transform: rgb_face = self.transform(rgb_face) if self.scenario == 'distraction': label = frame.distraction_label elif self.scenario == 'drowsiness': label = frame.drowsiness_level elif self.scenario == 'gaze': label = frame.gaze_zone else: label = 0 label_idx = self.label_map.get(label, 0) return { 'image': rgb_face, 'label': torch.tensor(label_idx, dtype=torch.long), 'subject_id': subject_id, 'frame_id': frame_id, }
if __name__ == '__main__': from torchvision import transforms transform = transforms.Compose([ transforms.ToPILImage(), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) dataset = DMDDataset( data_root='/path/to/dmd', scenario='distraction', transform=transform ) dataloader = DataLoader( dataset, batch_size=32, shuffle=True, num_workers=4 ) for batch in dataloader: images = batch['image'] labels = batch['label'] print(f"Batch size: {images.shape[0]}, Labels: {labels}") break
|