Python篇-摄像头中的人脸、眼睛识别

  • Post author:
  • Post category:python


import cv2

# 图片中的人脸检测
pathf = r'haarcascade_frontalface_default.xml'
pathe = r'haarcascade_eye.xml'

# 获取训练好的人脸的参数数据,这里直接从GitHub上使用默认值
face_cascade = cv2.CascadeClassifier(pathf)
eye_cascade = cv2.CascadeClassifier(pathe)

# 检测摄像头中的人脸
if __name__ == "__main__":

    cap = cv2.VideoCapture(0)
    video_w, video_h = int(cap.get(3)), int(cap.get(4))
    print(video_h, video_w)

    while True:
        # 获取当前帧并初始化occupied/unoccupied文本
        (grabbed, frame) = cap.read()
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

        # 探测图片中的人脸
        faces = face_cascade.detectMultiScale(
            gray,
            scaleFactor=1.15,
            minNeighbors=5,
            minSize = (5, 5),
        )

        print("发现{0}个人脸!".format(len(faces)))
        for (x,y,w,h) in faces:
            #圆圈
            cv2.circle(frame,((x+x+w)//2,(y+y+h)//2),w//2,(0,255,0),2)
            #矩形
            # cv2.rectangle(frame,(x,y),(x+w,y+w),(0,255,0),2)
            face_re = frame[y:y+h, x:x+h]
            face_re_g = gray[y:y+h, x:x+h]
            eyes = eye_cascade.detectMultiScale(face_re_g)
            for(ex,ey,ew,eh) in eyes:
                cv2.rectangle(face_re,(ex,ey),(ex+ew,ey+eh),(255,0,0),1)

        cv2.imshow("摄像头", frame)
        k = cv2.waitKey(1) & 0xff
        if k == ord('q') or k == 27:
            break

    cap.release()
复制代码

效果如下(请忽略我英俊的脸庞?):如对你有帮助点个赞呗