Opencv Python 简明教程

OpenCV Python - Face Detection

OpenCV 使用 Haar 基于特征的级联分类器进行对象检测。它是一种基于机器学习的算法,级联函数由大量正负图像训练。然后,它用于检测其他图像中的对象。该算法使用了级联分类器的概念。

OpenCV uses Haar feature-based cascade classifiers for the object detection. It is a machine learning based algorithm, where a cascade function is trained from a lot of positive and negative images. It is then used to detect objects in other images. The algorithm uses the concept of Cascade of Classifiers.

人脸、眼睛等预训练分类器可从 https://github.com 下载

Pretrained classifiers for face, eye etc. can be downloaded from https://github.com

对于以下示例,请从该 URL 下载并 copy haarcascade_frontalface_default.xmlhaarcascade_eye.xml 。然后,加载将用于灰度模式人脸检测的输入图像。

For the following example, download and copy haarcascade_frontalface_default.xml and haarcascade_eye.xml from this URL. Then, load our input image to be used for face detection in grayscale mode.

CascadeClassifier 类的 DetectMultiScale() 方法检测输入图像中的对象。它以矩形形式返回检测到的人脸的位置及其尺寸 (x,y,w,h)。一旦获得这些位置,我们就可以将其用于眼睛检测,因为眼睛始终在人脸上!

The DetectMultiScale() method of CascadeClassifier class detects objects in the input image. It returns the positions of detected faces as in the form of Rectangle and its dimensions (x,y,w,h). Once we get these locations, we can use it for eye detection since eyes are always on the face!

Example

人脸检测的完整代码如下 −

The complete code for face detection is as follows −

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

img = cv2.imread('Dhoni-and-virat.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
   img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
   roi_gray = gray[y:y+h, x:x+w]
   roi_color = img[y:y+h, x:x+w]
   eyes = eye_cascade.detectMultiScale(roi_gray)
   for (ex,ey,ew,eh) in eyes:
      cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output

您将在输入图像中看到围绕人脸绘制的矩形,如下所示 −

You will get rectangles drawn around faces in the input image as shown below −

face detection