OpenCV3-Python人脸识别方法—基于图像

OpenCV实现人脸检测技术的其中一个版本,由 Paul Viols 和 Michael Jones 设计,称为Viola-Jones 检测器,OpenCV称这个检测器为“Harr分类器”。

1. 检测原理

Haar分类器是一个监督分类器,其先对图形进行直方图均衡化并归一化到同样大小,然后标记里面是否包含要检测的物体。

Haar级联不具有旋转不变性,其认为倒置的人脸图像和直立的人脸图像不一样,侧面的人脸图像与正面的也不一样。

2. 基于图像检测

OpenCV中预先训练好的物体检测器位于.../data/haarcascades 目录下,也可访问官网获取。基于正面识别效果最好的模型文件为 **haarcascade_frontalface_alt2.xml **。

(1)检测器文件如下:

图片

(2)举例(官网):

import cv2

filename = 'players.png'

def detect(filename):
  face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_alt2.xml')
  eye_cascade = cv2.CascadeClassifier('./cascades/haarcascade_eye.xml')
  img = cv2.imread(filename)
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

  '''
  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.
  '''
  faces = face_cascade.detectMultiScale(gray, 1.1, 5)
  for (x,y,w,h) in faces:
    img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

  cv2.namedWindow('Players Detected!!')
  cv2.imshow('Players Detected!!', img)
  cv2.waitKey()
  cv2.destroyAllWindows()

detect(filename)

(3)检测结果如下:

图片

下一篇:《OpenCV3-Python人脸识别方法—基于摄像头》

参考:

Gary Bradski,Adrian Kaehler(著)《学习OpenCV(中文版)》 清华大学出版社。