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
| import numpy as np from scipy.signal import welch, butter, filtfilt from dataclasses import dataclass
@dataclass class rPPGSignal: """rPPG信号段""" raw: np.ndarray fps: int duration_sec: float
class SignalQualityAssessor: """ rPPG信号质量机器学习评估 论文方法:从rPPG信号中提取质量指标, 用机器学习分类器判定信号质量等级 """ def __init__(self, fs: int = 30): self.fs = fs def extract_quality_features(self, rppg: np.ndarray) -> dict: """ 提取信号质量特征 Args: rppg: [N] rPPG信号段 Returns: features: dict of quality metrics """ N = len(rppg) freqs, psd = welch(rppg, fs=self.fs, nperseg=min(256, N)) hr_mask = (freqs >= 0.7) & (freqs <= 4.0) hr_power = np.sum(psd[hr_mask]) total_power = np.sum(psd) + 1e-8 spectral_ratio = hr_power / total_power if np.any(psd[hr_mask] > 0): peak_freq = freqs[hr_mask][np.argmax(psd[hr_mask])] else: peak_freq = 0 peak_idx = np.argmax(psd[hr_mask]) peak_width = self._peak_width(freqs[hr_mask], psd[hr_mask], peak_idx) spectral_concentration = 1.0 / (1.0 + peak_width) amplitude = np.std(rppg) zero_crossings = np.sum(np.diff(np.sign(rppg)) != 0) zcr = zero_crossings / N noise_power = total_power - hr_power snr = 10 * np.log10(hr_power / (noise_power + 1e-8)) motion_mask = freqs > 4.0 motion_power = np.sum(psd[motion_mask]) motion_ratio = motion_power / total_power t = np.arange(N) trend_coef = np.polyfit(t, rppg, 1)[0] trend_ratio = abs(trend_coef * N) / (np.std(rppg) + 1e-8) autocorr = np.correlate(rppg - np.mean(rppg), rppg - np.mean(rppg), mode='full') autocorr = autocorr[N-1:] / autocorr[N-1] periodicity = 0 for lag in range(int(0.5 * self.fs), int(3.0 * self.fs)): if lag < len(autocorr): if autocorr[lag] > periodicity: periodicity = autocorr[lag] return { 'spectral_ratio': spectral_ratio, 'peak_freq': peak_freq, 'spectral_concentration': spectral_concentration, 'amplitude': amplitude, 'zcr': zcr, 'snr': snr, 'motion_ratio': motion_ratio, 'trend_ratio': trend_ratio, 'periodicity': periodicity, } def classify_quality(self, features: dict) -> dict: """ 机器学习分类信号质量 Returns: {'quality': str, 'confidence': float, 'usable': bool} """ score = 0 if features['spectral_ratio'] > 0.3: score += 2 elif features['spectral_ratio'] > 0.15: score += 1 if features['snr'] > 3.0: score += 2 elif features['snr'] > 0.0: score += 1 if features['motion_ratio'] < 0.2: score += 2 elif features['motion_ratio'] < 0.4: score += 1 if features['periodicity'] > 0.5: score += 2 elif features['periodicity'] > 0.3: score += 1 if features['trend_ratio'] < 0.5: score += 1 if score >= 7: quality = 'Excellent' confidence = 0.9 usable = True elif score >= 5: quality = 'Good' confidence = 0.75 usable = True elif score >= 3: quality = 'Fair' confidence = 0.5 usable = False else: quality = 'Poor' confidence = 0.2 usable = False return { 'quality': quality, 'confidence': confidence, 'usable': usable, 'score': score, } def _peak_width(self, freqs, psd, peak_idx, threshold=0.5): """计算峰宽""" peak_val = psd[peak_idx] half_max = peak_val * threshold left = peak_idx while left > 0 and psd[left] > half_max: left -= 1 right = peak_idx while right < len(psd) - 1 and psd[right] > half_max: right += 1 return freqs[right] - freqs[left]
if __name__ == "__main__": assessor = SignalQualityAssessor(fs=30) t = np.arange(900) / 30 clean_rppg = 0.5 * np.sin(2 * np.pi * 1.2 * t) clean_rppg += 0.05 * np.random.randn(900) features_clean = assessor.extract_quality_features(clean_rppg) result_clean = assessor.classify_quality(features_clean) print("高质量信号:") print(f" 质量: {result_clean['quality']}") print(f" 可用: {result_clean['usable']}") print(f" SNR: {features_clean['snr']:.1f}dB") print(f" 周期性: {features_clean['periodicity']:.2f}") noisy_rppg = 0.1 * np.sin(2 * np.pi * 1.2 * t) noisy_rppg += 0.5 * np.random.randn(900) noisy_rppg += 0.3 * np.sin(2 * np.pi * 8 * t) features_noisy = assessor.extract_quality_features(noisy_rppg) result_noisy = assessor.classify_quality(features_noisy) print("\n低质量信号:") print(f" 质量: {result_noisy['quality']}") print(f" 可用: {result_noisy['usable']}") print(f" SNR: {features_noisy['snr']:.1f}dB") print(f" 运动比: {features_noisy['motion_ratio']:.2f}")
|