📜  用于人脸检测的 Opencv Python程序

📅  最后修改于: 2022-05-13 01:54:56.749000             🧑  作者: Mango

用于人脸检测的 Opencv Python程序


给出的程序的目标是实时检测感兴趣的对象(人脸)并保持对同一对象的跟踪。这是一个如何在Python中检测人脸的简单示例。您可以尝试通过在所需对象上训练分类器来使用您选择的任何其他对象的训练样本来检测。

以下是下载以下要求的步骤。

脚步:

  1. 下载Python 2.7.x 版本、numpy 和 Opencv 2.7.x 版本。检查您的 Windows 32 位或 64 位是否兼容并相应安装。
  2. 确保 numpy 在你的Python中运行,然后尝试安装 opencv。
  3. 将 haarcascade_eye.xml 和 haarcascade_frontalface_default.xml 文件放在同一个文件夹中(链接在下面的代码中)。

执行

# OpenCV program to detect face in real time
# import libraries of python OpenCV 
# where its functionality resides
import cv2 
  
# load the required trained XML classifiers
# https://github.com/Itseez/opencv/blob/master/
# data/haarcascades/haarcascade_frontalface_default.xml
# Trained XML classifiers describes some features of some
# object we want to detect a cascade function is trained
# from a lot of positive(faces) and negative(non-faces)
# images.
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
  
# https://github.com/Itseez/opencv/blob/master
# /data/haarcascades/haarcascade_eye.xml
# Trained XML file for detecting eyes
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') 
  
# capture frames from a camera
cap = cv2.VideoCapture(0)
  
# loop runs if capturing has been initialized.
while 1: 
  
    # reads frames from a camera
    ret, img = cap.read() 
  
    # convert to gray scale of each frames
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  
    # Detects faces of different sizes in the input image
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
  
    for (x,y,w,h) in faces:
        # To draw a rectangle in a face 
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2) 
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]
  
        # Detects eyes of different sizes in the input image
        eyes = eye_cascade.detectMultiScale(roi_gray) 
  
        #To draw a rectangle in eyes
        for (ex,ey,ew,eh) in eyes:
            cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,127,255),2)
  
    # Display an image in a window
    cv2.imshow('img',img)
  
    # Wait for Esc key to stop
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break
  
# Close the window
cap.release()
  
# De-allocate any associated memory usage
cv2.destroyAllWindows() 

输出:

输出


下一篇:
人脸检测的Opencv C++程序

参考:

  • https://www.youtube.com/v=WfdYYNamHZ8
  • http://docs.opencv.org/2.4/modules/objdetect/doc/cascade_classification.html?highlight=cascadeclassifier#cascadeclassifier
  • http://www.multimedia-computing.de/mediawiki//images/5/52/MRL-TR-May02-revised-Dec02.pdf