Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
iperov
GitHub Repository: iperov/deepfacelab
Path: blob/master/samplelib/SampleProcessor.py
628 views
1
import collections
2
import math
3
from enum import IntEnum
4
5
import cv2
6
import numpy as np
7
8
from core import imagelib
9
from core.cv2ex import *
10
from core.imagelib import sd
11
from facelib import FaceType, LandmarksProcessor
12
13
14
class SampleProcessor(object):
15
class SampleType(IntEnum):
16
NONE = 0
17
IMAGE = 1
18
FACE_IMAGE = 2
19
FACE_MASK = 3
20
LANDMARKS_ARRAY = 4
21
PITCH_YAW_ROLL = 5
22
PITCH_YAW_ROLL_SIGMOID = 6
23
24
class ChannelType(IntEnum):
25
NONE = 0
26
BGR = 1 #BGR
27
G = 2 #Grayscale
28
GGG = 3 #3xGrayscale
29
30
class FaceMaskType(IntEnum):
31
NONE = 0
32
FULL_FACE = 1 # mask all hull as grayscale
33
EYES = 2 # mask eyes hull as grayscale
34
EYES_MOUTH = 3 # eyes and mouse
35
36
class Options(object):
37
def __init__(self, random_flip = True, rotation_range=[-10,10], scale_range=[-0.05, 0.05], tx_range=[-0.05, 0.05], ty_range=[-0.05, 0.05] ):
38
self.random_flip = random_flip
39
self.rotation_range = rotation_range
40
self.scale_range = scale_range
41
self.tx_range = tx_range
42
self.ty_range = ty_range
43
44
@staticmethod
45
def process (samples, sample_process_options, output_sample_types, debug, ct_sample=None):
46
SPST = SampleProcessor.SampleType
47
SPCT = SampleProcessor.ChannelType
48
SPFMT = SampleProcessor.FaceMaskType
49
50
51
outputs = []
52
for sample in samples:
53
sample_rnd_seed = np.random.randint(0x80000000)
54
55
sample_face_type = sample.face_type
56
sample_bgr = sample.load_bgr()
57
sample_landmarks = sample.landmarks
58
ct_sample_bgr = None
59
h,w,c = sample_bgr.shape
60
61
def get_full_face_mask():
62
xseg_mask = sample.get_xseg_mask()
63
if xseg_mask is not None:
64
if xseg_mask.shape[0] != h or xseg_mask.shape[1] != w:
65
xseg_mask = cv2.resize(xseg_mask, (w,h), interpolation=cv2.INTER_CUBIC)
66
xseg_mask = imagelib.normalize_channels(xseg_mask, 1)
67
return np.clip(xseg_mask, 0, 1)
68
else:
69
full_face_mask = LandmarksProcessor.get_image_hull_mask (sample_bgr.shape, sample_landmarks, eyebrows_expand_mod=sample.eyebrows_expand_mod )
70
return np.clip(full_face_mask, 0, 1)
71
72
def get_eyes_mask():
73
eyes_mask = LandmarksProcessor.get_image_eye_mask (sample_bgr.shape, sample_landmarks)
74
return np.clip(eyes_mask, 0, 1)
75
76
def get_eyes_mouth_mask():
77
eyes_mask = LandmarksProcessor.get_image_eye_mask (sample_bgr.shape, sample_landmarks)
78
mouth_mask = LandmarksProcessor.get_image_mouth_mask (sample_bgr.shape, sample_landmarks)
79
mask = eyes_mask + mouth_mask
80
return np.clip(mask, 0, 1)
81
82
is_face_sample = sample_landmarks is not None
83
84
if debug and is_face_sample:
85
LandmarksProcessor.draw_landmarks (sample_bgr, sample_landmarks, (0, 1, 0))
86
87
outputs_sample = []
88
for opts in output_sample_types:
89
resolution = opts.get('resolution', 0)
90
sample_type = opts.get('sample_type', SPST.NONE)
91
channel_type = opts.get('channel_type', SPCT.NONE)
92
nearest_resize_to = opts.get('nearest_resize_to', None)
93
warp = opts.get('warp', False)
94
transform = opts.get('transform', False)
95
random_hsv_shift_amount = opts.get('random_hsv_shift_amount', 0)
96
normalize_tanh = opts.get('normalize_tanh', False)
97
ct_mode = opts.get('ct_mode', None)
98
data_format = opts.get('data_format', 'NHWC')
99
100
rnd_seed_shift = opts.get('rnd_seed_shift', 0)
101
warp_rnd_seed_shift = opts.get('warp_rnd_seed_shift', rnd_seed_shift)
102
103
rnd_state = np.random.RandomState (sample_rnd_seed+rnd_seed_shift)
104
warp_rnd_state = np.random.RandomState (sample_rnd_seed+warp_rnd_seed_shift)
105
106
warp_params = imagelib.gen_warp_params(resolution,
107
sample_process_options.random_flip,
108
rotation_range=sample_process_options.rotation_range,
109
scale_range=sample_process_options.scale_range,
110
tx_range=sample_process_options.tx_range,
111
ty_range=sample_process_options.ty_range,
112
rnd_state=rnd_state,
113
warp_rnd_state=warp_rnd_state,
114
)
115
116
if sample_type == SPST.FACE_MASK or sample_type == SPST.IMAGE:
117
border_replicate = False
118
elif sample_type == SPST.FACE_IMAGE:
119
border_replicate = True
120
121
122
border_replicate = opts.get('border_replicate', border_replicate)
123
borderMode = cv2.BORDER_REPLICATE if border_replicate else cv2.BORDER_CONSTANT
124
125
126
if sample_type == SPST.FACE_IMAGE or sample_type == SPST.FACE_MASK:
127
if not is_face_sample:
128
raise ValueError("face_samples should be provided for sample_type FACE_*")
129
130
if sample_type == SPST.FACE_IMAGE or sample_type == SPST.FACE_MASK:
131
face_type = opts.get('face_type', None)
132
face_mask_type = opts.get('face_mask_type', SPFMT.NONE)
133
134
if face_type is None:
135
raise ValueError("face_type must be defined for face samples")
136
137
if sample_type == SPST.FACE_MASK:
138
if face_mask_type == SPFMT.FULL_FACE:
139
img = get_full_face_mask()
140
elif face_mask_type == SPFMT.EYES:
141
img = get_eyes_mask()
142
elif face_mask_type == SPFMT.EYES_MOUTH:
143
mask = get_full_face_mask().copy()
144
mask[mask != 0.0] = 1.0
145
img = get_eyes_mouth_mask()*mask
146
else:
147
img = np.zeros ( sample_bgr.shape[0:2]+(1,), dtype=np.float32)
148
149
if sample_face_type == FaceType.MARK_ONLY:
150
raise NotImplementedError()
151
mat = LandmarksProcessor.get_transform_mat (sample_landmarks, warp_resolution, face_type)
152
img = cv2.warpAffine( img, mat, (warp_resolution, warp_resolution), flags=cv2.INTER_LINEAR )
153
154
img = imagelib.warp_by_params (warp_params, img, warp, transform, can_flip=True, border_replicate=border_replicate, cv2_inter=cv2.INTER_LINEAR)
155
img = cv2.resize( img, (resolution,resolution), interpolation=cv2.INTER_LINEAR )
156
else:
157
if face_type != sample_face_type:
158
mat = LandmarksProcessor.get_transform_mat (sample_landmarks, resolution, face_type)
159
img = cv2.warpAffine( img, mat, (resolution,resolution), borderMode=borderMode, flags=cv2.INTER_LINEAR )
160
else:
161
if w != resolution:
162
img = cv2.resize( img, (resolution, resolution), interpolation=cv2.INTER_LINEAR )
163
164
img = imagelib.warp_by_params (warp_params, img, warp, transform, can_flip=True, border_replicate=border_replicate, cv2_inter=cv2.INTER_LINEAR)
165
166
if face_mask_type == SPFMT.EYES_MOUTH:
167
div = img.max()
168
if div != 0.0:
169
img = img / div # normalize to 1.0 after warp
170
171
if len(img.shape) == 2:
172
img = img[...,None]
173
174
if channel_type == SPCT.G:
175
out_sample = img.astype(np.float32)
176
else:
177
raise ValueError("only channel_type.G supported for the mask")
178
179
elif sample_type == SPST.FACE_IMAGE:
180
img = sample_bgr
181
182
if face_type != sample_face_type:
183
mat = LandmarksProcessor.get_transform_mat (sample_landmarks, resolution, face_type)
184
img = cv2.warpAffine( img, mat, (resolution,resolution), borderMode=borderMode, flags=cv2.INTER_CUBIC )
185
else:
186
if w != resolution:
187
img = cv2.resize( img, (resolution, resolution), interpolation=cv2.INTER_CUBIC )
188
189
# Apply random color transfer
190
if ct_mode is not None and ct_sample is not None:
191
if ct_sample_bgr is None:
192
ct_sample_bgr = ct_sample.load_bgr()
193
img = imagelib.color_transfer (ct_mode, img, cv2.resize( ct_sample_bgr, (resolution,resolution), interpolation=cv2.INTER_LINEAR ) )
194
195
if random_hsv_shift_amount != 0:
196
a = random_hsv_shift_amount
197
h_amount = max(1, int(360*a*0.5))
198
img_h, img_s, img_v = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
199
img_h = (img_h + rnd_state.randint(-h_amount, h_amount+1) ) % 360
200
img_s = np.clip (img_s + (rnd_state.random()-0.5)*a, 0, 1 )
201
img_v = np.clip (img_v + (rnd_state.random()-0.5)*a, 0, 1 )
202
img = np.clip( cv2.cvtColor(cv2.merge([img_h, img_s, img_v]), cv2.COLOR_HSV2BGR) , 0, 1 )
203
204
img = imagelib.warp_by_params (warp_params, img, warp, transform, can_flip=True, border_replicate=border_replicate)
205
206
img = np.clip(img.astype(np.float32), 0, 1)
207
208
# Transform from BGR to desired channel_type
209
if channel_type == SPCT.BGR:
210
out_sample = img
211
elif channel_type == SPCT.G:
212
out_sample = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)[...,None]
213
elif channel_type == SPCT.GGG:
214
out_sample = np.repeat ( np.expand_dims(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY),-1), (3,), -1)
215
216
# Final transformations
217
if nearest_resize_to is not None:
218
out_sample = cv2_resize(out_sample, (nearest_resize_to,nearest_resize_to), interpolation=cv2.INTER_NEAREST)
219
220
if not debug:
221
if normalize_tanh:
222
out_sample = np.clip (out_sample * 2.0 - 1.0, -1.0, 1.0)
223
if data_format == "NCHW":
224
out_sample = np.transpose(out_sample, (2,0,1) )
225
elif sample_type == SPST.IMAGE:
226
img = sample_bgr
227
img = imagelib.warp_by_params (warp_params, img, warp, transform, can_flip=True, border_replicate=True)
228
img = cv2.resize( img, (resolution, resolution), interpolation=cv2.INTER_CUBIC )
229
out_sample = img
230
231
if data_format == "NCHW":
232
out_sample = np.transpose(out_sample, (2,0,1) )
233
234
235
elif sample_type == SPST.LANDMARKS_ARRAY:
236
l = sample_landmarks
237
l = np.concatenate ( [ np.expand_dims(l[:,0] / w,-1), np.expand_dims(l[:,1] / h,-1) ], -1 )
238
l = np.clip(l, 0.0, 1.0)
239
out_sample = l
240
elif sample_type == SPST.PITCH_YAW_ROLL or sample_type == SPST.PITCH_YAW_ROLL_SIGMOID:
241
pitch,yaw,roll = sample.get_pitch_yaw_roll()
242
if warp_params['flip']:
243
yaw = -yaw
244
245
if sample_type == SPST.PITCH_YAW_ROLL_SIGMOID:
246
pitch = np.clip( (pitch / math.pi) / 2.0 + 0.5, 0, 1)
247
yaw = np.clip( (yaw / math.pi) / 2.0 + 0.5, 0, 1)
248
roll = np.clip( (roll / math.pi) / 2.0 + 0.5, 0, 1)
249
250
out_sample = (pitch, yaw)
251
else:
252
raise ValueError ('expected sample_type')
253
254
outputs_sample.append ( out_sample )
255
outputs += [outputs_sample]
256
257
return outputs
258
259
260