face_alignment.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # Original code
  2. # https://github.com/ZhaoJ9014/face.evoLVe.PyTorch/blob/master/align/face_align.py
  3. import argparse
  4. import os
  5. import numpy as np
  6. from align.align_trans import (
  7. get_reference_facial_points,
  8. warp_and_crop_face,
  9. )
  10. from align.detector import detect_faces
  11. from PIL import Image
  12. from tqdm import tqdm
  13. if __name__ == "__main__":
  14. parser = argparse.ArgumentParser()
  15. parser.add_argument(
  16. "--tags",
  17. help="specify your tags for raw datasets",
  18. default="test",
  19. nargs='+',
  20. required=True
  21. )
  22. parser.add_argument(
  23. "--crop_size",
  24. help="specify size of aligned faces",
  25. default=112,
  26. choices=[112, 224],
  27. type=int,
  28. )
  29. args = parser.parse_args()
  30. tags = args.tags
  31. crop_size = args.crop_size
  32. scale = crop_size / 112.0
  33. reference = get_reference_facial_points(default_square=True) * scale
  34. for tag in tags:
  35. source_root = os.path.join("data", tag)
  36. dest_root = source_root + "_aligned"
  37. if not os.path.isdir(dest_root):
  38. os.mkdir(dest_root)
  39. for subfolder in tqdm(os.listdir(source_root)):
  40. if not os.path.isdir(os.path.join(dest_root, subfolder)):
  41. os.mkdir(os.path.join(dest_root, subfolder))
  42. for image_name in os.listdir(os.path.join(source_root, subfolder)):
  43. print(
  44. "Processing\t{}".format(
  45. os.path.join(source_root, subfolder, image_name),
  46. ),
  47. )
  48. img = Image.open(os.path.join(source_root, subfolder, image_name))
  49. try: # Handle exception
  50. _, landmarks = detect_faces(img)
  51. except Exception:
  52. print(
  53. "{} is discarded due to exception!".format(
  54. os.path.join(source_root, subfolder, image_name),
  55. ),
  56. )
  57. continue
  58. if (
  59. len(landmarks) == 0
  60. ): # If the landmarks cannot be detected, the img will be discarded
  61. print(
  62. "{} is discarded due to non-detected landmarks!".format(
  63. os.path.join(source_root, subfolder, image_name),
  64. ),
  65. )
  66. continue
  67. facial5points = [[landmarks[0][j], landmarks[0][j + 5]] for j in range(5)]
  68. warped_face = warp_and_crop_face(
  69. np.array(img),
  70. facial5points,
  71. reference,
  72. crop_size=(crop_size, crop_size),
  73. )
  74. img_warped = Image.fromarray(warped_face)
  75. if image_name.split(".")[-1].lower() not in ["jpg", "jpeg"]:
  76. image_name = ".".join(image_name.split(".")[:-1]) + ".jpg"
  77. img_warped.save(os.path.join(dest_root, subfolder, image_name))