網路上關於手機測心率的專案不少,核心原理大致相同:把手指蓋在鏡頭與閃光燈上,指尖因脈搏而充血,會讓透光顏色產生極細微的週期性變化;擷取這個變化、找出波峰與波谷,再用兩個波峰之間的時間差換算成瞬時心率。
// 設備 @property (strong, nonatomic) AVCaptureDevice *device; // 結合輸入輸出 @property (strong, nonatomic) AVCaptureSession *session; // 輸入設備 @property (strong, nonatomic) AVCaptureDeviceInput *input; // 輸出設備 @property (strong, nonatomic) AVCaptureVideoDataOutput *output; // 輸出的所有點 @property (strong, nonatomic) NSMutableArray *points; // 記錄浮點變化的前一次的值 static float lastH = 0; // 用於判斷是否是第一個福點值 static int count = 0; // 初始化 self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; self.session = [[AVCaptureSession alloc]init]; self.input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:nil]; self.output = [[AVCaptureVideoDataOutput alloc]init]; self.points = [[NSMutableArray alloc]init];
這裡有個實務上的取捨:不顯示預覽畫面,並刻意調降閃光燈亮度、解析度與每秒幀數,主要都是為了壓低記憶體佔用與發熱。
// 開啟閃光燈 if ([self.device isTorchModeSupported:AVCaptureTorchModeOn]) { [self.device lockForConfiguration:nil]; // 開啟閃光燈 self.device.torchMode=AVCaptureTorchModeOn; // 調低閃光燈亮度(為了減少內存占用和避免時間長手機發燙) [self.device setTorchModeOnWithLevel:0.01 error:nil]; [self.device unlockForConfiguration]; } // 開始配置input output [self.session beginConfiguration]; // 設置像素輸出格式 NSNumber *BGRA32Format = [NSNumber numberWithInt:kCVPixelFormatType_32BGRA]; NSDictionary *setting =@{(id)kCVPixelBufferPixelFormatTypeKey:BGRA32Format}; [self.output setVideoSettings:setting]; // 拋棄延遲的幀 [self.output setAlwaysDiscardsLateVideoFrames:YES]; //開啟攝像頭采集圖像輸出的子線程 dispatch_queue_t outputQueue = dispatch_queue_create("VideoDataOutputQueue", DISPATCH_QUEUE_SERIAL); // 設置子線程執行代理方法 [self.output setSampleBufferDelegate:self queue:outputQueue]; // 向session添加 if ([self.session canAddInput:self.input]) [self.session addInput:self.input]; if ([self.session canAddOutput:self.output]) [self.session addOutput:self.output]; // 降低分辨率,減少采樣率(為了減少內存占用) self.session.sessionPreset = AVCaptureSessionPreset1280x720; // 設置最小的視頻幀輸出間隔 self.device.activeVideoMinFrameDuration = CMTimeMake(1, 10); // 用當前的output 初始化connection AVCaptureConnection *connection =[self.output connectionWithMediaType:AVMediaTypeVideo]; [connection setVideoOrientation:AVCaptureVideoOrientationPortrait]; // 完成編輯 [self.session commitConfiguration]; // 開始運行 [self.session startRunning];
// captureOutput->當前output sampleBuffer->樣本緩沖 connection->捕獲連接 - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection { //獲取圖層緩沖 CVPixelBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); CVPixelBufferLockBaseAddress(imageBuffer, 0); uint8_t*buf = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer); size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); size_t width = CVPixelBufferGetWidth(imageBuffer); size_t height = CVPixelBufferGetHeight(imageBuffer); float r = 0, g = 0,b = 0; float h,s,v; // 計算RGB TORGB(buf, width, height, bytesPerRow, &r, &g, &b); // RGB轉HSV RGBtoHSV(r, g, b, &h, &s, &v); // 獲取當前時間戳(精確到毫秒) double t = [[NSDate date] timeIntervalSince1970]*1000; // 返回處理後的浮點值 float p = HeartRate(h); // 綁定浮點和時間戳 NSDictionary *point = @{[NSNumber numberWithDouble:t]:[NSNumber numberWithFloat:p]}; //下面按個人情況可以進行計算心率或者畫心率圖 }
到這一步資料已整理完成,後續就能拿來算心率或繪製折線圖。
計算 RGB
void TORGB (uint8_t *buf, float ww, float hh, size_t pr, float *r, float *g, float *b) { float wh = (float)(ww * hh ); for(int y = 0; y < hh; y++) { for(int x = 0; x < ww * 4; x += 4) { *b += buf[x]; *g += buf[x+1]; *r += buf[x+2]; } buf += pr; } *r /= 255 * wh; *g /= 255 * wh; *b /= 255 * wh; }
RGB 轉 HSV
void RGBtoHSV( float r, float g, float b, float *h, float *s, float *v ) { float min, max, delta; min = MIN( r, MIN(g, b )); max = MAX( r, MAX(g, b )); *v = max; delta = max - min; if( max != 0 ) *s = delta / max; else { *s = 0; *h = -1; return; } if( r == max ) *h = ( g - b ) / delta; else if( g == max ) *h = 2 + (b - r) / delta; else *h = 4 + (r - g) / delta; *h *= 60; if( *h < 0 ) *h += 360; }
把 H 轉成差值
float HeartRate (float h) { float low = 0; count++; lastH = (count==1)?h:lastH; low = (h-lastH); lastH = h; return low; }
這一段是整個功能最難調的部分。筆者試了幾種算法都不理想,數值偏差明顯,後來參考了他人的分享,採用類似基音偵測的思路,效果才穩定下來。
做法是:先在一個時間窗口內找出最低峰值,並定義一個週期 T;接著在該峰值前間隔 0.5T 到 1.5T 的區間、以及後間隔 0.5T 到 1.5T 的區間各找一個最低峰值,最後用這幾個點的時間差推估瞬時心率。
- (void)analysisPointsWith:(NSDictionary *)point { [self.points addObject:point]; if (self.points.count<=30) return; int count = (int)self.points.count; if (self.points.count%10 == 0) { int d_i_c = 0; //最低峰值的位置 姑且算在中間位置 c->center int d_i_l = 0; //最低峰值左面的最低峰值位置 l->left int d_i_r = 0; //最低峰值右面的最低峰值位置 r->right float trough_c = 0; //最低峰值的浮點值 float trough_l = 0; //最低峰值左面的最低峰值浮點值 float trough_r = 0; //最低峰值右面的最低峰值浮點值 // 1.先確定數據中的最低峰值 for (int i = 0; i < count; i++) { float trough = [[[self.points[i] allObjects] firstObject] floatValue]; if (trough < trough_c) { trough_c = trough; d_i_c = i; } } // 2.找到最低峰值以後 以最低峰值為中心 找到前0.5-1.5周期中的最低峰值 和後0.5-1.5周期的最低峰值 if (d_i_c >= 1.5*T) { // a.如果最低峰值處在中心位置, 即距離前後都至少有1.5個周期 if (d_i_c <= count-1.5*T) { // 左面最低峰值 for (int j = d_i_c - 0.5*T; j > d_i_c - 1.5*T; j--) { float trough = [[[self.points[j] allObjects] firstObject] floatValue]; if (trough < trough_l) { trough_l = trough; d_i_l = j; } } // 右面最低峰值 for (int k = d_i_c + 0.5*T; k < d_i_c + 1.5*T; k++) { float trough = [[[self.points[k] allObjects] firstObject] floatValue]; if (trough < trough_r) { trough_r = trough; d_i_r = k; } } } // b.如果最低峰值右面不夠1.5個周期 分兩種情況 不夠0.5個周期和夠0.5個周期 else { // b.1 夠0.5個周期 if (d_i_c <count-0.5*T) { // 左面最低峰值 for (int j = d_i_c - 0.5*T; j > d_i_c - 1.5*T; j--) { float trough = [[[self.points[j] allObjects] firstObject] floatValue]; if (trough < trough_l) { trough_l = trough; d_i_l = j; } } // 右面最低峰值 for (int k = d_i_c + 0.5*T; k < count; k++) { float trough = [[[self.points[k] allObjects] firstObject] floatValue]; if (trough < trough_r) { trough_r = trough; d_i_r = k; } } } // b.2 不夠0.5個周期 else { // 左面最低峰值 for (int j = d_i_c - 0.5*T; j > d_i_c - 1.5*T; j--) { float trough = [[[self.points[j] allObjects] firstObject] floatValue]; if (trough < trough_l) { trough_l = trough; d_i_l = j; } } } } } // c. 如果左面不夠1.5個周期 一樣分兩種情況 夠0.5個周期 不夠0.5個周期 else { // c.1 夠0.5個周期 if (d_i_c>0.5*T) { // 左面最低峰值 for (int j = d_i_c - 0.5*T; j > 0; j--) { float trough = [[[self.points[j] allObjects] firstObject] floatValue]; if (trough < trough_l) { trough_l = trough; d_i_l = j; } } // 右面最低峰值 for (int k = d_i_c + 0.5*T; k < d_i_c + 1.5*T; k++) { float trough = [[[self.points[k] allObjects] firstObject] floatValue]; if (trough < trough_r) { trough_r = trough; d_i_r = k; } } } // c.2 不夠0.5個周期 else { // 右面最低峰值 for (int k = d_i_c + 0.5*T; k < d_i_c + 1.5*T; k++) { float trough = [[[self.points[k] allObjects] firstObject] floatValue]; if (trough < trough_r) { trough_r = trough; d_i_r = k; } } } } // 3. 確定哪一個與最低峰值更接近 用最接近的一個最低峰值測出瞬時心率 60*1000兩個峰值的時間差 if (trough_l-trough_c < trough_r-trough_c) { NSDictionary *point_c = self.points[d_i_c]; NSDictionary *point_l = self.points[d_i_l]; double t_c = [[[point_c allKeys] firstObject] doubleValue]; double t_l = [[[point_l allKeys] firstObject] doubleValue]; NSInteger fre = (NSInteger)(60*1000)/(t_c - t_l); if (self.frequency) self.frequency(fre); if ([self.delegate respondsToSelector:@selector(startHeartDelegateRateFrequency:)]) [self.delegate startHeartDelegateRateFrequency:fre]; } else { NSDictionary *point_c = self.points[d_i_c]; NSDictionary *point_r = self.points[d_i_r]; double t_c = [[[point_c allKeys] firstObject] doubleValue]; double t_r = [[[point_r allKeys] firstObject] doubleValue]; NSInteger fre = (NSInteger)(60*1000)/(t_r - t_c); if (self.frequency) self.frequency(fre); if ([self.delegate respondsToSelector:@selector(startHeartDelegateRateFrequency:)]) [self.delegate startHeartDelegateRateFrequency:fre]; } // 4.刪除過期數據 for (int i = 0; i< 10; i++) { [self.points removeObjectAtIndex:0]; } } }
目前取的是左右兩側峰值中,與中心最低峰值最接近的那一個來算時間差。實測與其他 App 比對,誤差大致在每分鐘 1 到 2 次以內(前提是取樣數據夠穩定)。若有更好的做法也歡迎推薦。
使用 CoreGraphics 有個前提:繪製程式碼必須寫在 view 的 drawRect: 中,否則取不到畫布。因此筆者另外封裝了一個 UIView 子類。
a. 準備資料並觸發重繪
@property (strong, nonatomic) NSMutableArray *points; // 在init中初始化數組 self.points = [[NSMutableArray alloc]init]; // 這個可以翻譯過來,也是在init中 self.clearsContextBeforeDrawing = YES; // 外部調用方法 - (void)drawRateWithPoint:(NSNumber *)point { // 倒敘插入數組 [self.points insertObject:point atIndex:0]; // 刪除溢出屏幕數據 if (self.points.count > self.frame.size.width/6) { [self.points removeLastObject]; } dispatch_async(dispatch_get_main_queue(), ^{ // 這個方法自動調取 drawRect:方法 [self setNeedsDisplay]; }); }
這裡有個小插曲:先前直接呼叫 setNeedsDisplay,drawRect: 遲遲不觸發或只跑一次。查資料得知它會在系統空閒時才執行,於是嘗試切回主線程呼叫,問題就解決了。合理推測與 UIKit 要求在主線程操作 view 有關。
b. 畫折線
CGFloat ww = self.frame.size.width; CGFloat hh = self.frame.size.height; CGFloat pos_x = ww; CGFloat pos_y = hh/2; // 獲取當前畫布 CGContextRef context = UIGraphicsGetCurrentContext(); // 折線寬度 CGContextSetLineWidth(context, 1.0); //消除鋸齒 //CGContextSetAllowsAntialiasing(context,false); // 折線顏色 CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); CGContextMoveToPoint(context, pos_x, pos_y); for (int i = 0; i < self.points.count; i++) { float h = [self.points[i] floatValue]; pos_y = hh/2 + (h * hh/2) ; CGContextAddLineToPoint(context, pos_x, pos_y); pos_x -=6; } CGContextStrokePath(context);
c. 加上網格背景
static CGFloat grid_w = 30.0f; - (void)buildGrid { CGFloat wight = self.frame.size.width; CGFloat height = self.frame.size.height; // 獲取當前畫布 CGContextRef context = UIGraphicsGetCurrentContext(); CGFloat pos_x = 0.0f; CGFloat pos_y = 0.0f; // 在wight范圍內畫豎線 while (pos_x < wight) { // 設置網格線寬度 CGContextSetLineWidth(context, 0.2); // 設置網格線顏色 CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor); // 起點 CGContextMoveToPoint(context, pos_x, 1.0f); // 終點 CGContextAddLineToPoint(context, pos_x, height); pos_x +=grid_w; //開始劃線 CGContextStrokePath(context); } // 在height范圍內畫橫線 while (pos_y < height) { CGContextSetLineWidth(context, 0.2); CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor); CGContextMoveToPoint(context, 1.0f, pos_y); CGContextAddLineToPoint(context, wight, pos_y); pos_y +=grid_w; CGContextStrokePath(context); } pos_x = 0.0f; pos_y = 0.0f; // 在wight范圍內畫豎線 while (pos_x < wight) { CGContextSetLineWidth(context, 0.1); CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor); CGContextMoveToPoint(context, pos_x, 1.0f); CGContextAddLineToPoint(context, pos_x, height); pos_x +=grid_w/5; CGContextStrokePath(context); } // 在height范圍內畫橫線 while (pos_y < height) { CGContextSetLineWidth(context, 0.1); CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor); CGContextMoveToPoint(context, 1.0f, pos_y); CGContextAddLineToPoint(context, wight, pos_y); pos_y +=grid_w/5; CGContextStrokePath(context); } }
寫這個功能的過程中參考了不少他人的文章、程式碼與畢業論文,也請教了幾位學醫的朋友。程式碼本身不算難,真正棘手的是資料處理與峰值判斷——雜訊、抖動、不同機型的光照差異都會影響結果。完成之後還算有成就感,程式碼仍有許多可優化之處,後續會慢慢調整,也歡迎指正。