上接《OpenCV3-Python人脸识别方法—基于图像》,本篇介绍实时摄像头下人脸检测。

1. Viola-Jones分类器

Viola-Jones分类器在级联的每个节点中使用AdaBoost来学习一个高检测率低拒绝率的多层树分类器,其有以下几点创新:

(1)使用类Haar输入特征,对矩形图像区域的“和”或者“差”进行阈值化。

(2)积分图像技术加速矩形图像区的45°旋转值的计算,被用来加速类Haar输入特征的计算。

(3)使用统计boosting创建两类问题(人脸、非人脸)的分类器节点(高通过率、低拒绝率)。

(4)把弱分类节点组成筛选式级联。换句话说:第一组分类器是最优,能通过包含物体的图像区域,同时允许一些不包含物体的图像通过;第二组分类器次优分类器,也是有较低的拒绝率;以此类推,在测试模式下,只要图像区域通过了整个级联,则认为里面有物体。

2. 摄像头实时人脸识别

加载人脸检测器文件 haarcascade_frontalface_default.xml 和人眼检测器文件 haarcascade_eye.xml;调用 cv2.VideoCapture(0) 打开USB摄像头,获取实时图像,程序会根据获取的图像,检测并绘制出人脸和眼睛。

若佩戴着眼镜,请加载检测器文件 haarcascade_eye_tree_eyeglasses.xml 。

import cv2

def detect():
  face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_default.xml')
  eye_cascade = cv2.CascadeClassifier('./cascades/haarcascade_eye.xml')
  #eye_cascade = cv2.CascadeClassifier('./cascades/haarcascade_eye_tree_eyeglasses.xml')
  
  camera = cv2.VideoCapture(0)
  
  while (True):
    ret, frame = camera.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    #img = cv2.imread(frame)
    for (x,y,w,h) in faces:
        img = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
        
        roi_gray = gray[y:y+h, x:x+w]

        '''
          cv2.CascadeClassifier.detectMultiScale(image[, scaleFactor[, minNeighbors[, flags[, minSize[, maxSize]]]]]) → objects
          Parameters: 
                image – Matrix of the type CV_8U containing an image where objects are detected.
                scaleFactor – Parameter specifying how much the image size is reduced at each image scale.
                minNeighbors – Parameter specifying how many neighbors each candidate rectangle should have to retain it.
                flags – Parameter with the same meaning for an old cascade as in the function cvHaarDetectObjects. It is not used for a new cascade.
                minSize – Minimum possible object size. Objects smaller than that are ignored.
                maxSize – Maximum possible object size. Objects larger than that are ignored.  
                objects – Vector of rectangles where each rectangle contains the detected object, the rectangles may be partially outside the original image.
        '''         
        eyes = eye_cascade.detectMultiScale(roi_gray, 1.03, 5, 0, (80,80))
        for (ex,ey,ew,eh) in eyes:
            cv2.rectangle(img,(x+ex,y+ey),(x+ex+ew,y+ey+eh),(0,255,0),2)

    cv2.imshow("camera", frame)
    if cv2.waitKey(100) & 0xff == ord("q"):
      break

  camera.release()
  cv2.destroyAllWindows()

if __name__ == "__main__":
  detect()

3. 识别结果

4. 注意事项 

实际中进行眼睛检测时,其结果可能会和鼻子混淆,此时可通过添加minSize来限制最小区域:

minSize – Minimum possible object size. Objects smaller than that are ignored.

下一篇:《OpenCV3-Python人脸识别方法—人脸识别与标记》

注意:本站所有文章除特别说明外,均为原创,转载请务必以超链接方式并注明作者出处。 标签:python,opencv3,人脸识别