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

Util.py 7.4 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
  1. import pickle
  2. from pathlib import Path
  3. import cv2
  4. from DFLIMG import *
  5. from facelib import LandmarksProcessor
  6. from imagelib import IEPolys
  7. from interact import interact as io
  8. from utils import Path_utils
  9. from utils.cv2_utils import *
  10. def save_faceset_metadata_folder(input_path):
  11. input_path = Path(input_path)
  12. metadata_filepath = input_path / 'meta.dat'
  13. io.log_info (f"Saving metadata to {str(metadata_filepath)}\r\n")
  14. d = {}
  15. for filepath in io.progress_bar_generator( Path_utils.get_image_paths(input_path), "Processing"):
  16. filepath = Path(filepath)
  17. dflimg = DFLIMG.load (filepath)
  18. dfl_dict = dflimg.getDFLDictData()
  19. d[filepath.name] = ( dflimg.get_shape(), dfl_dict )
  20. try:
  21. with open(metadata_filepath, "wb") as f:
  22. f.write ( pickle.dumps(d) )
  23. except:
  24. raise Exception( 'cannot save %s' % (filename) )
  25. io.log_info("Now you can edit images.")
  26. io.log_info("!!! Keep same filenames in the folder.")
  27. io.log_info("You can change size of images, restoring process will downscale back to original size.")
  28. io.log_info("After that, use restore metadata.")
  29. def restore_faceset_metadata_folder(input_path):
  30. input_path = Path(input_path)
  31. metadata_filepath = input_path / 'meta.dat'
  32. io.log_info (f"Restoring metadata from {str(metadata_filepath)}.\r\n")
  33. if not metadata_filepath.exists():
  34. io.log_err(f"Unable to find {str(metadata_filepath)}.")
  35. try:
  36. with open(metadata_filepath, "rb") as f:
  37. d = pickle.loads(f.read())
  38. except:
  39. raise FileNotFoundError(filename)
  40. for filepath in io.progress_bar_generator( Path_utils.get_image_paths(input_path), "Processing"):
  41. filepath = Path(filepath)
  42. shape, dfl_dict = d.get(filepath.name, None)
  43. img = cv2_imread (str(filepath))
  44. if img.shape != shape:
  45. img = cv2.resize (img, (shape[1], shape[0]), cv2.INTER_LANCZOS4 )
  46. if filepath.suffix == '.png':
  47. cv2_imwrite (str(filepath), img)
  48. elif filepath.suffix == '.jpg':
  49. cv2_imwrite (str(filepath), img, [int(cv2.IMWRITE_JPEG_QUALITY), 100] )
  50. if filepath.suffix == '.png':
  51. DFLPNG.embed_dfldict( str(filepath), dfl_dict )
  52. elif filepath.suffix == '.jpg':
  53. DFLJPG.embed_dfldict( str(filepath), dfl_dict )
  54. else:
  55. continue
  56. metadata_filepath.unlink()
  57. def remove_ie_polys_file (filepath):
  58. filepath = Path(filepath)
  59. dflimg = DFLIMG.load (filepath)
  60. if dflimg is None:
  61. io.log_err ("%s is not a dfl image file" % (filepath.name) )
  62. return
  63. dflimg.remove_ie_polys()
  64. dflimg.embed_and_set( str(filepath) )
  65. def remove_ie_polys_folder(input_path):
  66. input_path = Path(input_path)
  67. io.log_info ("Removing ie_polys...\r\n")
  68. for filepath in io.progress_bar_generator( Path_utils.get_image_paths(input_path), "Removing"):
  69. filepath = Path(filepath)
  70. remove_ie_polys_file(filepath)
  71. def remove_fanseg_file (filepath):
  72. filepath = Path(filepath)
  73. dflimg = DFLIMG.load (filepath)
  74. if dflimg is None:
  75. io.log_err ("%s is not a dfl image file" % (filepath.name) )
  76. return
  77. dflimg.remove_fanseg_mask()
  78. dflimg.embed_and_set( str(filepath) )
  79. def remove_fanseg_folder(input_path):
  80. input_path = Path(input_path)
  81. io.log_info ("Removing fanseg mask...\r\n")
  82. for filepath in io.progress_bar_generator( Path_utils.get_image_paths(input_path), "Removing"):
  83. filepath = Path(filepath)
  84. remove_fanseg_file(filepath)
  85. def convert_png_to_jpg_file (filepath):
  86. filepath = Path(filepath)
  87. if filepath.suffix != '.png':
  88. return
  89. dflpng = DFLPNG.load (str(filepath) )
  90. if dflpng is None:
  91. io.log_err ("%s is not a dfl png image file" % (filepath.name) )
  92. return
  93. dfl_dict = dflpng.getDFLDictData()
  94. img = cv2_imread (str(filepath))
  95. new_filepath = str(filepath.parent / (filepath.stem + '.jpg'))
  96. cv2_imwrite ( new_filepath, img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
  97. DFLJPG.embed_data( new_filepath,
  98. face_type=dfl_dict.get('face_type', None),
  99. landmarks=dfl_dict.get('landmarks', None),
  100. ie_polys=dfl_dict.get('ie_polys', None),
  101. source_filename=dfl_dict.get('source_filename', None),
  102. source_rect=dfl_dict.get('source_rect', None),
  103. source_landmarks=dfl_dict.get('source_landmarks', None) )
  104. filepath.unlink()
  105. def convert_png_to_jpg_folder (input_path):
  106. input_path = Path(input_path)
  107. io.log_info ("Converting PNG to JPG...\r\n")
  108. for filepath in io.progress_bar_generator( Path_utils.get_image_paths(input_path), "Converting"):
  109. filepath = Path(filepath)
  110. convert_png_to_jpg_file(filepath)
  111. def add_landmarks_debug_images(input_path):
  112. io.log_info ("Adding landmarks debug images...")
  113. for filepath in io.progress_bar_generator( Path_utils.get_image_paths(input_path), "Processing"):
  114. filepath = Path(filepath)
  115. img = cv2_imread(str(filepath))
  116. dflimg = DFLIMG.load (filepath)
  117. if dflimg is None:
  118. io.log_err ("%s is not a dfl image file" % (filepath.name) )
  119. continue
  120. if img is not None:
  121. face_landmarks = dflimg.get_landmarks()
  122. LandmarksProcessor.draw_landmarks(img, face_landmarks, transparent_mask=True, ie_polys=IEPolys.load(dflimg.get_ie_polys()) )
  123. output_file = '{}{}'.format( str(Path(str(input_path)) / filepath.stem), '_debug.jpg')
  124. cv2_imwrite(output_file, img, [int(cv2.IMWRITE_JPEG_QUALITY), 50] )
  125. def recover_original_aligned_filename(input_path):
  126. io.log_info ("Recovering original aligned filename...")
  127. files = []
  128. for filepath in io.progress_bar_generator( Path_utils.get_image_paths(input_path), "Processing"):
  129. filepath = Path(filepath)
  130. dflimg = DFLIMG.load (filepath)
  131. if dflimg is None:
  132. io.log_err ("%s is not a dfl image file" % (filepath.name) )
  133. continue
  134. files += [ [filepath, None, dflimg.get_source_filename(), False] ]
  135. files_len = len(files)
  136. for i in io.progress_bar_generator( range(files_len), "Sorting" ):
  137. fp, _, sf, converted = files[i]
  138. if converted:
  139. continue
  140. sf_stem = Path(sf).stem
  141. files[i][1] = fp.parent / ( sf_stem + '_0' + fp.suffix )
  142. files[i][3] = True
  143. c = 1
  144. for j in range(i+1, files_len):
  145. fp_j, _, sf_j, converted_j = files[j]
  146. if converted_j:
  147. continue
  148. if sf_j == sf:
  149. files[j][1] = fp_j.parent / ( sf_stem + ('_%d' % (c)) + fp_j.suffix )
  150. files[j][3] = True
  151. c += 1
  152. for file in io.progress_bar_generator( files, "Renaming", leave=False ):
  153. fs, _, _, _ = file
  154. dst = fs.parent / ( fs.stem + '_tmp' + fs.suffix )
  155. try:
  156. fs.rename (dst)
  157. except:
  158. io.log_err ('fail to rename %s' % (fs.name) )
  159. for file in io.progress_bar_generator( files, "Renaming" ):
  160. fs, fd, _, _ = file
  161. fs = fs.parent / ( fs.stem + '_tmp' + fs.suffix )
  162. try:
  163. fs.rename (fd)
  164. except:
  165. io.log_err ('fail to rename %s' % (fs.name) )
Tip!

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

Comments

Loading...