Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
iperov
GitHub Repository: iperov/deepfacelab
Path: blob/master/mainscripts/XSegUtil.py
628 views
1
import json
2
import shutil
3
import traceback
4
from pathlib import Path
5
6
import numpy as np
7
8
from core import pathex
9
from core.cv2ex import *
10
from core.interact import interact as io
11
from core.leras import nn
12
from DFLIMG import *
13
from facelib import XSegNet, LandmarksProcessor, FaceType
14
import pickle
15
16
def apply_xseg(input_path, model_path):
17
if not input_path.exists():
18
raise ValueError(f'{input_path} not found. Please ensure it exists.')
19
20
if not model_path.exists():
21
raise ValueError(f'{model_path} not found. Please ensure it exists.')
22
23
face_type = None
24
25
model_dat = model_path / 'XSeg_data.dat'
26
if model_dat.exists():
27
dat = pickle.loads( model_dat.read_bytes() )
28
dat_options = dat.get('options', None)
29
if dat_options is not None:
30
face_type = dat_options.get('face_type', None)
31
32
33
34
if face_type is None:
35
face_type = io.input_str ("XSeg model face type", 'same', ['h','mf','f','wf','head','same'], help_message="Specify face type of trained XSeg model. For example if XSeg model trained as WF, but faceset is HEAD, specify WF to apply xseg only on WF part of HEAD. Default is 'same'").lower()
36
if face_type == 'same':
37
face_type = None
38
39
if face_type is not None:
40
face_type = {'h' : FaceType.HALF,
41
'mf' : FaceType.MID_FULL,
42
'f' : FaceType.FULL,
43
'wf' : FaceType.WHOLE_FACE,
44
'head' : FaceType.HEAD}[face_type]
45
46
io.log_info(f'Applying trained XSeg model to {input_path.name}/ folder.')
47
48
device_config = nn.DeviceConfig.ask_choose_device(choose_only_one=True)
49
nn.initialize(device_config)
50
51
52
53
xseg = XSegNet(name='XSeg',
54
load_weights=True,
55
weights_file_root=model_path,
56
data_format=nn.data_format,
57
raise_on_no_model_files=True)
58
xseg_res = xseg.get_resolution()
59
60
images_paths = pathex.get_image_paths(input_path, return_Path_class=True)
61
62
for filepath in io.progress_bar_generator(images_paths, "Processing"):
63
dflimg = DFLIMG.load(filepath)
64
if dflimg is None or not dflimg.has_data():
65
io.log_info(f'{filepath} is not a DFLIMG')
66
continue
67
68
img = cv2_imread(filepath).astype(np.float32) / 255.0
69
h,w,c = img.shape
70
71
img_face_type = FaceType.fromString( dflimg.get_face_type() )
72
if face_type is not None and img_face_type != face_type:
73
lmrks = dflimg.get_source_landmarks()
74
75
fmat = LandmarksProcessor.get_transform_mat(lmrks, w, face_type)
76
imat = LandmarksProcessor.get_transform_mat(lmrks, w, img_face_type)
77
78
g_p = LandmarksProcessor.transform_points (np.float32([(0,0),(w,0),(0,w) ]), fmat, True)
79
g_p2 = LandmarksProcessor.transform_points (g_p, imat)
80
81
mat = cv2.getAffineTransform( g_p2, np.float32([(0,0),(w,0),(0,w) ]) )
82
83
img = cv2.warpAffine(img, mat, (w, w), cv2.INTER_LANCZOS4)
84
img = cv2.resize(img, (xseg_res, xseg_res), interpolation=cv2.INTER_LANCZOS4)
85
else:
86
if w != xseg_res:
87
img = cv2.resize( img, (xseg_res,xseg_res), interpolation=cv2.INTER_LANCZOS4 )
88
89
if len(img.shape) == 2:
90
img = img[...,None]
91
92
mask = xseg.extract(img)
93
94
if face_type is not None and img_face_type != face_type:
95
mask = cv2.resize(mask, (w, w), interpolation=cv2.INTER_LANCZOS4)
96
mask = cv2.warpAffine( mask, mat, (w,w), np.zeros( (h,w,c), dtype=np.float), cv2.WARP_INVERSE_MAP | cv2.INTER_LANCZOS4)
97
mask = cv2.resize(mask, (xseg_res, xseg_res), interpolation=cv2.INTER_LANCZOS4)
98
mask[mask < 0.5]=0
99
mask[mask >= 0.5]=1
100
dflimg.set_xseg_mask(mask)
101
dflimg.save()
102
103
104
105
def fetch_xseg(input_path):
106
if not input_path.exists():
107
raise ValueError(f'{input_path} not found. Please ensure it exists.')
108
109
output_path = input_path.parent / (input_path.name + '_xseg')
110
output_path.mkdir(exist_ok=True, parents=True)
111
112
io.log_info(f'Copying faces containing XSeg polygons to {output_path.name}/ folder.')
113
114
images_paths = pathex.get_image_paths(input_path, return_Path_class=True)
115
116
117
files_copied = []
118
for filepath in io.progress_bar_generator(images_paths, "Processing"):
119
dflimg = DFLIMG.load(filepath)
120
if dflimg is None or not dflimg.has_data():
121
io.log_info(f'{filepath} is not a DFLIMG')
122
continue
123
124
ie_polys = dflimg.get_seg_ie_polys()
125
126
if ie_polys.has_polys():
127
files_copied.append(filepath)
128
shutil.copy ( str(filepath), str(output_path / filepath.name) )
129
130
io.log_info(f'Files copied: {len(files_copied)}')
131
132
is_delete = io.input_bool (f"\r\nDelete original files?", True)
133
if is_delete:
134
for filepath in files_copied:
135
Path(filepath).unlink()
136
137
138
def remove_xseg(input_path):
139
if not input_path.exists():
140
raise ValueError(f'{input_path} not found. Please ensure it exists.')
141
142
io.log_info(f'Processing folder {input_path}')
143
io.log_info('!!! WARNING : APPLIED XSEG MASKS WILL BE REMOVED FROM THE FRAMES !!!')
144
io.log_info('!!! WARNING : APPLIED XSEG MASKS WILL BE REMOVED FROM THE FRAMES !!!')
145
io.log_info('!!! WARNING : APPLIED XSEG MASKS WILL BE REMOVED FROM THE FRAMES !!!')
146
io.input_str('Press enter to continue.')
147
148
images_paths = pathex.get_image_paths(input_path, return_Path_class=True)
149
150
files_processed = 0
151
for filepath in io.progress_bar_generator(images_paths, "Processing"):
152
dflimg = DFLIMG.load(filepath)
153
if dflimg is None or not dflimg.has_data():
154
io.log_info(f'{filepath} is not a DFLIMG')
155
continue
156
157
if dflimg.has_xseg_mask():
158
dflimg.set_xseg_mask(None)
159
dflimg.save()
160
files_processed += 1
161
io.log_info(f'Files processed: {files_processed}')
162
163
def remove_xseg_labels(input_path):
164
if not input_path.exists():
165
raise ValueError(f'{input_path} not found. Please ensure it exists.')
166
167
io.log_info(f'Processing folder {input_path}')
168
io.log_info('!!! WARNING : LABELED XSEG POLYGONS WILL BE REMOVED FROM THE FRAMES !!!')
169
io.log_info('!!! WARNING : LABELED XSEG POLYGONS WILL BE REMOVED FROM THE FRAMES !!!')
170
io.log_info('!!! WARNING : LABELED XSEG POLYGONS WILL BE REMOVED FROM THE FRAMES !!!')
171
io.input_str('Press enter to continue.')
172
173
images_paths = pathex.get_image_paths(input_path, return_Path_class=True)
174
175
files_processed = 0
176
for filepath in io.progress_bar_generator(images_paths, "Processing"):
177
dflimg = DFLIMG.load(filepath)
178
if dflimg is None or not dflimg.has_data():
179
io.log_info(f'{filepath} is not a DFLIMG')
180
continue
181
182
if dflimg.has_seg_ie_polys():
183
dflimg.set_seg_ie_polys(None)
184
dflimg.save()
185
files_processed += 1
186
187
io.log_info(f'Files processed: {files_processed}')
188