Path: blob/master/Face-Recognition-with-ArcFace/face_alignment.py
3118 views
# Original code1# https://github.com/ZhaoJ9014/face.evoLVe.PyTorch/blob/master/align/face_align.py23import argparse4import os56import numpy as np7from align.align_trans import (8get_reference_facial_points,9warp_and_crop_face,10)11from align.detector import detect_faces12from PIL import Image13from tqdm import tqdm1415if __name__ == "__main__":16parser = argparse.ArgumentParser()17parser.add_argument(18"--tags",19help="specify your tags for raw datasets",20default="test",21nargs='+',22required=True23)24parser.add_argument(25"--crop_size",26help="specify size of aligned faces",27default=112,28choices=[112, 224],29type=int,30)31args = parser.parse_args()3233tags = args.tags34crop_size = args.crop_size35scale = crop_size / 112.036reference = get_reference_facial_points(default_square=True) * scale3738for tag in tags:39source_root = os.path.join("data", tag)40dest_root = source_root + "_aligned"41if not os.path.isdir(dest_root):42os.mkdir(dest_root)4344for subfolder in tqdm(os.listdir(source_root)):45if not os.path.isdir(os.path.join(dest_root, subfolder)):46os.mkdir(os.path.join(dest_root, subfolder))47for image_name in os.listdir(os.path.join(source_root, subfolder)):48print(49"Processing\t{}".format(50os.path.join(source_root, subfolder, image_name),51),52)53img = Image.open(os.path.join(source_root, subfolder, image_name))54try: # Handle exception55_, landmarks = detect_faces(img)56except Exception:57print(58"{} is discarded due to exception!".format(59os.path.join(source_root, subfolder, image_name),60),61)62continue63if (64len(landmarks) == 065): # If the landmarks cannot be detected, the img will be discarded66print(67"{} is discarded due to non-detected landmarks!".format(68os.path.join(source_root, subfolder, image_name),69),70)71continue72facial5points = [[landmarks[0][j], landmarks[0][j + 5]] for j in range(5)]73warped_face = warp_and_crop_face(74np.array(img),75facial5points,76reference,77crop_size=(crop_size, crop_size),78)79img_warped = Image.fromarray(warped_face)80if image_name.split(".")[-1].lower() not in ["jpg", "jpeg"]:81image_name = ".".join(image_name.split(".")[:-1]) + ".jpg"82img_warped.save(os.path.join(dest_root, subfolder, image_name))838485