def face_alignment(faces,show=False):
'''
faces: num * width * height * channels ,value = 0~255, dtype = np.uint8,
note: width must equal to height
'''
print(faces.shape)
if len(faces.shape)==4 and faces.shape[3]==1:
faces = faces.reshape(faces.shape[:-1]) # if gray, turns to num * width * height, no channel axis 如果是灰度图,去掉最后一维,否则predictor会报错
num = faces.shape[0]
import numpy as np
faces_aligned = np.zeros(shape=faces.shape,dtype=np.uint8)
import dlib
predictor_path = "./shape_predictor_68_face_landmarks.dat" # dlib提供的训练好的68个人脸关键点的模型,网上可以下
predictor = dlib.shape_predictor(predictor_path) # 用来预测关键点
for i in range(num):
img = faces[i]
rec = dlib.rectangle(0,0,img.shape[0],img.shape[1])
shape = predictor(np.uint8(img),rec) # 注意输入的必须是uint8类型
order=[36,45,30,48,54] # left eye, right eye, nose, left mouth, right mouth 注意关键点的顺序,这个在网上可以找
if show:
plt.pyplot.figure()
plt.pyplot.imshow(img,cmap='gray')
for j in order:
x = shape.part(j).x
y = shape.part(j).y
plt.pyplot.scatter(x,y) # 可以plot出来看看效果,这里我只plot5个点
eye_