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
| """ 电容感应乘员分类原理
通过测量座椅表面的电容分布变化,识别乘员类型 """
import numpy as np from typing import Tuple, List
class CapacitiveSensingOCS: """ 电容感应乘员分类系统 基于电容分布矩阵进行乘员类型分类 """ CLASS_EMPTY = 0 CLASS_REAR_FACING = 1 CLASS_FORWARD_FACING = 2 CLASS_CHILD = 3 CLASS_ADULT_SMALL = 4 CLASS_ADULT_LARGE = 5 def __init__(self, grid_size: Tuple[int, int] = (12, 8)): """ Args: grid_size: 电容传感器网格尺寸 (行, 列) """ self.grid_size = grid_size self.num_sensors = grid_size[0] * grid_size[1] self.classifier = self._init_classifier() self.baseline = None def _init_classifier(self): """初始化分类器""" return None def calibrate(self, empty_seat_reading: np.ndarray): """ 校准空座基准 Args: empty_seat_reading: 空座时的电容读数 (rows, cols) """ self.baseline = empty_seat_reading.copy() def classify( self, current_reading: np.ndarray ) -> Tuple[int, float, dict]: """ 分类乘员类型 Args: current_reading: 当前电容读数 (rows, cols) Returns: (class_id, confidence, details) Example: >>> ocs = CapacitiveSensingOCS() >>> reading = np.random.rand(12, 8) # 模拟读数 >>> class_id, conf, details = ocs.classify(reading) """ if self.baseline is None: self.calibrate(current_reading) return self.CLASS_EMPTY, 1.0, {'status': 'calibrated'} delta = current_reading - self.baseline features = self._extract_features(delta) class_id, confidence = self._classify_features(features) details = { 'total_capacitance': float(np.sum(delta)), 'peak_capacitance': float(np.max(delta)), 'occupied_area': int(np.sum(delta > 0.1)), 'centroid': self._calculate_centroid(delta), 'features': features } return class_id, confidence, details def _extract_features(self, delta: np.ndarray) -> dict: """ 提取电容分布特征 特征包括: - 总电容变化量 - 分布形状特征 - 中心位置 - 对称性 """ total_cap = np.sum(delta) peak_cap = np.max(delta) occupied_area = np.sum(delta > 0.1) centroid = self._calculate_centroid(delta) shape_features = self._extract_shape_features(delta) left_right_symmetry = self._calculate_symmetry(delta, axis=1) return { 'total_capacitance': total_cap, 'peak_capacitance': peak_cap, 'occupied_area': occupied_area, 'centroid_x': centroid[0], 'centroid_y': centroid[1], 'shape_aspect_ratio': shape_features['aspect_ratio'], 'shape_compactness': shape_features['compactness'], 'left_right_symmetry': left_right_symmetry } def _calculate_centroid(self, delta: np.ndarray) -> Tuple[float, float]: """计算电容分布重心""" total = np.sum(delta) if total < 1e-6: return (0.0, 0.0) rows, cols = delta.shape row_coords = np.arange(rows) col_coords = np.arange(cols) centroid_row = np.sum(delta * row_coords[:, np.newaxis]) / total centroid_col = np.sum(delta * col_coords[np.newaxis, :]) / total return (float(centroid_col), float(centroid_row)) def _extract_shape_features(self, delta: np.ndarray) -> dict: """提取形状特征""" mask = delta > 0.1 rows, cols = np.where(mask) if len(rows) == 0: return {'aspect_ratio': 0, 'compactness': 0} height = rows.max() - rows.min() + 1 width = cols.max() - cols.min() + 1 aspect_ratio = height / width if width > 0 else 0 area = np.sum(mask) perimeter = self._calculate_perimeter(mask) compactness = 4 * np.pi * area / (perimeter ** 2) if perimeter > 0 else 0 return { 'aspect_ratio': aspect_ratio, 'compactness': compactness } def _calculate_perimeter(self, mask: np.ndarray) -> int: """计算周长(简化版)""" from scipy.ndimage import binary_dilation dilated = binary_dilation(mask) return np.sum(dilated) - np.sum(mask) def _calculate_symmetry(self, delta: np.ndarray, axis: int) -> float: """计算对称性""" if axis == 1: left = delta[:, :delta.shape[1]//2] right = delta[:, delta.shape[1]//2:][:, ::-1] if left.shape != right.shape: right = right[:, :left.shape[1]] diff = np.abs(left - right) return 1.0 - np.mean(diff) / (np.mean(np.abs(left)) + 1e-6) return 0.0 def _classify_features(self, features: dict) -> Tuple[int, float]: """ 基于特征进行分类 使用规则 + 机器学习混合方法 """ total_cap = features['total_capacitance'] peak_cap = features['peak_capacitance'] area = features['occupied_area'] aspect = features['shape_aspect_ratio'] if total_cap < 0.5: return self.CLASS_EMPTY, 0.95 if total_cap > 10 and area < 30 and features['shape_compactness'] > 0.6: return self.CLASS_REAR_FACING, 0.88 if total_cap > 8 and area < 40 and aspect > 1.2: return self.CLASS_FORWARD_FACING, 0.85 if total_cap > 5 and total_cap < 10 and area < 50: return self.CLASS_CHILD, 0.82 if total_cap > 10: if area > 60: return self.CLASS_ADULT_LARGE, 0.90 else: return self.CLASS_ADULT_SMALL, 0.87 return self.CLASS_ADULT_SMALL, 0.5
if __name__ == "__main__": import matplotlib.pyplot as plt ocs = CapacitiveSensingOCS(grid_size=(12, 8)) empty_reading = np.random.rand(12, 8) * 0.1 ocs.calibrate(empty_reading) test_cases = { '空座': np.random.rand(12, 8) * 0.1, '儿童座椅': np.zeros((12, 8)), '儿童': np.zeros((12, 8)), '成人': np.zeros((12, 8)) } test_cases['儿童座椅'][4:8, 3:5] = 2.0 + np.random.rand(4, 2) * 0.5 test_cases['儿童'][3:9, 2:6] = 1.2 + np.random.rand(6, 4) * 0.3 test_cases['成人'][2:10, 1:7] = 1.5 + np.random.rand(8, 6) * 0.5 print("乘员分类测试结果:") print("=" * 60) class_names = { 0: '空座', 1: '后向儿童座椅', 2: '前向儿童座椅', 3: '儿童', 4: '小体型成人', 5: '大体型成人' } for name, reading in test_cases.items(): class_id, conf, details = ocs.classify(reading) print(f"\n{name}:") print(f" 分类: {class_names[class_id]} (置信度: {conf:.2f})") print(f" 总电容: {details['total_capacitance']:.2f}") print(f" 占据面积: {details['occupied_area']}")
|