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