import cv2
import numpy
cam = cv2.VideoCapture(0)
face_det = cv2.CascadeClassifier('./apply/haarcascade_frontalface_default.xml')
success = cam.isOpened()

while success and cv2.waitKey(1) == -1:
    ret, img = cam.read()
    face =  face_det.detectMultiScale(img,1.3,5)
    if len(face):
        for(x, y, w, h) in face:
            img = cv2.rectangle(img, (x,y),(x+w,y+h),(255,0,0),2)
            img_face = img[y :y+h , x:x+w]
            cv2.imshow('1', img_face)

    # print(img_face)

    cv2.imshow('0',img)

心得:在截取人脸过程中,img[y1:y2,x:1:x2],先对y区域设置

基于CVzone的人脸检测,速度和识别效果良好

from cvzone.FaceDetectionModule import FaceDetector
import cv2
import imutils
cap = cv2.VideoCapture(r'data/song.jpg')
detector = FaceDetector()

while True:
    success, img = cap.read()
    img = imutils.resize(img, width=1024)
    img, bboxs = detector.findFaces(img)

    if bboxs:
        # bboxInfo - "id","bbox","score","center"
        center = bboxs[0]["center"]
        cv2.circle(img, center, 5, (255, 0, 255), cv2.FILLED)
    # img = cv2.putText(img, "中国", (50,50), cv2.FONT_HERSHEY_PLAIN,2, (0,255,255))
    cv2.imshow("Image", img)
    if cv2.waitKey(0) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()