Подтвердить что ты не робот

Обнаружение сердечного ритма с помощью камеры

Мне нужны те же функции, что и приложение Instant Heart Rate.

Основной процесс требует от пользователя:

  • Нанесите кончик указательного пальца на объектив камеры.
  • Нанесите равномерное давление и накройте весь объектив.
  • Держите его устойчивым в течение 10 секунд и получите частоту сердечных сокращений.

Это можно сделать, включив вспышку и наблюдайте за изменением света, когда кровь перемещается по указательному пальцу.

Как я могу получить данные уровня света из видеозахвата? Где я должен искать это? Я просмотрел класс AVCaptureDevice, но не нашел ничего полезного.

Я также нашел AVCaptureDeviceSubjectAreaDidChangeNotification, было бы полезно?

4b9b3361

Ответ 1

Проверьте это..

// switch on the flash in torch mode  
 if([camera isTorchModeSupported:AVCaptureTorchModeOn]) {  
 [camera lockForConfiguration:nil];  
 camera.torchMode=AVCaptureTorchModeOn;  
 [camera unlockForConfiguration];  
 }  

  [session setSessionPreset:AVCaptureSessionPresetLow];

   // Create the AVCapture Session  
   session = [[AVCaptureSession alloc] init];  

  // Get the default camera device  
   AVCaptureDevice* camera = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];  
  if([camera isTorchModeSupported:AVCaptureTorchModeOn]) {  
    [camera lockForConfiguration:nil];  
  camera.torchMode=AVCaptureTorchModeOn;  
    [camera unlockForConfiguration];  
 }  
 // Create a AVCaptureInput with the camera device  
    NSError *error=nil;  
     AVCaptureInput* cameraInput = [[AVCaptureDeviceInput alloc] initWithDevice:camera error:&error];  
   if (cameraInput == nil) {  
    NSLog(@"Error to create camera capture:%@",error);  
  }  

    // Set the output  
    AVCaptureVideoDataOutput* videoOutput = [[AVCaptureVideoDataOutput alloc] init];  

   // create a queue to run the capture on  
  dispatch_queue_t captureQueue=dispatch_queue_create("catpureQueue", NULL);  

   // setup our delegate  
   [videoOutput setSampleBufferDelegate:self queue:captureQueue];  

    // configure the pixel format  
    videoOutput.videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber     numberWithUnsignedInt:kCVPixelFormatType_32BGRA], (id)kCVPixelBufferPixelFormatTypeKey,  
     nil];  
   // cap the framerate  
   videoOutput.minFrameDuration=CMTimeMake(1, 10);  
  // and the size of the frames we want  
  [session setSessionPreset:AVCaptureSessionPresetLow];  

   // Add the input and output  
   [session addInput:cameraInput];  
   [session addOutput:videoOutput];  

   // Start the session  

    [session startRunning];  

   - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {  



   // this is the image buffer  

  CVImageBufferRef cvimgRef = CMSampleBufferGetImageBuffer(sampleBuffer);  


   // Lock the image buffer  

  CVPixelBufferLockBaseAddress(cvimgRef,0);  


  // access the data  

  int width=CVPixelBufferGetWidth(cvimgRef);  
  int height=CVPixelBufferGetHeight(cvimgRef);  


  // get the raw image bytes  
  uint8_t *buf=(uint8_t *) CVPixelBufferGetBaseAddress(cvimgRef);  
  size_t bprow=CVPixelBufferGetBytesPerRow(cvimgRef);  


// get the average red green and blue values from the image  

 float r=0,g=0,b=0;  
 for(int y=0; y<height; y++) {  
 for(int x=0; x<width*4; x+=4) {  
  b+=buf[x];  
  g+=buf[x+1];  
  r+=buf[x+2];  
 }  
 buf+=bprow;  
 }  
  r/=255*(float) (width*height);  
  g/=255*(float) (width*height);  
  b/=255*(float) (width*height);  

  NSLog(@"%f,%f,%f", r, g, b);  
  }  

Пример кода Здесь

Ответ 2

На самом деле может быть просто, вам нужно проанализировать значения пикселей захваченного изображения. Один простой алгоритм: выбор и область в центре изображения, преобразование в шкалу серого, получение медианного значения пикселя для каждого изображения, и в итоге вы получите 2D-функцию, а на этой функции вычислите расстояние между минимумами или максимум, и проблема решена.

Если вы посмотрите на гистограмму полученных изображений в течение 5 секунд, вы заметите изменения распределения уровня серого. Если вы хотите, чтобы более надежный расчет анализировал гистограмму.

Ответ 3

В качестве дополнительной заметки вам может быть интересен этот исследовательский документ. Этот метод даже не требует пальца (или ничего) непосредственно на объективе.