原图像:
- import cv2
- import dlib
- import matplotlib.pyplot as plt
-
- # 获取图片
- my_img = cv2.imread('my_img.jpg')
- # BGR to RGB
- my_img = cv2.cvtColor(my_img, cv2.COLOR_BGR2RGB)
-
- # 使用特征提取器get_frontal_face_detector
- detector = dlib.get_frontal_face_detector()
-
- dets = detector(my_img, 1)
-
- for det in dets:
- # 将框画在原图上
- # cv2.rectangle 参数1:图片, 参数2:左上角坐标, 参数2:左上角坐标, 参数3:右下角坐标, 参数4:颜色(R,G,B), 参数5:粗细
- my_img = cv2.rectangle(my_img, (det.left(),det.top()), (det.right(),det.bottom()), (0,255,0), 5)
-
- # plt.figure(figsize=(5,5))
- plt.imshow(my_img)
- plt.show()
-
使用关键点模型需要提前下载此模型,并解压得到shape_predictor_68_face_landmarks.dat
下载地址:http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
- # 人脸检测器
- predictor = dlib.shape_predictor(r'./shape_predictor_68_face_landmarks.dat')
-
- for det in dets:
- shape = predictor(my_img, det)
- # 将关键点绘制到人脸上
- for i in range(68):
- cv2.putText(my_img, str(i), (shape.part(i).x, shape.part(i).y), cv2.FONT_HERSHEY_DUPLEX, 0.3, (0, 255, 255), 2, cv2.LINE_AA)
- cv2.circle(my_img, (shape.part(i).x, shape.part(i).y), 1, (0, 0, 255))
-
- plt.imshow(my_img)
- plt.show()
-
- # 人脸对齐
- my_img = dlib.get_face_chip(my_img, shape, size = 150)
- plt.imshow(my_img)
- plt.show()
-