如果懒得下,opencv的人脸模型,从下面下载

资源下载地址

https://download.csdn.net/download/chencaw/13569353

基于opencv现有模型,adaboost方法

注意:眼睛,鼻子什么的也都可以检测,自己换模型就好了

#引入opencv模块
import cv2 as cv
#引入numpy模块
import numpy as np
#引入sys模块
import sys


#人脸检测
def face_detection(img):
    gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)    
    face_detector = cv.CascadeClassifier("E:/chenopencvblogimg/haarcascades/haarcascade_frontalface_alt_tree.xml")
    #faces = face_detector.detectMultiScale(gray,1.02,2)
    #faces = face_detector.detectMultiScale(gray,1.1,2)
    faces = face_detector.detectMultiScale(gray,1.02,5)
    for x,y,w,h in faces:
        cv.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
    cv.namedWindow("face_detection",cv.WINDOW_NORMAL)
    cv.imshow("face_detection",img)   

def capture_video():
    capture = cv.VideoCapture(0)
    while(True):
        ret,frame = capture.read()
        #如果没有读取到图
        if ret == False:
            print('read video error')
            break
        face_detection(frame)
        cv.waitKey(10)


def img_test():
    img = cv.imread('E:/chenopencvblogimg/face2.jpg')     
    #判断是否读取成功
    if img is None:
        print("Could not read the image,may be path error")
        return
    cv.namedWindow("origin Pic",cv.WINDOW_NORMAL)
    cv.imshow("origin Pic",img)
    face_detection(img)
    capture_video()
    #让显示等待键盘输入维持在那里,否则程序跑完就闪退啦!
    cv.waitKey(0)
    #销毁窗口
    cv.destroyAllWindows()


if __name__ == '__main__':
    sys.exit(img_test() or 0)

 

本文地址:https://blog.csdn.net/chencaw/article/details/110871968