|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# |
| 3 | +# Copyright(C) 2021 wuyaoping |
| 4 | +# |
| 5 | + |
| 6 | + |
| 7 | +import numpy as np |
| 8 | +import os.path as osp |
| 9 | +import sys |
| 10 | +import cv2 |
| 11 | +import dlib |
| 12 | + |
| 13 | +OUT_SIZE = (224, 224) |
| 14 | +LEFT_EYE_RANGE = (36, 42) |
| 15 | +RIGHT_EYE_RABGE = (42, 48) |
| 16 | +LEFT_EYE_POS = (0.35, 0.3815) |
| 17 | +DAT_PATH = "./dat/shape_predictor_68_face_landmarks.dat" |
| 18 | + |
| 19 | + |
| 20 | +def main(files): |
| 21 | + detector = dlib.get_frontal_face_detector() |
| 22 | + sp = dlib.shape_predictor(DAT_PATH) |
| 23 | + |
| 24 | + for file in files: |
| 25 | + img = cv2.imread(file, cv2.IMREAD_ANYCOLOR) |
| 26 | + img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) |
| 27 | + |
| 28 | + faces = detect_align_faces(detector, sp, img) |
| 29 | + for (idx, face) in enumerate(faces): |
| 30 | + face = cv2.cvtColor(face, cv2.COLOR_RGB2BGR) |
| 31 | + filename, ext = osp.splitext(file) |
| 32 | + filename += '_face_{:03}'.format(idx) + ext |
| 33 | + cv2.imwrite(filename, face) |
| 34 | + |
| 35 | + |
| 36 | +def detect_align_faces(detector, sp, img): |
| 37 | + faces = detector(img, 1) |
| 38 | + res = [] |
| 39 | + for face in faces: |
| 40 | + shape = sp(img, face) |
| 41 | + left, right = shape_to_pos(shape) |
| 42 | + left_center = np.mean(left, axis=0) |
| 43 | + right_center = np.mean(right, axis=0) |
| 44 | + |
| 45 | + dx = right_center[0] - left_center[0] |
| 46 | + dy = right_center[1] - left_center[1] |
| 47 | + angle = np.degrees(np.arctan2(dy, dx)) |
| 48 | + dist = np.sqrt(dy ** 2 + dx ** 2) |
| 49 | + out_dist = OUT_SIZE[0] * (1 - 2 * LEFT_EYE_POS[0]) |
| 50 | + scale = out_dist / dist |
| 51 | + center = ((left_center + right_center) // 2).tolist() |
| 52 | + |
| 53 | + mat = cv2.getRotationMatrix2D(center, angle, scale) |
| 54 | + mat[0, 2] += (0.5 * OUT_SIZE[0] - center[0]) |
| 55 | + mat[1, 2] += (LEFT_EYE_POS[1] * OUT_SIZE[1] - center[1]) |
| 56 | + res_face = cv2.warpAffine(img, mat, OUT_SIZE, flags=cv2.INTER_CUBIC) |
| 57 | + res.append(res_face) |
| 58 | + |
| 59 | + return res |
| 60 | + |
| 61 | + |
| 62 | +def shape_to_pos(shape): |
| 63 | + parts = [] |
| 64 | + for p in shape.parts(): |
| 65 | + parts.append((p.x, p.y)) |
| 66 | + |
| 67 | + left = parts[LEFT_EYE_RANGE[0]: LEFT_EYE_RANGE[-1]] |
| 68 | + right = parts[RIGHT_EYE_RABGE[0]: RIGHT_EYE_RABGE[-1]] |
| 69 | + |
| 70 | + return (np.array(left), np.array(right)) |
| 71 | + |
| 72 | + |
| 73 | +if __name__ == '__main__': |
| 74 | + main(sys.argv[1:]) |
0 commit comments