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 6.2 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
  1. import pickle
  2. from pathlib import Path
  3. import cv2
  4. from DFLIMG import *
  5. from facelib import LandmarksProcessor, FaceType
  6. from core.interact import interact as io
  7. from core import pathex
  8. from core.cv2ex import *
  9. def save_faceset_metadata_folder(input_path):
  10. input_path = Path(input_path)
  11. metadata_filepath = input_path / 'meta.dat'
  12. io.log_info (f"Saving metadata to {str(metadata_filepath)}\r\n")
  13. d = {}
  14. for filepath in io.progress_bar_generator( pathex.get_image_paths(input_path), "Processing"):
  15. filepath = Path(filepath)
  16. dflimg = DFLIMG.load (filepath)
  17. if dflimg is None or not dflimg.has_data():
  18. io.log_info(f"{filepath} is not a dfl image file")
  19. continue
  20. dfl_dict = dflimg.get_dict()
  21. d[filepath.name] = ( dflimg.get_shape(), dfl_dict )
  22. try:
  23. with open(metadata_filepath, "wb") as f:
  24. f.write ( pickle.dumps(d) )
  25. except:
  26. raise Exception( 'cannot save %s' % (filename) )
  27. io.log_info("Now you can edit images.")
  28. io.log_info("!!! Keep same filenames in the folder.")
  29. io.log_info("You can change size of images, restoring process will downscale back to original size.")
  30. io.log_info("After that, use restore metadata.")
  31. def restore_faceset_metadata_folder(input_path):
  32. input_path = Path(input_path)
  33. metadata_filepath = input_path / 'meta.dat'
  34. io.log_info (f"Restoring metadata from {str(metadata_filepath)}.\r\n")
  35. if not metadata_filepath.exists():
  36. io.log_err(f"Unable to find {str(metadata_filepath)}.")
  37. try:
  38. with open(metadata_filepath, "rb") as f:
  39. d = pickle.loads(f.read())
  40. except:
  41. raise FileNotFoundError(filename)
  42. for filepath in io.progress_bar_generator( pathex.get_image_paths(input_path, image_extensions=['.jpg'], return_Path_class=True), "Processing"):
  43. saved_data = d.get(filepath.name, None)
  44. if saved_data is None:
  45. io.log_info(f"No saved metadata for {filepath}")
  46. continue
  47. shape, dfl_dict = saved_data
  48. img = cv2_imread (filepath)
  49. if img.shape != shape:
  50. img = cv2.resize (img, (shape[1], shape[0]), interpolation=cv2.INTER_LANCZOS4 )
  51. cv2_imwrite (str(filepath), img, [int(cv2.IMWRITE_JPEG_QUALITY), 100] )
  52. if filepath.suffix == '.jpg':
  53. dflimg = DFLJPG.load(filepath)
  54. dflimg.set_dict(dfl_dict)
  55. dflimg.save()
  56. else:
  57. continue
  58. metadata_filepath.unlink()
  59. def add_landmarks_debug_images(input_path):
  60. io.log_info ("Adding landmarks debug images...")
  61. for filepath in io.progress_bar_generator( pathex.get_image_paths(input_path), "Processing"):
  62. filepath = Path(filepath)
  63. img = cv2_imread(str(filepath))
  64. dflimg = DFLIMG.load (filepath)
  65. if dflimg is None or not dflimg.has_data():
  66. io.log_err (f"{filepath.name} is not a dfl image file")
  67. continue
  68. if img is not None:
  69. face_landmarks = dflimg.get_landmarks()
  70. face_type = FaceType.fromString ( dflimg.get_face_type() )
  71. if face_type == FaceType.MARK_ONLY:
  72. rect = dflimg.get_source_rect()
  73. LandmarksProcessor.draw_rect_landmarks(img, rect, face_landmarks, FaceType.FULL )
  74. else:
  75. LandmarksProcessor.draw_landmarks(img, face_landmarks, transparent_mask=True )
  76. output_file = '{}{}'.format( str(Path(str(input_path)) / filepath.stem), '_debug.jpg')
  77. cv2_imwrite(output_file, img, [int(cv2.IMWRITE_JPEG_QUALITY), 50] )
  78. def recover_original_aligned_filename(input_path):
  79. io.log_info ("Recovering original aligned filename...")
  80. files = []
  81. for filepath in io.progress_bar_generator( pathex.get_image_paths(input_path), "Processing"):
  82. filepath = Path(filepath)
  83. dflimg = DFLIMG.load (filepath)
  84. if dflimg is None or not dflimg.has_data():
  85. io.log_err (f"{filepath.name} is not a dfl image file")
  86. continue
  87. files += [ [filepath, None, dflimg.get_source_filename(), False] ]
  88. files_len = len(files)
  89. for i in io.progress_bar_generator( range(files_len), "Sorting" ):
  90. fp, _, sf, converted = files[i]
  91. if converted:
  92. continue
  93. sf_stem = Path(sf).stem
  94. files[i][1] = fp.parent / ( sf_stem + '_0' + fp.suffix )
  95. files[i][3] = True
  96. c = 1
  97. for j in range(i+1, files_len):
  98. fp_j, _, sf_j, converted_j = files[j]
  99. if converted_j:
  100. continue
  101. if sf_j == sf:
  102. files[j][1] = fp_j.parent / ( sf_stem + ('_%d' % (c)) + fp_j.suffix )
  103. files[j][3] = True
  104. c += 1
  105. for file in io.progress_bar_generator( files, "Renaming", leave=False ):
  106. fs, _, _, _ = file
  107. dst = fs.parent / ( fs.stem + '_tmp' + fs.suffix )
  108. try:
  109. fs.rename (dst)
  110. except:
  111. io.log_err ('fail to rename %s' % (fs.name) )
  112. for file in io.progress_bar_generator( files, "Renaming" ):
  113. fs, fd, _, _ = file
  114. fs = fs.parent / ( fs.stem + '_tmp' + fs.suffix )
  115. try:
  116. fs.rename (fd)
  117. except:
  118. io.log_err ('fail to rename %s' % (fs.name) )
  119. def export_faceset_mask(input_dir):
  120. for filename in io.progress_bar_generator(pathex.get_image_paths (input_dir), "Processing"):
  121. filepath = Path(filename)
  122. if '_mask' in filepath.stem:
  123. continue
  124. mask_filepath = filepath.parent / (filepath.stem+'_mask'+filepath.suffix)
  125. dflimg = DFLJPG.load(filepath)
  126. H,W,C = dflimg.shape
  127. seg_ie_polys = dflimg.get_seg_ie_polys()
  128. if dflimg.has_xseg_mask():
  129. mask = dflimg.get_xseg_mask()
  130. mask[mask < 0.5] = 0.0
  131. mask[mask >= 0.5] = 1.0
  132. elif seg_ie_polys.has_polys():
  133. mask = np.zeros ((H,W,1), dtype=np.float32)
  134. seg_ie_polys.overlay_mask(mask)
  135. else:
  136. raise Exception(f'no mask in file {filepath}')
  137. cv2_imwrite(mask_filepath, (mask*255).astype(np.uint8), [int(cv2.IMWRITE_JPEG_QUALITY), 100] )
Tip!

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

Comments

Loading...