from mtcnn.mtcnn import MTCNN
import cv2
img=cv2.imread('../data/test/2.jpg')
detector=MTCNN()
box=detector.detect_faces(img)
faces=[]
for i in range(len(box)):
faces.append(box[i]['box'])
for (x, y, w, h) in faces:
print(x)
mtcnn速度慢
cascade = cv2.CascadeClassifier('../data/params/haarcascade_frontalface_default.xml') # 检测人脸
faces = cascade.detectMultiScale(frame_gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE)
不精准
dlib
def detection(img):
"""
人脸检测
:param img:
:return:
"""
detector = dlib.get_frontal_face_detector()
dets = detector(img, 1) # 使用detector进行人脸检测 dets为返回的结果
print("Number of faces detected: {}".format(len(dets))) # 打印识别到的人脸个数
for index, face in enumerate(dets):
# 在图片中标注人脸,并显示
left = face.left()
top = face.top()
right = face.right()
bottom = face.bottom()
cv.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 1)
return dets
68个标注点定位
def predictor(img, dets):
"""
特征点标定
:param img:
:param dets:
:return:
"""
# shape_predictor_68_face_landmarks.dat是进行人脸标定的模型,它是基于HOG特征的,这里是他所在的路径
predictor_path = "../model/shape_predictor_68_face_landmarks.dat"
predictor = dlib.shape_predictor(predictor_path)
shape_list = []
for index, face in enumerate(dets):
shape = predictor(img, face) # 寻找人脸的68个标定点
# 遍历所有点,打印出其坐标,并用绿色的圈表示出来
for _, pt in enumerate(shape.parts()):
pt_pos = (pt.x, pt.y)
cv.circle(img, pt_pos, 1, (0, 255, 0), 1)
shape_list.append(shape)
return shape_list