trysem/vintager
2
1# Copyright (c) 2021 Justin Pinkney2 3import dlib4import numpy as np5import os6from PIL import Image7from PIL import ImageOps8from scipy.ndimage import gaussian_filter9import cv210 11 12MODEL_PATH = "shape_predictor_5_face_landmarks.dat"13detector = dlib.get_frontal_face_detector()14 15 16def align(image_in, face_index=0, output_size=256):17 try:18 image_in = ImageOps.exif_transpose(image_in)19 except:20 print("exif problem, not rotating")21 22 landmarks = list(get_landmarks(image_in))23 n_faces = len(landmarks)24 face_index = min(n_faces-1, face_index)25 if n_faces == 0:26 aligned_image = image_in27 quad = None28 else:29 aligned_image, quad = image_align(image_in, landmarks[face_index], output_size=output_size)30 31 return aligned_image, n_faces, quad32 33 34def composite_images(quad, img, output):35 """Composite an image into and output canvas according to transformed co-ords"""36 output = output.convert("RGBA")37 img = img.convert("RGBA")38 input_size = img.size39 src = np.array(((0, 0), (0, input_size[1]), input_size, (input_size[0], 0)), dtype=np.float32)40 dst = np.float32(quad)41 mtx = cv2.getPerspectiveTransform(dst, src)42 img = img.transform(output.size, Image.PERSPECTIVE, mtx.flatten(), Image.BILINEAR)43 output.alpha_composite(img)44 45 return output.convert("RGB")46 47 48def get_landmarks(image):49 """Get landmarks from PIL image"""50 shape_predictor = dlib.shape_predictor(MODEL_PATH)51 52 max_size = max(image.size)53 reduction_scale = int(max_size/512)54 if reduction_scale == 0:55 reduction_scale = 156 downscaled = image.reduce(reduction_scale)57 img = np.array(downscaled)58 detections = detector(img, 0)59 60 for detection in detections:61 try:62 face_landmarks = [(reduction_scale*item.x, reduction_scale*item.y) for item in shape_predictor(img, detection).parts()]63 yield face_landmarks64 except Exception as e:65 print(e)66 67 68def image_align(src_img, face_landmarks, output_size=512, transform_size=2048, enable_padding=True, x_scale=1, y_scale=1, em_scale=0.1, alpha=False):69 # Align function modified from ffhq-dataset70 # See https://github.com/NVlabs/ffhq-dataset for license71 72 lm = np.array(face_landmarks)73 lm_eye_left = lm[2:3] # left-clockwise74 lm_eye_right = lm[0:1] # left-clockwise75 76 # Calculate auxiliary vectors.77 eye_left = np.mean(lm_eye_left, axis=0)78 eye_right = np.mean(lm_eye_right, axis=0)79 eye_avg = (eye_left + eye_right) * 0.580 eye_to_eye = 0.71*(eye_right - eye_left)81 mouth_avg = lm[4]82 eye_to_mouth = 1.35*(mouth_avg - eye_avg)83 84 # Choose oriented crop rectangle.85 x = eye_to_eye.copy()86 x /= np.hypot(*x)87 x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8)88 x *= x_scale89 y = np.flipud(x) * [-y_scale, y_scale]90 c = eye_avg + eye_to_mouth * em_scale91 quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])92 quad_orig = quad.copy()93 qsize = np.hypot(*x) * 2 94 95 img = src_img.convert('RGBA').convert('RGB')96 97 # Shrink.98 shrink = int(np.floor(qsize / output_size * 0.5))99 if shrink > 1:100 rsize = (int(np.rint(float(img.size[0]) / shrink)), int(np.rint(float(img.size[1]) / shrink)))101 img = img.resize(rsize, Image.ANTIALIAS)102 quad /= shrink103 qsize /= shrink104 105 # Crop.106 border = max(int(np.rint(qsize * 0.1)), 3)107 crop = (int(np.floor(min(quad[:,0]))), int(np.floor(min(quad[:,1]))), int(np.ceil(max(quad[:,0]))), int(np.ceil(max(quad[:,1]))))108 crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]), min(crop[3] + border, img.size[1]))109 if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]:110 img = img.crop(crop)111 quad -= crop[0:2]112 113 # Pad.114 pad = (int(np.floor(min(quad[:,0]))), int(np.floor(min(quad[:,1]))), int(np.ceil(max(quad[:,0]))), int(np.ceil(max(quad[:,1]))))115 pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0), max(pad[3] - img.size[1] + border, 0))116 if enable_padding and max(pad) > border - 4:117 pad = np.maximum(pad, int(np.rint(qsize * 0.3)))118 img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')119 h, w, _ = img.shape120 y, x, _ = np.ogrid[:h, :w, :1]121 mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w-1-x) / pad[2]), 1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h-1-y) / pad[3]))122 blur = qsize * 0.02123 img += (gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)124 img += (np.median(img, axis=(0,1)) - img) * np.clip(mask, 0.0, 1.0)125 img = np.uint8(np.clip(np.rint(img), 0, 255))126 if alpha:127 mask = 1-np.clip(3.0 * mask, 0.0, 1.0)128 mask = np.uint8(np.clip(np.rint(mask*255), 0, 255))129 img = np.concatenate((img, mask), axis=2)130 img = Image.fromarray(img, 'RGBA')131 else:132 img = Image.fromarray(img, 'RGB')133 quad += pad[:2]134 135 # Transform.136 img = img.transform((transform_size, transform_size), Image.QUAD, (quad + 0.5).flatten(), Image.BILINEAR)137 if output_size < transform_size:138 img = img.resize((output_size, output_size), Image.ANTIALIAS)139 140 return img, quad_orig141 