当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOS利用手机摄像头测心率

iOS利用手机摄像头测心率

2019年07月24日  | 移动技术网移动技术  | 我要评论
原理 简单介绍一下,网上可以查到很多关于手机测心率的这种项目,大概就是: 把手指放在摄像头和闪光灯上,通过手指处脉搏跳动充血导致的细微颜色变化来确定心跳波动,确定波峰

原理

简单介绍一下,网上可以查到很多关于手机测心率的这种项目,大概就是: 把手指放在摄像头和闪光灯上,通过手指处脉搏跳动充血导致的细微颜色变化来确定心跳波动,确定波峰波谷,根据两个波峰之间的时间差来确定瞬时心率。

思路

首先,采集视频流,根据拿到的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) ;
    cgcontextaddlinetopoint(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);
    // 终点
    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);
  }

}

总结

写这个功能的时候,自己有很多思考,也参考了很多其他人的博客、代码还有别人的毕业论文,呵呵呵,还问了几个学医的同学,代码不难,数据处理的部分可能不太好弄,但是写完还是有点成就感的。

代码里还存在很多问题,后期有时间我会慢慢优化,欢迎指正。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网