安装dlib
pip install dlib
代码
import cv2
import dlib
capture_index = 0
def img2gray(img):
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 使用dlib自带的frontal_face_detector作为我们的特征提取器
def main():
detector = dlib.get_frontal_face_detector()
# 打开摄像头
cap = cv2.VideoCapture(capture_index)
# 开始检测
while True:
success, img = cap.read()
# 转化为灰度图
gray_img = img2gray(img)
# 检测
dets = detector(img, 1)
# 这个也可以
# dets = detector(gray_img, 1)
print("找到人脸%d个" %len(dets))
cv2.namedWindow("image")
# 找到人脸坐标
face_rect = []
# for i,d in enumerate(dets):
for d in dets:
face = []
y1 = d.top() if d.top() > 0 else 0
x1 = d.left() if d.left() > 0 else 0
x2 = d.right() if d.right() > 0 else 0
y2 = d.bottom() if d.bottom() > 0 else 0
face.append(x1)
face.append(y1)
face.append(x2)
face.append(y2)
face_rect.append(face)
# 画框
for rect in face_rect:
cv2.rectangle(img,(rect[0],rect[1]),(rect[2],rect[3]), (0,255,255))
# 竖直翻转一下并显示
cv2.imshow("image", cv2.flip(img,1))
cv2.waitKey(1)
return 0
if __name__ == "__main__":
main()