Skip to content

Commit c714880

Browse files
author
Alex Damian
committed
``
1 parent 21dd077 commit c714880

File tree

4 files changed

+200
-28
lines changed

4 files changed

+200
-28
lines changed

.gitignore

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
.DS_Store
2+
__pycache__/*
23
.idea/*
34
runs/*
45
input/*
5-
cache/*
6+
cache/*
7+
realpics/*

align_face.py

+167
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
"""
2+
brief: face alignment with FFHQ method (https://github.com/NVlabs/ffhq-dataset)
3+
author: lzhbrian (https://lzhbrian.me)
4+
date: 2020.1.5
5+
note: code is heavily borrowed from
6+
https://github.com/NVlabs/ffhq-dataset
7+
http://dlib.net/face_landmark_detection.py.html
8+
9+
requirements:
10+
apt install cmake
11+
conda install Pillow numpy scipy
12+
pip install dlib
13+
# download face landmark model from:
14+
# http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
15+
"""
16+
17+
import numpy as np
18+
import PIL
19+
import PIL.Image
20+
import sys
21+
import os
22+
import glob
23+
import scipy
24+
import scipy.ndimage
25+
import dlib
26+
from drive import open_url
27+
from pathlib import Path
28+
import argparse
29+
from bicubic import BicubicDownSample
30+
import torchvision
31+
32+
def get_landmark(filepath):
33+
"""get landmark with dlib
34+
:return: np.array shape=(68, 2)
35+
"""
36+
detector = dlib.get_frontal_face_detector()
37+
38+
img = dlib.load_rgb_image(filepath)
39+
dets = detector(img, 1)
40+
filepath = Path(filepath)
41+
print(f"{filepath.name}: Number of faces detected: {len(dets)}")
42+
shapes = [predictor(img, d) for k,d in enumerate(dets)]
43+
44+
lms = [np.array([[tt.x,tt.y] for tt in shape.parts()]) for shape in shapes]
45+
46+
return lms
47+
48+
49+
def align_face(filepath):
50+
"""
51+
:param filepath: str
52+
:return: PIL Image
53+
"""
54+
55+
lms = get_landmark(filepath)
56+
imgs=[]
57+
for lm in lms:
58+
lm_chin = lm[0 : 17] # left-right
59+
lm_eyebrow_left = lm[17 : 22] # left-right
60+
lm_eyebrow_right = lm[22 : 27] # left-right
61+
lm_nose = lm[27 : 31] # top-down
62+
lm_nostrils = lm[31 : 36] # top-down
63+
lm_eye_left = lm[36 : 42] # left-clockwise
64+
lm_eye_right = lm[42 : 48] # left-clockwise
65+
lm_mouth_outer = lm[48 : 60] # left-clockwise
66+
lm_mouth_inner = lm[60 : 68] # left-clockwise
67+
68+
# Calculate auxiliary vectors.
69+
eye_left = np.mean(lm_eye_left, axis=0)
70+
eye_right = np.mean(lm_eye_right, axis=0)
71+
eye_avg = (eye_left + eye_right) * 0.5
72+
eye_to_eye = eye_right - eye_left
73+
mouth_left = lm_mouth_outer[0]
74+
mouth_right = lm_mouth_outer[6]
75+
mouth_avg = (mouth_left + mouth_right) * 0.5
76+
eye_to_mouth = mouth_avg - eye_avg
77+
78+
# Choose oriented crop rectangle.
79+
x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
80+
x /= np.hypot(*x)
81+
x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8)
82+
y = np.flipud(x) * [-1, 1]
83+
c = eye_avg + eye_to_mouth * 0.1
84+
quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
85+
qsize = np.hypot(*x) * 2
86+
87+
88+
# read image
89+
img = PIL.Image.open(filepath)
90+
91+
output_size=1024
92+
transform_size=4096
93+
enable_padding=True
94+
95+
# Shrink.
96+
shrink = int(np.floor(qsize / output_size * 0.5))
97+
if shrink > 1:
98+
rsize = (int(np.rint(float(img.size[0]) / shrink)), int(np.rint(float(img.size[1]) / shrink)))
99+
img = img.resize(rsize, PIL.Image.ANTIALIAS)
100+
quad /= shrink
101+
qsize /= shrink
102+
103+
# Crop.
104+
border = max(int(np.rint(qsize * 0.1)), 3)
105+
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]))))
106+
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]))
107+
if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]:
108+
img = img.crop(crop)
109+
quad -= crop[0:2]
110+
111+
# Pad.
112+
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]))))
113+
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))
114+
if enable_padding and max(pad) > border - 4:
115+
pad = np.maximum(pad, int(np.rint(qsize * 0.3)))
116+
img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')
117+
h, w, _ = img.shape
118+
y, x, _ = np.ogrid[:h, :w, :1]
119+
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]))
120+
blur = qsize * 0.02
121+
img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)
122+
img += (np.median(img, axis=(0,1)) - img) * np.clip(mask, 0.0, 1.0)
123+
img = PIL.Image.fromarray(np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB')
124+
quad += pad[:2]
125+
126+
# Transform.
127+
img = img.transform((transform_size, transform_size), PIL.Image.QUAD, (quad + 0.5).flatten(), PIL.Image.BILINEAR)
128+
if output_size < transform_size:
129+
img = img.resize((output_size, output_size), PIL.Image.ANTIALIAS)
130+
131+
# Save aligned image.
132+
imgs.append(img)
133+
return imgs
134+
135+
parser = argparse.ArgumentParser(description='PULSE')
136+
137+
parser.add_argument('-input_dir', type=str, default='realpics', help='directory with unprocessed images')
138+
parser.add_argument('-output_dir', type=str, default='input', help='output directory')
139+
parser.add_argument('-output_size', type=int, default=32, help='size to downscale the input images to, must be power of 2')
140+
parser.add_argument('-seed', type=int, help='manual seed to use')
141+
parser.add_argument('-cache_dir', type=str, default='cache', help='cache directory for model weights')
142+
143+
args = parser.parse_args()
144+
145+
cache_dir = Path(args.cache_dir)
146+
cache_dir.mkdir(parents=True, exist_ok=True)
147+
148+
output_dir = Path(args.output_dir)
149+
output_dir.mkdir(parents=True,exist_ok=True)
150+
151+
print("Downloading Shape Predictor")
152+
f=open_url("https://drive.google.com/uc?id=1huhv8PYpNNKbGCLOaYUjOgR1pY5pmbJx", cache_dir=cache_dir, return_path=True)
153+
predictor = dlib.shape_predictor(f)
154+
155+
for im in Path(args.input_dir).glob("*.*"):
156+
faces = align_face(str(im))
157+
158+
for i,face in enumerate(faces):
159+
if(args.output_size):
160+
factor = 1024//args.output_size
161+
assert args.output_size*factor == 1024
162+
D = BicubicDownSample(factor=factor)
163+
face_tensor = torchvision.transforms.ToTensor()(face).unsqueeze(0).cuda()
164+
face_tensor_lr = D(face_tensor)[0].cpu().detach().clamp(0, 1)
165+
face = torchvision.transforms.ToPILImage()(face_tensor_lr)
166+
167+
face.save(Path(args.output_dir) / (im.stem+f"_{i}.png"))

drive.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def is_url(obj: Any) -> bool:
2727
return True
2828

2929

30-
def open_url(url: str, cache_dir: str = None, num_attempts: int = 10, verbose: bool = True) -> Any:
30+
def open_url(url: str, cache_dir: str = None, num_attempts: int = 10, verbose: bool = True, return_path: bool = False) -> Any:
3131
"""Download the given URL and return a binary-mode file object to access the data."""
3232
assert is_url(url)
3333
assert num_attempts >= 1
@@ -37,7 +37,10 @@ def open_url(url: str, cache_dir: str = None, num_attempts: int = 10, verbose: b
3737
if cache_dir is not None:
3838
cache_files = glob.glob(os.path.join(cache_dir, url_md5 + "_*"))
3939
if len(cache_files) == 1:
40-
return open(cache_files[0], "rb")
40+
if(return_path):
41+
return cache_files[0]
42+
else:
43+
return open(cache_files[0], "rb")
4144

4245
# Download.
4346
url_name = None
@@ -85,6 +88,7 @@ def open_url(url: str, cache_dir: str = None, num_attempts: int = 10, verbose: b
8588
with open(temp_file, "wb") as f:
8689
f.write(url_data)
8790
os.replace(temp_file, cache_file) # atomic
91+
if(return_path): return cache_file
8892

8993
# Return data as file object.
9094
return io.BytesIO(url_data)

run.py

+24-25
Original file line numberDiff line numberDiff line change
@@ -7,31 +7,6 @@
77
from math import log10, ceil
88
import argparse
99

10-
if __name__ == '__main__':
11-
parser = argparse.ArgumentParser(description='PULSE')
12-
13-
#I/O arguments
14-
parser.add_argument('-input_dir', type=str, default='input', help='input data directory')
15-
parser.add_argument('-output_dir', type=str, default='runs', help='output data directory')
16-
parser.add_argument('-cache_dir', type=str, default='cache', help='cache directory for model weights')
17-
parser.add_argument('-duplicates', type=int, default=1, help='How many HR images to produce for every image in the input directory')
18-
19-
#PULSE arguments
20-
parser.add_argument('-seed', type=int, help='manual seed to use')
21-
parser.add_argument('-loss_str', type=str, default="100*L2+0.05*GEOCROSS", help='Loss function to use')
22-
parser.add_argument('-eps', type=float, default=1e-3, help='Target for downscaling loss (L2)')
23-
parser.add_argument('-noise_type', type=str, default='trainable', help='zero, fixed, or trainable')
24-
parser.add_argument('-num_trainable_noise_layers', type=int, default=5, help='Number of noise layers to optimize')
25-
parser.add_argument('-tile_latent', action='store_true', help='Whether to forcibly tile the same latent 18 times')
26-
parser.add_argument('-bad_noise_layers', type=str, default="17", help='List of noise layers to zero out to improve image quality')
27-
parser.add_argument('-opt_name', type=str, default='adam', help='Optimizer to use in projected gradient descent')
28-
parser.add_argument('-learning_rate', type=float, default=0.4, help='Learning rate to use during optimization')
29-
parser.add_argument('-steps', type=int, default=100, help='Number of optimization steps')
30-
parser.add_argument('-lr_schedule', type=str, default='linear1cycledrop', help='fixed, linear1cycledrop, linear1cycle')
31-
parser.add_argument('-save_intermediate', action='store_true', help='Whether to store and save intermediate HR and LR images during optimization')
32-
33-
kwargs = vars(parser.parse_args())
34-
3510
class Images(Dataset):
3611
def __init__(self, root_dir, duplicates):
3712
self.root_path = Path(root_dir)
@@ -49,6 +24,30 @@ def __getitem__(self, idx):
4924
else:
5025
return image,img_path.stem+f"_{(idx % self.duplicates)+1}"
5126

27+
parser = argparse.ArgumentParser(description='PULSE')
28+
29+
#I/O arguments
30+
parser.add_argument('-input_dir', type=str, default='input', help='input data directory')
31+
parser.add_argument('-output_dir', type=str, default='runs', help='output data directory')
32+
parser.add_argument('-cache_dir', type=str, default='cache', help='cache directory for model weights')
33+
parser.add_argument('-duplicates', type=int, default=1, help='How many HR images to produce for every image in the input directory')
34+
35+
#PULSE arguments
36+
parser.add_argument('-seed', type=int, help='manual seed to use')
37+
parser.add_argument('-loss_str', type=str, default="100*L2+0.05*GEOCROSS", help='Loss function to use')
38+
parser.add_argument('-eps', type=float, default=1e-3, help='Target for downscaling loss (L2)')
39+
parser.add_argument('-noise_type', type=str, default='trainable', help='zero, fixed, or trainable')
40+
parser.add_argument('-num_trainable_noise_layers', type=int, default=5, help='Number of noise layers to optimize')
41+
parser.add_argument('-tile_latent', action='store_true', help='Whether to forcibly tile the same latent 18 times')
42+
parser.add_argument('-bad_noise_layers', type=str, default="17", help='List of noise layers to zero out to improve image quality')
43+
parser.add_argument('-opt_name', type=str, default='adam', help='Optimizer to use in projected gradient descent')
44+
parser.add_argument('-learning_rate', type=float, default=0.4, help='Learning rate to use during optimization')
45+
parser.add_argument('-steps', type=int, default=100, help='Number of optimization steps')
46+
parser.add_argument('-lr_schedule', type=str, default='linear1cycledrop', help='fixed, linear1cycledrop, linear1cycle')
47+
parser.add_argument('-save_intermediate', action='store_true', help='Whether to store and save intermediate HR and LR images during optimization')
48+
49+
kwargs = vars(parser.parse_args())
50+
5251
dataset = Images(kwargs["input_dir"], duplicates=kwargs["duplicates"])
5352
out_path = Path(kwargs["output_dir"])
5453
out_path.mkdir(parents=True, exist_ok=True)

0 commit comments

Comments
 (0)