Opencv——python实现实时人脸检测

首先加载opencv库,cv2.VideoCapture(0)调用设备摄像头进行实时拍摄视频,然后调用模型对视频进行人脸检测并进行标注

import cv2
# 调用摄像头
capture=cv2.VideoCapture(0)
# 如果不能打开摄像头
if not capture.isOpened:
    print('不能打开')
    exit(0)
#     调用模型
face = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye=cv2.CascadeClassifier('haarcascade_eye.xml')
while True:
    ret,frame=capture.read()
    if frame is None:
        break
    #     灰度图像
    gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

    faces=face.detectMultiScale(gray)
    # 坐标
    for x,y,w,h in faces:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,255,0),2)
        roi_eye=gray[y:y+h,x:x+w]
        eyes=eye.detectMultiScale(roi_eye)
        for(ex,ey,ew,eh)in eyes:
            cv2.circle(frame[y:y+h,x:x+w],(int(ex+ew/2),
                int(ey+eh/2)),int(max(ew,eh)/2),(255,255,255),2)
# while (True):
    cv2.imshow('faces',frame)
    key=cv2.waitKey(30)
    #27是esc的aci编码
    if key==27:
        break
感谢大家支持!
 
 

你可能感兴趣的:(python,opencv,计算机视觉)