-
Notifications
You must be signed in to change notification settings - Fork 2
/
align_face.py
65 lines (50 loc) · 2.22 KB
/
align_face.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import numpy as np
import PIL
import PIL.Image
import sys
import os
import glob
import scipy
import scipy.ndimage
import dlib
from drive import open_url
from pathlib import Path
import argparse
from bicubic import BicubicDownSample
import torchvision
from shape_predictor import align_face
import torch
parser = argparse.ArgumentParser(description='PULSE')
parser.add_argument('-input_dir', type=str, default='realpics', help='directory with unprocessed images')
parser.add_argument('-output_dir', type=str, default='input', help='output directory')
parser.add_argument('-output_size', type=int, default=32, help='size to downscale the input images to, must be power of 2')
parser.add_argument('-seed', type=int, help='manual seed to use')
parser.add_argument('-cache_dir', type=str, default='cache', help='cache directory for model weights')
parser.add_argument('-split_str', type=str, default='1/1', help='X/Y format for separating the work into splits')
args = parser.parse_args()
torch.cuda.set_device(2)
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
cache_dir = Path(args.cache_dir)
cache_dir.mkdir(parents=True, exist_ok=True)
output_dir = Path(args.output_dir)
output_dir.mkdir(parents=True,exist_ok=True)
print("Downloading Shape Predictor")
f=open_url("https://drive.google.com/uc?id=1huhv8PYpNNKbGCLOaYUjOgR1pY5pmbJx", cache_dir=cache_dir, return_path=True)
predictor = dlib.shape_predictor(f)
all_files = sorted(Path(args.input_dir).glob("*.jpg"))
def chunkify(lst,n):
return [lst[idx::n] for idx in range(n)]
if args.split_str != '1/1':
chunk_idx, num_chunks = [int(part) for part in args.split_str.split('/')]
all_files = chunkify(all_files, num_chunks)[chunk_idx - 1]
for im in all_files:
faces = align_face(str(im),predictor)
for i,face in enumerate(faces):
if(args.output_size):
factor = 1024//args.output_size
assert args.output_size*factor == 1024
D = BicubicDownSample(factor=factor)
face_tensor = torchvision.transforms.ToTensor()(face).unsqueeze(0).cuda()
face_tensor_lr = D(face_tensor)[0].cpu().detach().clamp(0, 1)
face = torchvision.transforms.ToPILImage()(face_tensor_lr)
face.save(Path(args.output_dir) / (im.stem+f"_{i}.png"))