import dlib
import cv2
# 使用 dlib 的正面人脸检测器 frontal_face_detector
detector = dlib.get_frontal_face_detector()
# 打开摄像头
cap = cv2.VideoCapture(0)
# 摄像头打开状态
while cap.isOpened():
flag, img = cap.read()
# 每帧数据延时 1ms,延时为 0 读取的是静态帧
k = cv2.waitKey(1)
# 使用 detector 检测器来检测图像中的人脸
# detector() 的第二个参数表示在执行检测过程之前对图像进行上采样的次数,
# 因为图像越大检测器检测到更多的人脸的可能性就越高,但执行时间相应也会增加。
faces = detector(img, 1)
# print("人脸数 / Faces in all: ", len(faces))
# 处理多张人脸
for i, d in enumerate(faces):
# print("第", i+1, "个人脸的矩形框坐标:", "left:", d.left(), "right:", d.right(), "top:", d.top(), "bottom:", d.bottom())
# 绘制人脸框
cv2.rectangle(img, tuple([d.left(), d.top()]), tuple([d.right(), d.bottom()]), (0, 255, 255), 2)
# 显示人脸框
cv2.namedWindow("img", 0)
cv2.imshow("img", img)
# 释放摄像头
cap.release()
# 删除建立的窗口
cv2.destroyAllWindows()
