前陣子忙著封裝一個用手機鏡頭測心率的模組,緊張到吃飯、通勤、甚至作夢都在想它,前幾天終於搞定,特地寫篇文章慶祝一下。
網路上關於手機測心率這類專案其實不少,核心概念大致是:把手指蓋在鏡頭與閃光燈上,透過指尖因脈搏跳動充血所產生的細微顏色變化來判斷心跳波動,找出波峰與波谷,再依據兩個波峰之間的時間差計算出瞬時心率。
首先擷取影像串流,把取得的 RGB 顏色轉換成 HSV 色彩空間,實際上我們只會用到其中的 H(色相)分量。
對取得的 H 值做一些處理,主要用途是後續繪製折線圖與計算瞬時心率。如果可以的話,建議先濾掉雜訊,因為測量時手指輕微抖動會產生不穩定的數據。
將處理後的 H 值繪製成折線圖,筆者把 H 值與時間戳綁在一起,方便後續計算心率。
根據處理後的 H 值找出波峰與波谷,利用兩個波谷之間的時間差來計算心率。
思路大致如上,接著看看程式碼的具體落地方式。
// 設備 @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];這裡筆者刻意調低了閃光燈亮度、解析度,並降低每秒輸出的幀數,主要都是為了壓低記憶體占用。(手上只有一台 6,其他機型是否可行尚未測試)
// 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;
}
這部分筆者糾結了很久,試了好幾種方法都得不到理想結果,算出來特別不準。後來參考了一篇「基音算法」的文章,雖說一時沒完全讀懂,但覺得很厲害,在此特別感謝。以下用它的思路來找出心率。
原理:先劃出一段時間區間,在裡面找到一個
最低峰值並確定一個週期,然後分別在該峰值前間隔0.5 個週期的1 個週期範圍內、以及該峰值後間隔0.5 個週期的1 個週期範圍內,各找一個最低峰值,再依這幾個值來推算瞬時心率。
- (void)analysisPointsWith:(NSDictionary *)point {
[self.points addObject:point];
if (self.points.count > 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 週期中找最低峰值
// 依 d_i_c 是否距離前後各足夠 1.5 個週期,分成多種邊界情況處理(如不足 0.5 週期、剛好 0.5 週期等)
// ...(此處依上述原理對 d_i_l、d_i_r、trough_l、trough_r 進行賦值)
// 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 次(前提是數據穩定)。若有更好的方法也歡迎推薦。
PS:使用 CoreGraphics 時,繪圖必須在 View 的 drawRect: 方法中進行,否則拿不到畫布。筆者為了封裝,另外建立了一個 UIView 子類。
@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:,或只跑了一次,上網查才知道它會在系統空閒時執行。後來改成回到主線程呼叫就正常了,推測應該與「必須在主線程修改 View」有關。
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);
// 折線顏色
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);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);
}
// 細網格(間距為 grid_w/5)
// ...(以 0.1 線寬重複上述橫豎線繪製即可)
}
沒有華麗的效果圖,只有思路與程式碼。筆者把封裝好的程式碼放在 GitHub 上:https://github.com/YvanLiu/HeartBeatsPlugin.git
撰寫這個功能的過程中參考了許多前輩的部落格、程式碼甚至畢業論文,也請教了幾位學醫的朋友。程式碼本身不算難,棘手的是數據處理那塊,但完成後還是有滿滿的成就感。目前心率計算仍存在一定錯誤率,正在持續改進,歡迎指正與交流。
文章轉自 YvanLiu的簡書