浅析Python+OpenCV使用摄像头追踪人脸面部血液变化实现脉搏评估

使用摄像头追踪人脸由于血液流动引起的面部色素的微小变化实现实时脉搏评估。

效果如下(演示视频):

由于这是通过比较面部色素的变化评估脉搏所以光线、人体移动、不同角度、不同电脑摄像头等因素均会影响评估效果,实验原理是面部色素对比,识别效果存在一定误差,各位小伙伴且当娱乐,代码如下:

import cv2
import numpy as np
import dlib
import time
from scipy import signal
# Constants
WINDOW_TITLE = 'Pulse Observer'
BUFFER_MAX_SIZE = 500  # Number of recent ROI average values to store
MAX_VALUES_TO_GRAPH = 50 # Number of recent ROI average values to show in the pulse graph
MIN_HZ = 0.83  # 50 BPM - minimum allowed heart rate
MAX_HZ = 3.33  # 200 BPM - maximum allowed heart rate
MIN_FRAMES = 100 # Minimum number of frames required before heart rate is computed. Higher values are slower, but
     # more accurate.
DEBUG_MODE = False
# Creates the specified Butterworth filter and applies it.
def butterworth_filter(data, low, high, sample_rate, order=5):
 nyquist_rate = sample_rate * 0.5
 low /= nyquist_rate
 high /= nyquist_rate
 b, a = signal.butter(order, [low, high], btype='band')
 return signal.lfilter(b, a, data)
# Gets the region of interest for the forehead.
def get_forehead_roi(face_points):
 # Store the points in a Numpy array so we can easily get the min and max for x and y via slicing
 points = np.zeros((len(face_points.parts()), 2))
 for i, part in enumerate(face_points.parts()):
  points[i] = (part.x, part.y)
 min_x = int(points[21, 0])
 min_y = int(min(points[21, 1], points[22, 1]))
 max_x = int(points[22, 0])
 max_y = int(max(points[21, 1], points[22, 1]))
 left = min_x
 right = max_x
 top = min_y - (max_x - min_x)
 bottom = max_y * 0.98
 return int(left), int(right), int(top), int(bottom)
# Gets the region of interest for the nose.
def get_nose_roi(face_points):
 points = np.zeros((len(face_points.parts()), 2))
 for i, part in enumerate(face_points.parts()):
  points[i] = (part.x, part.y)
 # Nose and cheeks
 min_x = int(points[36, 0])
 min_y = int(points[28, 1])
 max_x = int(points[45, 0])
 max_y = int(points[33, 1])
 left = min_x
 right = max_x
 top = min_y + (min_y * 0.02)
 bottom = max_y + (max_y * 0.02)
 return int(left), int(right), int(top), int(bottom)
# Gets region of interest that includes forehead, eyes, and nose.
# Note: Combination of forehead and nose performs better. This is probably because this ROI includes eyes,
# and eye blinking adds noise.
def get_full_roi(face_points):
 points = np.zeros((len(face_points.parts()), 2))
 for i, part in enumerate(face_points.parts()):
  points[i] = (part.x, part.y)
 # Only keep the points that correspond to the internal features of the face (e.g. mouth, nose, eyes, brows).
 # The points outlining the jaw are discarded.
 min_x = int(np.min(points[17:47, 0]))
 min_y = int(np.min(points[17:47, 1]))
 max_x = int(np.max(points[17:47, 0]))
 max_y = int(np.max(points[17:47, 1]))
 center_x = min_x + (max_x - min_x) / 2
 left = min_x + int((center_x - min_x) * 0.15)
 right = max_x - int((max_x - center_x) * 0.15)
 top = int(min_y * 0.88)
 bottom = max_y
 return int(left), int(right), int(top), int(bottom)
def sliding_window_demean(signal_values, num_windows):
 window_size = int(round(len(signal_values) / num_windows))
 demeaned = np.zeros(signal_values.shape)
 for i in range(0, len(signal_values), window_size):
  if i + window_size > len(signal_values):
   window_size = len(signal_values) - i
  curr_slice = signal_values[i: i + window_size]
  if DEBUG_MODE and curr_slice.size == 0:
   print ('Empty Slice: size={0}, i={1}, window_size={2}'.format(signal_values.size, i, window_size))
   print (curr_slice)
  demeaned[i:i + window_size] = curr_slice - np.mean(curr_slice)
 return demeaned
# Averages the green values for two arrays of pixels
def get_avg(roi1, roi2):
 roi1_green = roi1[:, :, 1]
 roi2_green = roi2[:, :, 1]
 avg = (np.mean(roi1_green) + np.mean(roi2_green)) / 2.0
 return avg
# Returns maximum absolute value from a list
def get_max_abs(lst):
 return max(max(lst), -min(lst))
# Draws the heart rate graph in the GUI window.
def draw_graph(signal_values, graph_width, graph_height):
 graph = np.zeros((graph_height, graph_width, 3), np.uint8)
 scale_factor_x = float(graph_width) / MAX_VALUES_TO_GRAPH
 # Automatically rescale vertically based on the value with largest absolute value
 max_abs = get_max_abs(signal_values)
 scale_factor_y = (float(graph_height) / 2.0) / max_abs
 midpoint_y = graph_height / 2
 for i in range(0, len(signal_values) - 1):
  curr_x = int(i * scale_factor_x)
  curr_y = int(midpoint_y + signal_values[i] * scale_factor_y)
  next_x = int((i + 1) * scale_factor_x)
  next_y = int(midpoint_y + signal_values[i + 1] * scale_factor_y)
  cv2.line(graph, (curr_x, curr_y), (next_x, next_y), color=(0, 255, 0), thickness=1)
 return graph
# Draws the heart rate text (BPM) in the GUI window.
def draw_bpm(bpm_str, bpm_width, bpm_height):
 bpm_display = np.zeros((bpm_height, bpm_width, 3), np.uint8)
 bpm_text_size, bpm_text_base = cv2.getTextSize(bpm_str, fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=2.7,
             thickness=2)
 bpm_text_x = int((bpm_width - bpm_text_size[0]) / 2)
 bpm_text_y = int(bpm_height / 2 + bpm_text_base)
 cv2.putText(bpm_display, bpm_str, (bpm_text_x, bpm_text_y), fontFace=cv2.FONT_HERSHEY_DUPLEX,
    fontScale=2.7, color=(0, 255, 0), thickness=2)
 bpm_label_size, bpm_label_base = cv2.getTextSize('BPM', fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=0.6,
              thickness=1)
 bpm_label_x = int((bpm_width - bpm_label_size[0]) / 2)
 bpm_label_y = int(bpm_height - bpm_label_size[1] * 2)
 cv2.putText(bpm_display, 'BPM', (bpm_label_x, bpm_label_y),
    fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=0.6, color=(0, 255, 0), thickness=1)
 return bpm_display
# Draws the current frames per second in the GUI window.
def draw_fps(frame, fps):
 cv2.rectangle(frame, (0, 0), (100, 30), color=(0, 0, 0), thickness=-1)
 cv2.putText(frame, 'FPS: ' + str(round(fps, 2)), (5, 20), fontFace=cv2.FONT_HERSHEY_PLAIN,
    fontScale=1, color=(0, 255, 0))
 return frame
# Draw text in the graph area
def draw_graph_text(text, color, graph_width, graph_height):
 graph = np.zeros((graph_height, graph_width, 3), np.uint8)
 text_size, text_base = cv2.getTextSize(text, fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, thickness=1)
 text_x = int((graph_width - text_size[0]) / 2)
 text_y = int((graph_height / 2 + text_base))
 cv2.putText(graph, text, (text_x, text_y), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=1, color=color,
    thickness=1)
 return graph
# Calculate the pulse in beats per minute (BPM)
def compute_bpm(filtered_values, fps, buffer_size, last_bpm):
 # Compute FFT
 fft = np.abs(np.fft.rfft(filtered_values))
 # Generate list of frequencies that correspond to the FFT values
 freqs = fps / buffer_size * np.arange(buffer_size / 2 + 1)
 # Filter out any peaks in the FFT that are not within our range of [MIN_HZ, MAX_HZ]
 # because they correspond to impossible BPM values.
 while True:
  max_idx = fft.argmax()
  bps = freqs[max_idx]
  if bps < MIN_HZ or bps > MAX_HZ:
   if DEBUG_MODE:
    print ('BPM of {0} was discarded.'.format(bps * 60.0))
   fft[max_idx] = 0
  else:
   bpm = bps * 60.0
   break
 # It's impossible for the heart rate to change more than 10% between samples,
 # so use a weighted average to smooth the BPM with the last BPM.
 if last_bpm > 0:
  bpm = (last_bpm * 0.9) + (bpm * 0.1)
 return bpm
def filter_signal_data(values, fps):
 # Ensure that array doesn't have infinite or NaN values
 values = np.array(values)
 np.nan_to_num(values, copy=False)
 # Smooth the signal by detrending and demeaning
 detrended = signal.detrend(values, type='linear')
 demeaned = sliding_window_demean(detrended, 15)
 # Filter signal with Butterworth bandpass filter
 filtered = butterworth_filter(demeaned, MIN_HZ, MAX_HZ, fps, order=5)
 return filtered
# Get the average value for the regions of interest. Will also draw a green rectangle around
# the regions of interest, if requested.
def get_roi_avg(frame, view, face_points, draw_rect=True):
 # Get the regions of interest.
 fh_left, fh_right, fh_top, fh_bottom = get_forehead_roi(face_points)
 nose_left, nose_right, nose_top, nose_bottom = get_nose_roi(face_points)
 # Draw green rectangles around our regions of interest (ROI)
 if draw_rect:
  cv2.rectangle(view, (fh_left, fh_top), (fh_right, fh_bottom), color=(0, 255, 0), thickness=2)
  cv2.rectangle(view, (nose_left, nose_top), (nose_right, nose_bottom), color=(0, 255, 0), thickness=2)
 # Slice out the regions of interest (ROI) and average them
 fh_roi = frame[fh_top:fh_bottom, fh_left:fh_right]
 nose_roi = frame[nose_top:nose_bottom, nose_left:nose_right]
 return get_avg(fh_roi, nose_roi)
# Main function.
def run_pulse_observer(detector, predictor, webcam, window):
 roi_avg_values = []
 graph_values = []
 times = []
 last_bpm = 0
 graph_height = 200
 graph_width = 0
 bpm_display_width = 0
 # cv2.getWindowProperty() returns -1 when window is closed by user.
 while cv2.getWindowProperty(window, 0) == 0:
  ret_val, frame = webcam.read()
  # ret_val == False if unable to read from webcam
  if not ret_val:
   print ("ERROR: Unable to read from webcam. Was the webcam disconnected? Exiting.")
   shut_down(webcam)
  # Make copy of frame before we draw on it. We'll display the copy in the GUI.
  # The original frame will be used to compute heart rate.
  view = np.array(frame)
  # Heart rate graph gets 75% of window width. BPM gets 25%.
  if graph_width == 0:
   graph_width = int(view.shape[1] * 0.75)
   if DEBUG_MODE:
    print ('Graph width = {0}'.format(graph_width))
  if bpm_display_width == 0:
   bpm_display_width = view.shape[1] - graph_width
  # Detect face using dlib
  faces = detector(frame, 0)
  if len(faces) == 1:
   face_points = predictor(frame, faces[0])
   roi_avg = get_roi_avg(frame, view, face_points, draw_rect=True)
   roi_avg_values.append(roi_avg)
   times.append(time.time())
   # Buffer is full, so pop the value off the top to get rid of it
   if len(times) > BUFFER_MAX_SIZE:
    roi_avg_values.pop(0)
    times.pop(0)
   curr_buffer_size = len(times)
   # Don't try to compute pulse until we have at least the min. number of frames
   if curr_buffer_size > MIN_FRAMES:
    # Compute relevant times
    time_elapsed = times[-1] - times[0]
    fps = curr_buffer_size / time_elapsed # frames per second
    # Clean up the signal data
    filtered = filter_signal_data(roi_avg_values, fps)
    graph_values.append(filtered[-1])
    if len(graph_values) > MAX_VALUES_TO_GRAPH:
     graph_values.pop(0)
    # Draw the pulse graph
    graph = draw_graph(graph_values, graph_width, graph_height)
    # Compute and display the BPM
    bpm = compute_bpm(filtered, fps, curr_buffer_size, last_bpm)
    bpm_display = draw_bpm(str(int(round(bpm))), bpm_display_width, graph_height)
    last_bpm = bpm
    # Display the FPS
    if DEBUG_MODE:
     view = draw_fps(view, fps)
   else:
    # If there's not enough data to compute HR, show an empty graph with loading text and
    # the BPM placeholder
    pct = int(round(float(curr_buffer_size) / MIN_FRAMES * 100.0))
    loading_text = 'Computing pulse: ' + str(pct) + '%'
    graph = draw_graph_text(loading_text, (0, 255, 0), graph_width, graph_height)
    bpm_display = draw_bpm('--', bpm_display_width, graph_height)
  else:
   # No faces detected, so we must clear the lists of values and timestamps. Otherwise there will be a gap
   # in timestamps when a face is detected again.
   del roi_avg_values[:]
   del times[:]
   graph = draw_graph_text('No face detected', (0, 0, 255), graph_width, graph_height)
   bpm_display = draw_bpm('--', bpm_display_width, graph_height)
  graph = np.hstack((graph, bpm_display))
  view = np.vstack((view, graph))
  cv2.imshow(window, view)
  key = cv2.waitKey(1)
  # Exit if user presses the escape key
  if key == 27:
   shut_down(webcam)
# Clean up
def shut_down(webcam):
 webcam.release()
 cv2.destroyAllWindows()
 exit(0)
def main():
 detector = dlib.get_frontal_face_detector()
 # Predictor pre-trained model can be downloaded from:
 # http://sourceforge.net/projects/dclib/files/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2
 try:
  predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
 except RuntimeError as e:
  print ('ERROR: \'shape_predictor_68_face_landmarks.dat\' was not found in current directory. ' \
    'Download it from http://sourceforge.net/projects/dclib/files/dlib/v18.10/shape_predictor_68_face_landmarks.dat.bz2')
  return
 webcam = cv2.VideoCapture(0)
 if not webcam.isOpened():
  print ('ERROR: Unable to open webcam. Verify that webcam is connected and try again. Exiting.')
  webcam.release()
  return
 cv2.namedWindow(WINDOW_TITLE)
 run_pulse_observer(detector, predictor, webcam, WINDOW_TITLE)
 # run_pulse_observer() returns when the user has closed the window. Time to shut down.
 shut_down(webcam)
if __name__ == '__main__':
 main()

总结

以上所述是小编给大家介绍的浅析Python+OpenCV使用摄像头追踪人脸面部血液变化实现脉搏评估,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

(0)

相关推荐

  • OpenCV-Python 摄像头实时检测人脸代码实例

    参考 OpenCV摄像头使用 代码 import cv2 cap = cv2.VideoCapture(4) # 使用第5个摄像头(我的电脑插了5个摄像头) face_cascade = cv2.CascadeClassifier(r'haarcascade_frontalface_default.xml') # 加载人脸特征库 while(True): ret, frame = cap.read() # 读取一帧的图像 gray = cv2.cvtColor(frame, cv2.COLOR_

  • python版opencv摄像头人脸实时检测方法

    OpenCV版本3.3.0,注意模型文件的路径要改成自己所安装的opencv的模型文件的路径,路径不对就会报错,一般在opencv-3.3.0/data/haarcascades 路径下 import numpy as np import cv2 face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') cap = cv2.VideoCapture(0) while True: ret,img = ca

  • python操作摄像头截图实现远程监控的例子

    最近用python写了一个远程监控的程序,主要功能有:1.用邮件控制所以功能2.可以对屏幕截图,屏幕截图发送到邮箱3.可以用摄像头获取图片,这些图片上传到七牛4.开机自启动 复制代码 代码如下: ##coding by loster#import win32apiimport win32conimport platformimport socketimport timeimport osimport smtplibimport poplibfrom VideoCapture import Dev

  • python开启摄像头以及深度学习实现目标检测方法

    最近想做实时目标检测,需要用到python开启摄像头,我手上只有两个uvc免驱的摄像头,性能一般.利用python开启摄像头费了一番功夫,主要原因是我的摄像头都不能用cv2的VideCapture打开,这让我联想到原来opencv也打不开Android手机上的摄像头(后来采用QML的Camera模块实现的).看来opencv对于摄像头的兼容性仍然不是很完善. 我尝了几种办法:v4l2,v4l2_capture以及simpleCV,都打不开.最后采用pygame实现了摄像头的采集功能,这里直接给大

  • Python OpenCV调用摄像头检测人脸并截图

    本文实例为大家分享了Python OpenCV调用摄像头检测人脸并截图的具体代码,供大家参考,具体内容如下 注意:需要在python中安装OpenCV库,同时需要下载OpenCV人脸识别模型haarcascade_frontalface_alt.xml,模型可在OpenCV-PCA-KNN-SVM_face_recognition中下载. 使用OpenCV调用摄像头检测人脸并连续截图100张 #-*- coding: utf-8 -*- # import 进openCV的库 import cv2

  • Python OpenCV利用笔记本摄像头实现人脸检测

    本文实例为大家分享了Python OpenCV利用笔记本摄像头实现人脸检测的具体代码,供大家参考,具体内容如下 1.安装opencv 首先参考其他文章安装pip. 之后以管理员身份运行命令提示符,输入以下代码安装opencv pip install --user opencv-python 可以使用以下代码测试安装是否成功 #导入opencv模块 import cv2 #捕捉帧,笔记本摄像头设置为0即可 capture = cv2.VideoCapture(0) #循环显示帧 while(Tru

  • python opencv设置摄像头分辨率以及各个参数的方法

    1,为了获取视频,你应该创建一个 VideoCapture 对象.他的参数可以是设备的索引号,或者是一个视频文件.设备索引号就是在指定要使用的摄像头.一般的笔记本电脑都有内置摄像头.所以参数就是 0.你可以通过设置成 1 或者其他的来选择别的摄像头.之后,你就可以一帧一帧的捕获视频了.但是最后,别忘了停止捕获视频.使用 ls /dev/video*命令可以查看摄像头设备 2,cap.read() 返回一个布尔值(True/False).如果帧读取的是正确的,就是 True.所以最后你可以通过检查

  • 浅析Python+OpenCV使用摄像头追踪人脸面部血液变化实现脉搏评估

    使用摄像头追踪人脸由于血液流动引起的面部色素的微小变化实现实时脉搏评估. 效果如下(演示视频): 由于这是通过比较面部色素的变化评估脉搏所以光线.人体移动.不同角度.不同电脑摄像头等因素均会影响评估效果,实验原理是面部色素对比,识别效果存在一定误差,各位小伙伴且当娱乐,代码如下: import cv2 import numpy as np import dlib import time from scipy import signal # Constants WINDOW_TITLE = 'Pu

  • python openCV实现摄像头获取人脸图片

    本文实例为大家分享了python openCV实现摄像头获取人脸图片的具体代码,供大家参考,具体内容如下 在机器学习中,训练模型需要大量图片,通过openCV中的库可以快捷的调用摄像头,截取图片,可以快速的获取大量人脸图片 需要注意将CascadeClassifier方法中的地址改为自己包cv2包下面的文件 import cv2 def load_img(path,name,mun = 100,add_with = 0): # 获取人脸识别模型 # # #以下路径需要更改为自己环境下xml文件

  • python+opencv实现的简单人脸识别代码示例

    # 源码如下: #!/usr/bin/env python #coding=utf-8 import os from PIL import Image, ImageDraw import cv def detect_object(image): '''检测图片,获取人脸在图片中的坐标''' grayscale = cv.CreateImage((image.width, image.height), 8, 1) cv.CvtColor(image, grayscale, cv.CV_BGR2GR

  • python+openCV利用摄像头实现人员活动检测

    本文实例为大家分享了python+openCV利用摄像头实现人员活动检测的具体代码,供大家参考,具体内容如下 1.前言 最近在做个机器人比赛,其中一项要求是让机器人实现对是否有人员活动的检测,所以就先拿PC端写一下,准备移植到机器人的树莓派. 2.工具 工具还是简单的python+视觉模块openCV,代码量也比较少.很简单就可以实现 3.人员检测的原理   从图书馆借了一本<特征提取与图像处理(第二版)>,是Mark S.Nixon和Alberto S.Aguado写的,其中讲了跟多关于检测

  • Python OpenCV 调用摄像头并截图保存功能的实现代码

    0x01 OpenCV安装 通过命令pip install opencv-python 安装 pip install opencv-python 0x02  示例 import cv2 cap = cv2.VideoCapture(0) #打开摄像头 while(1): # get a frame ret, frame = cap.read() # show a frame cv2.imshow("capture", frame) #生成摄像头窗口 if cv2.waitKey(1)

  • python+openCV调用摄像头拍摄和处理图片的实现

    在深度学习过程中想做手势识别相关应用,需要大量采集手势图片进行训练,作为一个懒人当然希望飞快的连续采集图片并且采集到的图片就已经被处理成统一格式的啦..于是使用python+openCV调用摄像头,在采集图片的同时顺便处理成想要的格式. 详细代码如下: import cv2 import os print("=============================================") print("= 热键(请在摄像头的窗口使用): =") pri

  • python+opencv打开摄像头,保存视频、拍照功能的实现方法

    以下代码是保存视频 # coding:utf-8 import cv2 import sys reload(sys) sys.setdefaultencoding('utf8') cap = cv2.VideoCapture(0) cap.set(3,640) cap.set(4,480) cap.set(1, 10.0) #此处fourcc的在MAC上有效,如果视频保存为空,那么可以改一下这个参数试试, 也可以是-1 fourcc = cv2.cv.CV_FOURCC('m', 'p', '4

  • python+opencv+caffe+摄像头做目标检测的实例代码

    首先之前已经成功的使用Python做图像的目标检测,这回因为项目最终是需要用摄像头的, 所以实现摄像头获取图像,并且用Python调用CAFFE接口来实现目标识别 首先是摄像头请选择支持Linux万能驱动兼容V4L2的摄像头, 因为之前用学ARM的时候使用的Smart210,我已经确认我的摄像头是支持的, 我把摄像头插上之後自然就在 /dev 目录下看到多了一个video0的文件, 这个就是摄像头的设备文件了,所以我就没有额外处理驱动的部分 一.检测环境 再来在开始前因为之前按着国嵌的指导手册安

随机推荐