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

FacesetResizer.py 8.5 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
  1. import multiprocessing
  2. import shutil
  3. import cv2
  4. from core import pathex
  5. from core.cv2ex import *
  6. from core.interact import interact as io
  7. from core.joblib import Subprocessor
  8. from DFLIMG import *
  9. from facelib import FaceType, LandmarksProcessor
  10. class FacesetResizerSubprocessor(Subprocessor):
  11. #override
  12. def __init__(self, image_paths, output_dirpath, image_size, face_type=None):
  13. self.image_paths = image_paths
  14. self.output_dirpath = output_dirpath
  15. self.image_size = image_size
  16. self.face_type = face_type
  17. self.result = []
  18. super().__init__('FacesetResizer', FacesetResizerSubprocessor.Cli, 600)
  19. #override
  20. def on_clients_initialized(self):
  21. io.progress_bar (None, len (self.image_paths))
  22. #override
  23. def on_clients_finalized(self):
  24. io.progress_bar_close()
  25. #override
  26. def process_info_generator(self):
  27. base_dict = {'output_dirpath':self.output_dirpath, 'image_size':self.image_size, 'face_type':self.face_type}
  28. for device_idx in range( min(8, multiprocessing.cpu_count()) ):
  29. client_dict = base_dict.copy()
  30. device_name = f'CPU #{device_idx}'
  31. client_dict['device_name'] = device_name
  32. yield device_name, {}, client_dict
  33. #override
  34. def get_data(self, host_dict):
  35. if len (self.image_paths) > 0:
  36. return self.image_paths.pop(0)
  37. #override
  38. def on_data_return (self, host_dict, data):
  39. self.image_paths.insert(0, data)
  40. #override
  41. def on_result (self, host_dict, data, result):
  42. io.progress_bar_inc(1)
  43. if result[0] == 1:
  44. self.result +=[ (result[1], result[2]) ]
  45. #override
  46. def get_result(self):
  47. return self.result
  48. class Cli(Subprocessor.Cli):
  49. #override
  50. def on_initialize(self, client_dict):
  51. self.output_dirpath = client_dict['output_dirpath']
  52. self.image_size = client_dict['image_size']
  53. self.face_type = client_dict['face_type']
  54. self.log_info (f"Running on { client_dict['device_name'] }")
  55. #override
  56. def process_data(self, filepath):
  57. try:
  58. dflimg = DFLIMG.load (filepath)
  59. if dflimg is None or not dflimg.has_data():
  60. self.log_err (f"{filepath.name} is not a dfl image file")
  61. else:
  62. img = cv2_imread(filepath)
  63. h,w = img.shape[:2]
  64. if h != w:
  65. raise Exception(f'w != h in {filepath}')
  66. image_size = self.image_size
  67. face_type = self.face_type
  68. output_filepath = self.output_dirpath / filepath.name
  69. if face_type is not None:
  70. lmrks = dflimg.get_landmarks()
  71. mat = LandmarksProcessor.get_transform_mat(lmrks, image_size, face_type)
  72. img = cv2.warpAffine(img, mat, (image_size, image_size), flags=cv2.INTER_LANCZOS4 )
  73. img = np.clip(img, 0, 255).astype(np.uint8)
  74. cv2_imwrite ( str(output_filepath), img, [int(cv2.IMWRITE_JPEG_QUALITY), 100] )
  75. dfl_dict = dflimg.get_dict()
  76. dflimg = DFLIMG.load (output_filepath)
  77. dflimg.set_dict(dfl_dict)
  78. xseg_mask = dflimg.get_xseg_mask()
  79. if xseg_mask is not None:
  80. xseg_res = 256
  81. xseg_lmrks = lmrks.copy()
  82. xseg_lmrks *= (xseg_res / w)
  83. xseg_mat = LandmarksProcessor.get_transform_mat(xseg_lmrks, xseg_res, face_type)
  84. xseg_mask = cv2.warpAffine(xseg_mask, xseg_mat, (xseg_res, xseg_res), flags=cv2.INTER_LANCZOS4 )
  85. xseg_mask[xseg_mask < 0.5] = 0
  86. xseg_mask[xseg_mask >= 0.5] = 1
  87. dflimg.set_xseg_mask(xseg_mask)
  88. seg_ie_polys = dflimg.get_seg_ie_polys()
  89. for poly in seg_ie_polys.get_polys():
  90. poly_pts = poly.get_pts()
  91. poly_pts = LandmarksProcessor.transform_points(poly_pts, mat)
  92. poly.set_points(poly_pts)
  93. dflimg.set_seg_ie_polys(seg_ie_polys)
  94. lmrks = LandmarksProcessor.transform_points(lmrks, mat)
  95. dflimg.set_landmarks(lmrks)
  96. image_to_face_mat = dflimg.get_image_to_face_mat()
  97. if image_to_face_mat is not None:
  98. image_to_face_mat = LandmarksProcessor.get_transform_mat ( dflimg.get_source_landmarks(), image_size, face_type )
  99. dflimg.set_image_to_face_mat(image_to_face_mat)
  100. dflimg.set_face_type( FaceType.toString(face_type) )
  101. dflimg.save()
  102. else:
  103. dfl_dict = dflimg.get_dict()
  104. scale = w / image_size
  105. img = cv2.resize(img, (image_size, image_size), interpolation=cv2.INTER_LANCZOS4)
  106. cv2_imwrite ( str(output_filepath), img, [int(cv2.IMWRITE_JPEG_QUALITY), 100] )
  107. dflimg = DFLIMG.load (output_filepath)
  108. dflimg.set_dict(dfl_dict)
  109. lmrks = dflimg.get_landmarks()
  110. lmrks /= scale
  111. dflimg.set_landmarks(lmrks)
  112. seg_ie_polys = dflimg.get_seg_ie_polys()
  113. seg_ie_polys.mult_points( 1.0 / scale)
  114. dflimg.set_seg_ie_polys(seg_ie_polys)
  115. image_to_face_mat = dflimg.get_image_to_face_mat()
  116. if image_to_face_mat is not None:
  117. face_type = FaceType.fromString ( dflimg.get_face_type() )
  118. image_to_face_mat = LandmarksProcessor.get_transform_mat ( dflimg.get_source_landmarks(), image_size, face_type )
  119. dflimg.set_image_to_face_mat(image_to_face_mat)
  120. dflimg.save()
  121. return (1, filepath, output_filepath)
  122. except:
  123. self.log_err (f"Exception occured while processing file {filepath}. Error: {traceback.format_exc()}")
  124. return (0, filepath, None)
  125. def process_folder ( dirpath):
  126. image_size = io.input_int(f"New image size", 512, valid_range=[128,2048])
  127. face_type = io.input_str ("Change face type", 'same', ['h','mf','f','wf','head','same']).lower()
  128. if face_type == 'same':
  129. face_type = None
  130. else:
  131. face_type = {'h' : FaceType.HALF,
  132. 'mf' : FaceType.MID_FULL,
  133. 'f' : FaceType.FULL,
  134. 'wf' : FaceType.WHOLE_FACE,
  135. 'head' : FaceType.HEAD}[face_type]
  136. output_dirpath = dirpath.parent / (dirpath.name + '_resized')
  137. output_dirpath.mkdir (exist_ok=True, parents=True)
  138. dirpath_parts = '/'.join( dirpath.parts[-2:])
  139. output_dirpath_parts = '/'.join( output_dirpath.parts[-2:] )
  140. io.log_info (f"Resizing faceset in {dirpath_parts}")
  141. io.log_info ( f"Processing to {output_dirpath_parts}")
  142. output_images_paths = pathex.get_image_paths(output_dirpath)
  143. if len(output_images_paths) > 0:
  144. for filename in output_images_paths:
  145. Path(filename).unlink()
  146. image_paths = [Path(x) for x in pathex.get_image_paths( dirpath )]
  147. result = FacesetResizerSubprocessor ( image_paths, output_dirpath, image_size, face_type).run()
  148. is_merge = io.input_bool (f"\r\nMerge {output_dirpath_parts} to {dirpath_parts} ?", True)
  149. if is_merge:
  150. io.log_info (f"Copying processed files to {dirpath_parts}")
  151. for (filepath, output_filepath) in result:
  152. try:
  153. shutil.copy (output_filepath, filepath)
  154. except:
  155. pass
  156. io.log_info (f"Removing {output_dirpath_parts}")
  157. shutil.rmtree(output_dirpath)
Tip!

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

Comments

Loading...