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

SampleGeneratorFaceCelebAMaskHQ.py 10 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
  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 core import imagelib, mplib, pathex
  9. from core.cv2ex import *
  10. from core.interact import interact as io
  11. from core.joblib import SubprocessGenerator, ThisThreadGenerator
  12. from facelib import LandmarksProcessor
  13. from samplelib import SampleGeneratorBase
  14. class MaskType(IntEnum):
  15. none = 0,
  16. cloth = 1,
  17. ear_r = 2,
  18. eye_g = 3,
  19. hair = 4,
  20. hat = 5,
  21. l_brow = 6,
  22. l_ear = 7,
  23. l_eye = 8,
  24. l_lip = 9,
  25. mouth = 10,
  26. neck = 11,
  27. neck_l = 12,
  28. nose = 13,
  29. r_brow = 14,
  30. r_ear = 15,
  31. r_eye = 16,
  32. skin = 17,
  33. u_lip = 18
  34. MaskType_to_name = {
  35. int(MaskType.none ) : 'none',
  36. int(MaskType.cloth ) : 'cloth',
  37. int(MaskType.ear_r ) : 'ear_r',
  38. int(MaskType.eye_g ) : 'eye_g',
  39. int(MaskType.hair ) : 'hair',
  40. int(MaskType.hat ) : 'hat',
  41. int(MaskType.l_brow) : 'l_brow',
  42. int(MaskType.l_ear ) : 'l_ear',
  43. int(MaskType.l_eye ) : 'l_eye',
  44. int(MaskType.l_lip ) : 'l_lip',
  45. int(MaskType.mouth ) : 'mouth',
  46. int(MaskType.neck ) : 'neck',
  47. int(MaskType.neck_l) : 'neck_l',
  48. int(MaskType.nose ) : 'nose',
  49. int(MaskType.r_brow) : 'r_brow',
  50. int(MaskType.r_ear ) : 'r_ear',
  51. int(MaskType.r_eye ) : 'r_eye',
  52. int(MaskType.skin ) : 'skin',
  53. int(MaskType.u_lip ) : 'u_lip',
  54. }
  55. MaskType_from_name = { MaskType_to_name[k] : k for k in MaskType_to_name.keys() }
  56. class SampleGeneratorFaceCelebAMaskHQ(SampleGeneratorBase):
  57. def __init__ (self, root_path, debug=False, batch_size=1, resolution=256,
  58. generators_count=4, data_format="NHWC",
  59. **kwargs):
  60. super().__init__(debug, batch_size)
  61. self.initialized = False
  62. dataset_path = root_path / 'CelebAMask-HQ'
  63. if not dataset_path.exists():
  64. raise ValueError(f'Unable to find {dataset_path}')
  65. images_path = dataset_path /'CelebA-HQ-img'
  66. if not images_path.exists():
  67. raise ValueError(f'Unable to find {images_path}')
  68. masks_path = dataset_path / 'CelebAMask-HQ-mask-anno'
  69. if not masks_path.exists():
  70. raise ValueError(f'Unable to find {masks_path}')
  71. if self.debug:
  72. self.generators_count = 1
  73. else:
  74. self.generators_count = max(1, generators_count)
  75. source_images_paths = pathex.get_image_paths(images_path, return_Path_class=True)
  76. source_images_paths_len = len(source_images_paths)
  77. mask_images_paths = pathex.get_image_paths(masks_path, subdirs=True, return_Path_class=True)
  78. if source_images_paths_len == 0 or len(mask_images_paths) == 0:
  79. raise ValueError('No training data provided.')
  80. mask_file_id_hash = {}
  81. for filepath in io.progress_bar_generator(mask_images_paths, "Loading"):
  82. stem = filepath.stem
  83. file_id, mask_type = stem.split('_', 1)
  84. file_id = int(file_id)
  85. if file_id not in mask_file_id_hash:
  86. mask_file_id_hash[file_id] = {}
  87. mask_file_id_hash[file_id][ MaskType_from_name[mask_type] ] = str(filepath.relative_to(masks_path))
  88. source_file_id_set = set()
  89. for filepath in source_images_paths:
  90. stem = filepath.stem
  91. file_id = int(stem)
  92. source_file_id_set.update ( {file_id} )
  93. for k in mask_file_id_hash.keys():
  94. if k not in source_file_id_set:
  95. io.log_err (f"Corrupted dataset: {k} not in {images_path}")
  96. if self.debug:
  97. self.generators = [ThisThreadGenerator ( self.batch_func, (images_path, masks_path, mask_file_id_hash, data_format) )]
  98. else:
  99. self.generators = [SubprocessGenerator ( self.batch_func, (images_path, masks_path, mask_file_id_hash, data_format), start_now=False ) \
  100. for i in range(self.generators_count) ]
  101. SubprocessGenerator.start_in_parallel( self.generators )
  102. self.generator_counter = -1
  103. self.initialized = True
  104. #overridable
  105. def is_initialized(self):
  106. return self.initialized
  107. def __iter__(self):
  108. return self
  109. def __next__(self):
  110. self.generator_counter += 1
  111. generator = self.generators[self.generator_counter % len(self.generators) ]
  112. return next(generator)
  113. def batch_func(self, param ):
  114. images_path, masks_path, mask_file_id_hash, data_format = param
  115. file_ids = list(mask_file_id_hash.keys())
  116. shuffle_file_ids = []
  117. resolution = 256
  118. random_flip = True
  119. rotation_range=[-15,15]
  120. scale_range=[-0.10, 0.95]
  121. tx_range=[-0.3, 0.3]
  122. ty_range=[-0.3, 0.3]
  123. random_bilinear_resize = (25,75)
  124. motion_blur = (25, 5)
  125. gaussian_blur = (25, 5)
  126. bs = self.batch_size
  127. while True:
  128. batches = None
  129. n_batch = 0
  130. while n_batch < bs:
  131. try:
  132. if len(shuffle_file_ids) == 0:
  133. shuffle_file_ids = file_ids.copy()
  134. np.random.shuffle(shuffle_file_ids)
  135. file_id = shuffle_file_ids.pop()
  136. masks = mask_file_id_hash[file_id]
  137. image_path = images_path / f'{file_id}.jpg'
  138. skin_path = masks.get(MaskType.skin, None)
  139. hair_path = masks.get(MaskType.hair, None)
  140. hat_path = masks.get(MaskType.hat, None)
  141. #neck_path = masks.get(MaskType.neck, None)
  142. img = cv2_imread(image_path).astype(np.float32) / 255.0
  143. mask = cv2_imread(masks_path / skin_path)[...,0:1].astype(np.float32) / 255.0
  144. if hair_path is not None:
  145. hair_path = masks_path / hair_path
  146. if hair_path.exists():
  147. hair = cv2_imread(hair_path)[...,0:1].astype(np.float32) / 255.0
  148. mask *= (1-hair)
  149. if hat_path is not None:
  150. hat_path = masks_path / hat_path
  151. if hat_path.exists():
  152. hat = cv2_imread(hat_path)[...,0:1].astype(np.float32) / 255.0
  153. mask *= (1-hat)
  154. #if neck_path is not None:
  155. # neck_path = masks_path / neck_path
  156. # if neck_path.exists():
  157. # neck = cv2_imread(neck_path)[...,0:1].astype(np.float32) / 255.0
  158. # mask = np.clip(mask+neck, 0, 1)
  159. 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 )
  160. img = cv2.resize( img, (resolution,resolution), cv2.INTER_LANCZOS4 )
  161. h, s, v = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
  162. h = ( h + np.random.randint(360) ) % 360
  163. s = np.clip ( s + np.random.random()-0.5, 0, 1 )
  164. v = np.clip ( v + np.random.random()/2-0.25, 0, 1 )
  165. img = np.clip( cv2.cvtColor(cv2.merge([h, s, v]), cv2.COLOR_HSV2BGR) , 0, 1 )
  166. if motion_blur is not None:
  167. chance, mb_max_size = motion_blur
  168. chance = np.clip(chance, 0, 100)
  169. mblur_rnd_chance = np.random.randint(100)
  170. mblur_rnd_kernel = np.random.randint(mb_max_size)+1
  171. mblur_rnd_deg = np.random.randint(360)
  172. if mblur_rnd_chance < chance:
  173. img = imagelib.LinearMotionBlur (img, mblur_rnd_kernel, mblur_rnd_deg )
  174. img = imagelib.warp_by_params (warp_params, img, can_warp=True, can_transform=True, can_flip=True, border_replicate=False, cv2_inter=cv2.INTER_LANCZOS4)
  175. if gaussian_blur is not None:
  176. chance, kernel_max_size = gaussian_blur
  177. chance = np.clip(chance, 0, 100)
  178. gblur_rnd_chance = np.random.randint(100)
  179. gblur_rnd_kernel = np.random.randint(kernel_max_size)*2+1
  180. if gblur_rnd_chance < chance:
  181. img = cv2.GaussianBlur(img, (gblur_rnd_kernel,) *2 , 0)
  182. if random_bilinear_resize is not None:
  183. chance, max_size_per = random_bilinear_resize
  184. chance = np.clip(chance, 0, 100)
  185. pick_chance = np.random.randint(100)
  186. resize_to = resolution - int( np.random.rand()* int(resolution*(max_size_per/100.0)) )
  187. img = cv2.resize (img, (resize_to,resize_to), cv2.INTER_LINEAR )
  188. img = cv2.resize (img, (resolution,resolution), cv2.INTER_LINEAR )
  189. mask = cv2.resize( mask, (resolution,resolution), cv2.INTER_LANCZOS4 )[...,None]
  190. mask = imagelib.warp_by_params (warp_params, mask, can_warp=True, can_transform=True, can_flip=True, border_replicate=False, cv2_inter=cv2.INTER_LANCZOS4)
  191. mask[mask < 0.5] = 0.0
  192. mask[mask >= 0.5] = 1.0
  193. mask = np.clip(mask, 0, 1)
  194. if data_format == "NCHW":
  195. img = np.transpose(img, (2,0,1) )
  196. mask = np.transpose(mask, (2,0,1) )
  197. if batches is None:
  198. batches = [ [], [] ]
  199. batches[0].append ( img )
  200. batches[1].append ( mask )
  201. n_batch += 1
  202. except:
  203. io.log_err ( traceback.format_exc() )
  204. yield [ np.array(batch) for batch in batches]
Tip!

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

Comments

Loading...