道理
簡略引見一下,網上可以查到許多關於手機測心率的這類項目,年夜概就是: 把手指放在攝像頭和閃光燈上,經由過程手指處脈搏跳動充血招致的纖細色彩變更來肯定心跳動搖,肯定波峰波谷,依據兩個波峰之間的時光差來肯定瞬時心率。
思緒
起首,收集視頻流,依據拿到的RGB色彩轉成HSV色彩集,其實我們只用到了HSV的H。
對拿到的H停止一些處置,看跟人愛好或許詳細情形,重要是用於前面的折線圖和盤算瞬時心率,假如有才能的話可以處置一下樂音數據,由於能夠測的時刻手指稍微發抖會形成一些不穩固的數據。
依據處置後的H便可以停止畫折線圖了,我是把處置後的H和時光戳停止了綁定,用來前面的盤算心率。
依據處置後的H來肯定波峰波谷,應用兩個波谷之間的時光差盤算心率。
完成
年夜致思緒就是下面如許,上面來看一下代碼詳細完成以下。
1.起首我先初始化了一些數據,便利前面應用
// 裝備 @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];
2.設置視頻收集流,為了節儉內存,我沒有輸入視頻畫面
// 開啟閃光燈
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,沒有測其他裝備可弗成以)
3.在output的署理辦法中收集視頻流
// 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;
}
4.剖析數據,盤算心率
這裡我糾結了好長時光,試了幾種分歧的辦法,都沒有一個比擬幻想的成果,盤算出來的特殊禁絕。後來看了 http://IOS.jobbole.com/88158/ 這篇文章,前面優化的部門有一個 基音算法 ,雖不明,但覺厲,對此表現異常感激。吼吼吼。
道理:就是說整齊個時光段,在這個時光段外面找到一個 最低峰值 ,然後肯定一個 周期 ,然後分離在 這個峰值 前距離 0.5個周期 的 1周期裡 和 這個峰值 後距離 0.5個周期 的 1周期 裡找到一個最低峰值。 然後依據這幾個值來肯定瞬時心率。
- (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次每分鐘。(在數據比擬穩固的情形下,假如有更好的辦法請推舉,感謝)
5.畫折線圖 這裡用到了 CoreGraphics
PS:起首,應用這個CoreGraphics要在View外面,而且要在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: 辦法,或許就直走了一次,然後去百度是說 setNeedsDisplay 會在體系余暇的時刻履行 drawRect: ,然後我測驗考試著回歸到主線程中挪用,就行了。詳細緣由不是很清晰,也能夠是由於要在主線程中修正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) ;
CGContextAddL.netoPoint(context, pos_x, pos_y);
pos_x -=6;
}
CGContextStrokePath(context);
c.為了看起來悅目,我還加了網格,固然也是在 drawRect: 中挪用的
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);
// 起點
CGContextAddL.netoPoint(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);
CGContextAddL.netoPoint(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);
}
}
總結
寫這個功效的時刻,本身有許多思慮,也參考了許多其別人的博客、代碼還有他人的卒業論文,呵呵呵,還問了幾個學醫的同窗,代碼不難,數據處置的部門能夠不太好弄,然則寫完照樣有點造詣感的。
代碼裡還存在許多成績,前期有時光我會漸漸優化,迎接斧正。
以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐本站。
【iOS應用手機攝像頭測心率】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!