import cv2
import numpy as np
import matplotlib.pyplot as plt
#人脸检测
def face_rec(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier()
face_cascade.load(r'c:\\users\\carino\\appdata\\local\\programs\\python\\python39\\lib\\site-packages\\cv2\\data\\haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(gray,
scaleFactor = 1.15,
minNeighbors=3,
minSize=(3,3),
flags=cv2.IMREAD_GRAYSCALE)
for (x,y,w,h) in faces:
img = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
cv2.imshow('result',img)
cap = cv2.VideoCapture(0)#调整参数实现读取视频或调用摄像头
#cv.namedWindow("result", cv.WINDOW_AUTOSIZE)
while True:
ret, frame = cap.read()
#cv2.imshow("cap", frame)
face_rec(frame)
c = cv2.waitKey(10)
if c == 27:#当键盘按下‘ESC’退出程序
break
cap.release()
cv2.destroyAllWindows()