OpenCV-Python系列·第二十集:检测&跟踪人脸

Tip:直接应用OpenCV自带训练好的配置文件.xml

# -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 09:18:05 2018

@author: Miracle
"""
import cv2

def detectFace():
    #加载人脸检测的配置文件
    face_cascade = cv2.CascadeClassifier('../data/haarcascades/haarcascade_frontalface_alt.xml')
#    face_cascade.load('../data/haarcascades/haarcascade_frontalface_alt.xml')
    #打开摄像头
    cap = cv2.VideoCapture(0)
    scaling_factor = 1.25
   
    if not cap.isOpened:
        raise IOError('Cannot open webcam!')
    
    while True:
        ret,frame = cap.read()
        if not ret:
            break
        frame = cv2.resize(frame,None,
                           fx = scaling_factor,
                           fy = scaling_factor,
                           interpolation = cv2.INTER_LINEAR)
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        
        face_rects = face_cascade.detectMultiScale(gray)
        
        for (x,y,w,h) in face_rects:
            cv2.rectangle(frame,(x,y),(x+w,h+y),(0,255,0),3)
        
        cv2.imshow('detecting face',frame)
        
        if cv2.waitKey(1) == 27:
            break
    cap.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    detectFace()
    
    
    

OpenCV-Python系列·第二十集:检测&跟踪人脸_第1张图片

你可能感兴趣的:(OpenCV-Python)