dlib人脸检测
68个关键点的索引图:
- 先找到人脸的位置
- 找关键点相对于人脸的位置
摄像头实时检测
# 1 导入库
import cv2
import dlib
# 2 方法:绘制人脸矩形框
def plot_rectangle(image, faces):
for face in faces:
cv2.rectangle(image, (face.left(), face.top()), (face.right(), face.bottom()), (255, 0, 0), 4)
return image
def main():
# 3 打开摄像头,读取视频
capture = cv2.VideoCapture(0)
# 4 判断摄像头是否正常工作
if capture.isOpened() is False:
print("Camera Error !")
# 5 摄像头正常打开:循环读取每一帧
while True:
ret, frame = capture.read()
if ret:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # BGR to GRAY
# 6 调用dlib库中的检测器
detector = dlib.get_frontal_face_detector()
det_result = detector(gray, 1) # 对图片进行检测,返回一个结果
# 7 绘制检测结果
dets_image = plot_rectangle(frame, det_result) # 原始图片和检测结果 结果绘制到图片上去。
# 8 实时显示最终的检测效果
cv2.imshow("face detection with dlib", dets_image)
# 9 按键"ESC",退出,关闭摄像头
if cv2.waitKey(1) == 27:
break
# 10 释放所有的资源
capture.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
获取图片上人脸68个关键点
import cv2
import dlib
path = "21.jpg"
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 人脸分类器
detector = dlib.get_frontal_face_detector()
# 获取人脸检测器
predictor = dlib.shape_predictor(
"E:\\Code\\defectsDetection\\blink-detection\\shape_predictor_68_face_landmarks.dat"
)
dets = detector(gray, 1)
for face in dets:
shape = predictor(img, face) # 寻找人脸的68个标定点
# 遍历所有点,打印出其坐标,并圈出来
for pt in shape.parts():
pt_pos = (pt.x, pt.y)
cv2.circle(img, pt_pos, 2, (0, 255, 0), 1)
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()