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

Merger.py 12 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
  1. import math
  2. import multiprocessing
  3. import traceback
  4. from pathlib import Path
  5. import numpy as np
  6. import numpy.linalg as npla
  7. import samplelib
  8. from core import pathex
  9. from core.cv2ex import *
  10. from core.interact import interact as io
  11. from core.joblib import MPClassFuncOnDemand, MPFunc
  12. from core.leras import nn
  13. from DFLIMG import DFLIMG
  14. from facelib import FaceEnhancer, FaceType, LandmarksProcessor, XSegNet
  15. from merger import FrameInfo, InteractiveMergerSubprocessor, MergerConfig
  16. def main (model_class_name=None,
  17. saved_models_path=None,
  18. training_data_src_path=None,
  19. force_model_name=None,
  20. input_path=None,
  21. output_path=None,
  22. output_mask_path=None,
  23. aligned_path=None,
  24. force_gpu_idxs=None,
  25. cpu_only=None):
  26. io.log_info ("Running merger.\r\n")
  27. try:
  28. if not input_path.exists():
  29. io.log_err('Input directory not found. Please ensure it exists.')
  30. return
  31. if not output_path.exists():
  32. output_path.mkdir(parents=True, exist_ok=True)
  33. if not output_mask_path.exists():
  34. output_mask_path.mkdir(parents=True, exist_ok=True)
  35. if not saved_models_path.exists():
  36. io.log_err('Model directory not found. Please ensure it exists.')
  37. return
  38. # Initialize model
  39. import models
  40. model = models.import_model(model_class_name)(is_training=False,
  41. saved_models_path=saved_models_path,
  42. force_gpu_idxs=force_gpu_idxs,
  43. force_model_name=force_model_name,
  44. cpu_only=cpu_only)
  45. predictor_func, predictor_input_shape, cfg = model.get_MergerConfig()
  46. # Preparing MP functions
  47. predictor_func = MPFunc(predictor_func)
  48. run_on_cpu = len(nn.getCurrentDeviceConfig().devices) == 0
  49. xseg_256_extract_func = MPClassFuncOnDemand(XSegNet, 'extract',
  50. name='XSeg',
  51. resolution=256,
  52. weights_file_root=saved_models_path,
  53. place_model_on_cpu=True,
  54. run_on_cpu=run_on_cpu)
  55. face_enhancer_func = MPClassFuncOnDemand(FaceEnhancer, 'enhance',
  56. place_model_on_cpu=True,
  57. run_on_cpu=run_on_cpu)
  58. is_interactive = io.input_bool ("Use interactive merger?", True) if not io.is_colab() else False
  59. if not is_interactive:
  60. cfg.ask_settings()
  61. subprocess_count = io.input_int("Number of workers?", max(8, multiprocessing.cpu_count()),
  62. valid_range=[1, multiprocessing.cpu_count()], help_message="Specify the number of threads to process. A low value may affect performance. A high value may result in memory error. The value may not be greater than CPU cores." )
  63. input_path_image_paths = pathex.get_image_paths(input_path)
  64. if cfg.type == MergerConfig.TYPE_MASKED:
  65. if not aligned_path.exists():
  66. io.log_err('Aligned directory not found. Please ensure it exists.')
  67. return
  68. packed_samples = None
  69. try:
  70. packed_samples = samplelib.PackedFaceset.load(aligned_path)
  71. except:
  72. io.log_err(f"Error occured while loading samplelib.PackedFaceset.load {str(aligned_path)}, {traceback.format_exc()}")
  73. if packed_samples is not None:
  74. io.log_info ("Using packed faceset.")
  75. def generator():
  76. for sample in io.progress_bar_generator( packed_samples, "Collecting alignments"):
  77. filepath = Path(sample.filename)
  78. yield filepath, DFLIMG.load(filepath, loader_func=lambda x: sample.read_raw_file() )
  79. else:
  80. def generator():
  81. for filepath in io.progress_bar_generator( pathex.get_image_paths(aligned_path), "Collecting alignments"):
  82. filepath = Path(filepath)
  83. yield filepath, DFLIMG.load(filepath)
  84. alignments = {}
  85. multiple_faces_detected = False
  86. for filepath, dflimg in generator():
  87. if dflimg is None or not dflimg.has_data():
  88. io.log_err (f"{filepath.name} is not a dfl image file")
  89. continue
  90. source_filename = dflimg.get_source_filename()
  91. if source_filename is None:
  92. continue
  93. source_filepath = Path(source_filename)
  94. source_filename_stem = source_filepath.stem
  95. if source_filename_stem not in alignments.keys():
  96. alignments[ source_filename_stem ] = []
  97. alignments_ar = alignments[ source_filename_stem ]
  98. alignments_ar.append ( (dflimg.get_source_landmarks(), filepath, source_filepath ) )
  99. if len(alignments_ar) > 1:
  100. multiple_faces_detected = True
  101. if multiple_faces_detected:
  102. io.log_info ("")
  103. io.log_info ("Warning: multiple faces detected. Only one alignment file should refer one source file.")
  104. io.log_info ("")
  105. for a_key in list(alignments.keys()):
  106. a_ar = alignments[a_key]
  107. if len(a_ar) > 1:
  108. for _, filepath, source_filepath in a_ar:
  109. io.log_info (f"alignment {filepath.name} refers to {source_filepath.name} ")
  110. io.log_info ("")
  111. alignments[a_key] = [ a[0] for a in a_ar]
  112. if multiple_faces_detected:
  113. io.log_info ("It is strongly recommended to process the faces separatelly.")
  114. io.log_info ("Use 'recover original filename' to determine the exact duplicates.")
  115. io.log_info ("")
  116. frames = [ InteractiveMergerSubprocessor.Frame( frame_info=FrameInfo(filepath=Path(p),
  117. landmarks_list=alignments.get(Path(p).stem, None)
  118. )
  119. )
  120. for p in input_path_image_paths ]
  121. if multiple_faces_detected:
  122. io.log_info ("Warning: multiple faces detected. Motion blur will not be used.")
  123. io.log_info ("")
  124. else:
  125. s = 256
  126. local_pts = [ (s//2-1, s//2-1), (s//2-1,0) ] #center+up
  127. frames_len = len(frames)
  128. for i in io.progress_bar_generator( range(len(frames)) , "Computing motion vectors"):
  129. fi_prev = frames[max(0, i-1)].frame_info
  130. fi = frames[i].frame_info
  131. fi_next = frames[min(i+1, frames_len-1)].frame_info
  132. if len(fi_prev.landmarks_list) == 0 or \
  133. len(fi.landmarks_list) == 0 or \
  134. len(fi_next.landmarks_list) == 0:
  135. continue
  136. mat_prev = LandmarksProcessor.get_transform_mat ( fi_prev.landmarks_list[0], s, face_type=FaceType.FULL)
  137. mat = LandmarksProcessor.get_transform_mat ( fi.landmarks_list[0] , s, face_type=FaceType.FULL)
  138. mat_next = LandmarksProcessor.get_transform_mat ( fi_next.landmarks_list[0], s, face_type=FaceType.FULL)
  139. pts_prev = LandmarksProcessor.transform_points (local_pts, mat_prev, True)
  140. pts = LandmarksProcessor.transform_points (local_pts, mat, True)
  141. pts_next = LandmarksProcessor.transform_points (local_pts, mat_next, True)
  142. prev_vector = pts[0]-pts_prev[0]
  143. next_vector = pts_next[0]-pts[0]
  144. motion_vector = pts_next[0] - pts_prev[0]
  145. fi.motion_power = npla.norm(motion_vector)
  146. motion_vector = motion_vector / fi.motion_power if fi.motion_power != 0 else np.array([0,0],dtype=np.float32)
  147. fi.motion_deg = -math.atan2(motion_vector[1],motion_vector[0])*180 / math.pi
  148. if len(frames) == 0:
  149. io.log_info ("No frames to merge in input_dir.")
  150. else:
  151. if False:
  152. pass
  153. else:
  154. InteractiveMergerSubprocessor (
  155. is_interactive = is_interactive,
  156. merger_session_filepath = model.get_strpath_storage_for_file('merger_session.dat'),
  157. predictor_func = predictor_func,
  158. predictor_input_shape = predictor_input_shape,
  159. face_enhancer_func = face_enhancer_func,
  160. xseg_256_extract_func = xseg_256_extract_func,
  161. merger_config = cfg,
  162. frames = frames,
  163. frames_root_path = input_path,
  164. output_path = output_path,
  165. output_mask_path = output_mask_path,
  166. model_iter = model.get_iter(),
  167. subprocess_count = subprocess_count,
  168. ).run()
  169. model.finalize()
  170. except Exception as e:
  171. print ( traceback.format_exc() )
  172. """
  173. elif cfg.type == MergerConfig.TYPE_FACE_AVATAR:
  174. filesdata = []
  175. for filepath in io.progress_bar_generator(input_path_image_paths, "Collecting info"):
  176. filepath = Path(filepath)
  177. dflimg = DFLIMG.x(filepath)
  178. if dflimg is None:
  179. io.log_err ("%s is not a dfl image file" % (filepath.name) )
  180. continue
  181. filesdata += [ ( FrameInfo(filepath=filepath, landmarks_list=[dflimg.get_landmarks()] ), dflimg.get_source_filename() ) ]
  182. filesdata = sorted(filesdata, key=operator.itemgetter(1)) #sort by source_filename
  183. frames = []
  184. filesdata_len = len(filesdata)
  185. for i in range(len(filesdata)):
  186. frame_info = filesdata[i][0]
  187. prev_temporal_frame_infos = []
  188. next_temporal_frame_infos = []
  189. for t in range (cfg.temporal_face_count):
  190. prev_frame_info = filesdata[ max(i -t, 0) ][0]
  191. next_frame_info = filesdata[ min(i +t, filesdata_len-1 )][0]
  192. prev_temporal_frame_infos.insert (0, prev_frame_info )
  193. next_temporal_frame_infos.append ( next_frame_info )
  194. frames.append ( InteractiveMergerSubprocessor.Frame(prev_temporal_frame_infos=prev_temporal_frame_infos,
  195. frame_info=frame_info,
  196. next_temporal_frame_infos=next_temporal_frame_infos) )
  197. """
  198. #interpolate landmarks
  199. #from facelib import LandmarksProcessor
  200. #from facelib import FaceType
  201. #a = sorted(alignments.keys())
  202. #a_len = len(a)
  203. #
  204. #box_pts = 3
  205. #box = np.ones(box_pts)/box_pts
  206. #for i in range( a_len ):
  207. # if i >= box_pts and i <= a_len-box_pts-1:
  208. # af0 = alignments[ a[i] ][0] ##first face
  209. # m0 = LandmarksProcessor.get_transform_mat (af0, 256, face_type=FaceType.FULL)
  210. #
  211. # points = []
  212. #
  213. # for j in range(-box_pts, box_pts+1):
  214. # af = alignments[ a[i+j] ][0] ##first face
  215. # m = LandmarksProcessor.get_transform_mat (af, 256, face_type=FaceType.FULL)
  216. # p = LandmarksProcessor.transform_points (af, m)
  217. # points.append (p)
  218. #
  219. # points = np.array(points)
  220. # points_len = len(points)
  221. # t_points = np.transpose(points, [1,0,2])
  222. #
  223. # p1 = np.array ( [ int(np.convolve(x[:,0], box, mode='same')[points_len//2]) for x in t_points ] )
  224. # p2 = np.array ( [ int(np.convolve(x[:,1], box, mode='same')[points_len//2]) for x in t_points ] )
  225. #
  226. # new_points = np.concatenate( [np.expand_dims(p1,-1),np.expand_dims(p2,-1)], -1 )
  227. #
  228. # alignments[ a[i] ][0] = LandmarksProcessor.transform_points (new_points, m0, True).astype(np.int32)
Tip!

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

Comments

Loading...