Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

SampleGeneratorFaceXSeg.py 13 KB

You have to be logged in to leave a comment. Sign In
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
  1. import multiprocessing
  2. import pickle
  3. import time
  4. import traceback
  5. from enum import IntEnum
  6. import cv2
  7. import numpy as np
  8. from pathlib import Path
  9. from core import imagelib, mplib, pathex
  10. from core.imagelib import sd
  11. from core.cv2ex import *
  12. from core.interact import interact as io
  13. from core.joblib import Subprocessor, SubprocessGenerator, ThisThreadGenerator
  14. from facelib import LandmarksProcessor
  15. from samplelib import (SampleGeneratorBase, SampleLoader, SampleProcessor, SampleType)
  16. class SampleGeneratorFaceXSeg(SampleGeneratorBase):
  17. def __init__ (self, paths, debug=False, batch_size=1, resolution=256, face_type=None,
  18. generators_count=4, data_format="NHWC",
  19. **kwargs):
  20. super().__init__(debug, batch_size)
  21. self.initialized = False
  22. samples = sum([ SampleLoader.load (SampleType.FACE, path) for path in paths ] )
  23. seg_sample_idxs = SegmentedSampleFilterSubprocessor(samples).run()
  24. if len(seg_sample_idxs) == 0:
  25. seg_sample_idxs = SegmentedSampleFilterSubprocessor(samples, count_xseg_mask=True).run()
  26. if len(seg_sample_idxs) == 0:
  27. raise Exception(f"No segmented faces found.")
  28. else:
  29. io.log_info(f"Using {len(seg_sample_idxs)} xseg labeled samples.")
  30. else:
  31. io.log_info(f"Using {len(seg_sample_idxs)} segmented samples.")
  32. if self.debug:
  33. self.generators_count = 1
  34. else:
  35. self.generators_count = max(1, generators_count)
  36. args = (samples, seg_sample_idxs, resolution, face_type, data_format)
  37. if self.debug:
  38. self.generators = [ThisThreadGenerator ( self.batch_func, args )]
  39. else:
  40. self.generators = [SubprocessGenerator ( self.batch_func, args, start_now=False ) for i in range(self.generators_count) ]
  41. SubprocessGenerator.start_in_parallel( self.generators )
  42. self.generator_counter = -1
  43. self.initialized = True
  44. #overridable
  45. def is_initialized(self):
  46. return self.initialized
  47. def __iter__(self):
  48. return self
  49. def __next__(self):
  50. self.generator_counter += 1
  51. generator = self.generators[self.generator_counter % len(self.generators) ]
  52. return next(generator)
  53. def batch_func(self, param ):
  54. samples, seg_sample_idxs, resolution, face_type, data_format = param
  55. shuffle_idxs = []
  56. bg_shuffle_idxs = []
  57. random_flip = True
  58. rotation_range=[-10,10]
  59. scale_range=[-0.05, 0.05]
  60. tx_range=[-0.05, 0.05]
  61. ty_range=[-0.05, 0.05]
  62. random_bilinear_resize_chance, random_bilinear_resize_max_size_per = 25,75
  63. sharpen_chance, sharpen_kernel_max_size = 25, 5
  64. motion_blur_chance, motion_blur_mb_max_size = 25, 5
  65. gaussian_blur_chance, gaussian_blur_kernel_max_size = 25, 5
  66. random_jpeg_compress_chance = 25
  67. def gen_img_mask(sample):
  68. img = sample.load_bgr()
  69. h,w,c = img.shape
  70. if sample.seg_ie_polys.has_polys():
  71. mask = np.zeros ((h,w,1), dtype=np.float32)
  72. sample.seg_ie_polys.overlay_mask(mask)
  73. elif sample.has_xseg_mask():
  74. mask = sample.get_xseg_mask()
  75. mask[mask < 0.5] = 0.0
  76. mask[mask >= 0.5] = 1.0
  77. else:
  78. raise Exception(f'no mask in sample {sample.filename}')
  79. if face_type == sample.face_type:
  80. if w != resolution:
  81. img = cv2.resize( img, (resolution, resolution), interpolation=cv2.INTER_LANCZOS4 )
  82. mask = cv2.resize( mask, (resolution, resolution), interpolation=cv2.INTER_LANCZOS4 )
  83. else:
  84. mat = LandmarksProcessor.get_transform_mat (sample.landmarks, resolution, face_type)
  85. img = cv2.warpAffine( img, mat, (resolution,resolution), borderMode=cv2.BORDER_CONSTANT, flags=cv2.INTER_LANCZOS4 )
  86. mask = cv2.warpAffine( mask, mat, (resolution,resolution), borderMode=cv2.BORDER_CONSTANT, flags=cv2.INTER_LANCZOS4 )
  87. if len(mask.shape) == 2:
  88. mask = mask[...,None]
  89. return img, mask
  90. bs = self.batch_size
  91. while True:
  92. batches = [ [], [] ]
  93. n_batch = 0
  94. while n_batch < bs:
  95. try:
  96. if len(shuffle_idxs) == 0:
  97. shuffle_idxs = seg_sample_idxs.copy()
  98. np.random.shuffle(shuffle_idxs)
  99. sample = samples[shuffle_idxs.pop()]
  100. img, mask = gen_img_mask(sample)
  101. if np.random.randint(2) == 0:
  102. if len(bg_shuffle_idxs) == 0:
  103. bg_shuffle_idxs = seg_sample_idxs.copy()
  104. np.random.shuffle(bg_shuffle_idxs)
  105. bg_sample = samples[bg_shuffle_idxs.pop()]
  106. bg_img, bg_mask = gen_img_mask(bg_sample)
  107. bg_wp = imagelib.gen_warp_params(resolution, True, rotation_range=[-180,180], scale_range=[-0.10, 0.10], tx_range=[-0.10, 0.10], ty_range=[-0.10, 0.10] )
  108. bg_img = imagelib.warp_by_params (bg_wp, bg_img, can_warp=False, can_transform=True, can_flip=True, border_replicate=True)
  109. bg_mask = imagelib.warp_by_params (bg_wp, bg_mask, can_warp=False, can_transform=True, can_flip=True, border_replicate=False)
  110. bg_img = bg_img*(1-bg_mask)
  111. if np.random.randint(2) == 0:
  112. bg_img = imagelib.apply_random_hsv_shift(bg_img)
  113. else:
  114. bg_img = imagelib.apply_random_rgb_levels(bg_img)
  115. c_mask = 1.0 - (1-bg_mask) * (1-mask)
  116. rnd = 0.15 + np.random.uniform()*0.85
  117. img = img*(c_mask) + img*(1-c_mask)*rnd + bg_img*(1-c_mask)*(1-rnd)
  118. warp_params = imagelib.gen_warp_params(resolution, random_flip, rotation_range=rotation_range, scale_range=scale_range, tx_range=tx_range, ty_range=ty_range )
  119. img = imagelib.warp_by_params (warp_params, img, can_warp=True, can_transform=True, can_flip=True, border_replicate=True)
  120. mask = imagelib.warp_by_params (warp_params, mask, can_warp=True, can_transform=True, can_flip=True, border_replicate=False)
  121. img = np.clip(img.astype(np.float32), 0, 1)
  122. mask[mask < 0.5] = 0.0
  123. mask[mask >= 0.5] = 1.0
  124. mask = np.clip(mask, 0, 1)
  125. if np.random.randint(2) == 0:
  126. # random face flare
  127. krn = np.random.randint( resolution//4, resolution )
  128. krn = krn - krn % 2 + 1
  129. img = img + cv2.GaussianBlur(img*mask, (krn,krn), 0)
  130. if np.random.randint(2) == 0:
  131. # random bg flare
  132. krn = np.random.randint( resolution//4, resolution )
  133. krn = krn - krn % 2 + 1
  134. img = img + cv2.GaussianBlur(img*(1-mask), (krn,krn), 0)
  135. if np.random.randint(2) == 0:
  136. img = imagelib.apply_random_hsv_shift(img, mask=sd.random_circle_faded ([resolution,resolution]))
  137. else:
  138. img = imagelib.apply_random_rgb_levels(img, mask=sd.random_circle_faded ([resolution,resolution]))
  139. if np.random.randint(2) == 0:
  140. img = imagelib.apply_random_sharpen( img, sharpen_chance, sharpen_kernel_max_size, mask=sd.random_circle_faded ([resolution,resolution]))
  141. else:
  142. img = imagelib.apply_random_motion_blur( img, motion_blur_chance, motion_blur_mb_max_size, mask=sd.random_circle_faded ([resolution,resolution]))
  143. img = imagelib.apply_random_gaussian_blur( img, gaussian_blur_chance, gaussian_blur_kernel_max_size, mask=sd.random_circle_faded ([resolution,resolution]))
  144. if np.random.randint(2) == 0:
  145. img = imagelib.apply_random_nearest_resize( img, random_bilinear_resize_chance, random_bilinear_resize_max_size_per, mask=sd.random_circle_faded ([resolution,resolution]))
  146. else:
  147. img = imagelib.apply_random_bilinear_resize( img, random_bilinear_resize_chance, random_bilinear_resize_max_size_per, mask=sd.random_circle_faded ([resolution,resolution]))
  148. img = np.clip(img, 0, 1)
  149. img = imagelib.apply_random_jpeg_compress( img, random_jpeg_compress_chance, mask=sd.random_circle_faded ([resolution,resolution]))
  150. if data_format == "NCHW":
  151. img = np.transpose(img, (2,0,1) )
  152. mask = np.transpose(mask, (2,0,1) )
  153. batches[0].append ( img )
  154. batches[1].append ( mask )
  155. n_batch += 1
  156. except:
  157. io.log_err ( traceback.format_exc() )
  158. yield [ np.array(batch) for batch in batches]
  159. class SegmentedSampleFilterSubprocessor(Subprocessor):
  160. #override
  161. def __init__(self, samples, count_xseg_mask=False ):
  162. self.samples = samples
  163. self.samples_len = len(self.samples)
  164. self.count_xseg_mask = count_xseg_mask
  165. self.idxs = [*range(self.samples_len)]
  166. self.result = []
  167. super().__init__('SegmentedSampleFilterSubprocessor', SegmentedSampleFilterSubprocessor.Cli, 60)
  168. #override
  169. def process_info_generator(self):
  170. for i in range(multiprocessing.cpu_count()):
  171. yield 'CPU%d' % (i), {}, {'samples':self.samples, 'count_xseg_mask':self.count_xseg_mask}
  172. #override
  173. def on_clients_initialized(self):
  174. io.progress_bar ("Filtering", self.samples_len)
  175. #override
  176. def on_clients_finalized(self):
  177. io.progress_bar_close()
  178. #override
  179. def get_data(self, host_dict):
  180. if len (self.idxs) > 0:
  181. return self.idxs.pop(0)
  182. return None
  183. #override
  184. def on_data_return (self, host_dict, data):
  185. self.idxs.insert(0, data)
  186. #override
  187. def on_result (self, host_dict, data, result):
  188. idx, is_ok = result
  189. if is_ok:
  190. self.result.append(idx)
  191. io.progress_bar_inc(1)
  192. def get_result(self):
  193. return self.result
  194. class Cli(Subprocessor.Cli):
  195. #overridable optional
  196. def on_initialize(self, client_dict):
  197. self.samples = client_dict['samples']
  198. self.count_xseg_mask = client_dict['count_xseg_mask']
  199. def process_data(self, idx):
  200. if self.count_xseg_mask:
  201. return idx, self.samples[idx].has_xseg_mask()
  202. else:
  203. return idx, self.samples[idx].seg_ie_polys.get_pts_count() != 0
  204. """
  205. bg_path = None
  206. for path in paths:
  207. bg_path = Path(path) / 'backgrounds'
  208. if bg_path.exists():
  209. break
  210. if bg_path is None:
  211. io.log_info(f'Random backgrounds will not be used. Place no face jpg images to aligned\backgrounds folder. ')
  212. bg_pathes = None
  213. else:
  214. bg_pathes = pathex.get_image_paths(bg_path, image_extensions=['.jpg'], return_Path_class=True)
  215. io.log_info(f'Using {len(bg_pathes)} random backgrounds from {bg_path}')
  216. if bg_pathes is not None:
  217. bg_path = bg_pathes[ np.random.randint(len(bg_pathes)) ]
  218. bg_img = cv2_imread(bg_path)
  219. if bg_img is not None:
  220. bg_img = bg_img.astype(np.float32) / 255.0
  221. bg_img = imagelib.normalize_channels(bg_img, 3)
  222. bg_img = imagelib.random_crop(bg_img, resolution, resolution)
  223. bg_img = cv2.resize(bg_img, (resolution, resolution), interpolation=cv2.INTER_LINEAR)
  224. if np.random.randint(2) == 0:
  225. bg_img = imagelib.apply_random_hsv_shift(bg_img)
  226. else:
  227. bg_img = imagelib.apply_random_rgb_levels(bg_img)
  228. bg_wp = imagelib.gen_warp_params(resolution, True, rotation_range=[-180,180], scale_range=[0,0], tx_range=[0,0], ty_range=[0,0])
  229. bg_img = imagelib.warp_by_params (bg_wp, bg_img, can_warp=False, can_transform=True, can_flip=True, border_replicate=True)
  230. bg = img*(1-mask)
  231. fg = img*mask
  232. c_mask = sd.random_circle_faded ([resolution,resolution])
  233. bg = ( bg_img*c_mask + bg*(1-c_mask) )*(1-mask)
  234. img = fg+bg
  235. else:
  236. """
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...