|
import cv2 |
|
import dlib |
|
import numpy as np |
|
from PIL import Image, ImageOps |
|
|
|
|
|
|
|
MODEL_PATH = "shape_predictor_5_face_landmarks.dat" |
|
detector = dlib.get_frontal_face_detector() |
|
|
|
def get_face_landmarks(image_path): |
|
|
|
image = cv2.imread(image_path) |
|
try: |
|
image = ImageOps.exif_transpose(image) |
|
except: |
|
print("exif problem, not rotating") |
|
|
|
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) |
|
|
|
|
|
predictor = dlib.shape_predictor("shape_predictor_5_face_landmarks.dat") |
|
|
|
|
|
faces = detector(gray) |
|
|
|
if len(faces) > 0: |
|
|
|
shape = predictor(gray, faces[0]) |
|
landmarks = np.array([[p.x, p.y] for p in shape.parts()]) |
|
return landmarks |
|
else: |
|
return None |
|
|
|
def calculate_roll_and_yaw(landmarks): |
|
|
|
roll_angle = np.degrees(np.arctan2(landmarks[1, 1] - landmarks[0, 1], landmarks[1, 0] - landmarks[0, 0])) |
|
|
|
|
|
yaw_angle = np.degrees(np.arctan2(landmarks[1, 1] - landmarks[2, 1], landmarks[1, 0] - landmarks[2, 0])) |
|
|
|
return roll_angle, yaw_angle |
|
|
|
def detect_and_crop_head(input_image, factor=3.0): |
|
|
|
landmarks = get_face_landmarks(input_image) |
|
|
|
if landmarks is not None: |
|
|
|
center_x = int(np.mean(landmarks[:, 0])) |
|
center_y = int(np.mean(landmarks[:, 1])) |
|
|
|
|
|
size = int(max(np.max(landmarks[:, 0]) - np.min(landmarks[:, 0]), |
|
np.max(landmarks[:, 1]) - np.min(landmarks[:, 1])) * factor) |
|
|
|
|
|
x_new = max(0, center_x - size // 2) |
|
y_new = max(0, center_y - size // 2) |
|
|
|
|
|
roll_angle, yaw_angle = calculate_roll_and_yaw(landmarks) |
|
|
|
|
|
shift_x = int(size * 0.4 * np.sin(np.radians(yaw_angle))) |
|
shift_y = int(size * 0.4 * np.sin(np.radians(roll_angle))) |
|
|
|
|
|
|
|
center_x += shift_x |
|
center_y += shift_y |
|
|
|
|
|
x_new = max(0, center_x - size // 2) |
|
y_new = max(0, center_y - size // 2) |
|
|
|
|
|
image = Image.open(input_image) |
|
|
|
|
|
cropped_head = np.array(image.crop((x_new, y_new, x_new + size, y_new + size))) |
|
|
|
|
|
cropped_head_pil = Image.fromarray(cropped_head) |
|
|
|
|
|
return cropped_head_pil |
|
else: |
|
return None |
|
|
|
if __name__ == '__main__': |
|
input_image_path = 'input.jpg' |
|
output_image_path = 'output.jpg' |
|
|
|
|
|
cropped_head = detect_and_crop_head(input_image_path, factor=3.0) |
|
|
|
|
|
cropped_head.save(output_image_path) |