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

XSegUtil.py 7.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
  1. import json
  2. import shutil
  3. import traceback
  4. from pathlib import Path
  5. import numpy as np
  6. from core import pathex
  7. from core.cv2ex import *
  8. from core.interact import interact as io
  9. from core.leras import nn
  10. from DFLIMG import *
  11. from facelib import XSegNet, LandmarksProcessor, FaceType
  12. import pickle
  13. def apply_xseg(input_path, model_path):
  14. if not input_path.exists():
  15. raise ValueError(f'{input_path} not found. Please ensure it exists.')
  16. if not model_path.exists():
  17. raise ValueError(f'{model_path} not found. Please ensure it exists.')
  18. face_type = None
  19. model_dat = model_path / 'XSeg_data.dat'
  20. if model_dat.exists():
  21. dat = pickle.loads( model_dat.read_bytes() )
  22. dat_options = dat.get('options', None)
  23. if dat_options is not None:
  24. face_type = dat_options.get('face_type', None)
  25. if face_type is None:
  26. 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()
  27. if face_type == 'same':
  28. face_type = None
  29. if face_type is not None:
  30. face_type = {'h' : FaceType.HALF,
  31. 'mf' : FaceType.MID_FULL,
  32. 'f' : FaceType.FULL,
  33. 'wf' : FaceType.WHOLE_FACE,
  34. 'head' : FaceType.HEAD}[face_type]
  35. io.log_info(f'Applying trained XSeg model to {input_path.name}/ folder.')
  36. device_config = nn.DeviceConfig.ask_choose_device(choose_only_one=True)
  37. nn.initialize(device_config)
  38. xseg = XSegNet(name='XSeg',
  39. load_weights=True,
  40. weights_file_root=model_path,
  41. data_format=nn.data_format,
  42. raise_on_no_model_files=True)
  43. xseg_res = xseg.get_resolution()
  44. images_paths = pathex.get_image_paths(input_path, return_Path_class=True)
  45. for filepath in io.progress_bar_generator(images_paths, "Processing"):
  46. dflimg = DFLIMG.load(filepath)
  47. if dflimg is None or not dflimg.has_data():
  48. io.log_info(f'{filepath} is not a DFLIMG')
  49. continue
  50. img = cv2_imread(filepath).astype(np.float32) / 255.0
  51. h,w,c = img.shape
  52. img_face_type = FaceType.fromString( dflimg.get_face_type() )
  53. if face_type is not None and img_face_type != face_type:
  54. lmrks = dflimg.get_source_landmarks()
  55. fmat = LandmarksProcessor.get_transform_mat(lmrks, w, face_type)
  56. imat = LandmarksProcessor.get_transform_mat(lmrks, w, img_face_type)
  57. g_p = LandmarksProcessor.transform_points (np.float32([(0,0),(w,0),(0,w) ]), fmat, True)
  58. g_p2 = LandmarksProcessor.transform_points (g_p, imat)
  59. mat = cv2.getAffineTransform( g_p2, np.float32([(0,0),(w,0),(0,w) ]) )
  60. img = cv2.warpAffine(img, mat, (w, w), cv2.INTER_LANCZOS4)
  61. img = cv2.resize(img, (xseg_res, xseg_res), interpolation=cv2.INTER_LANCZOS4)
  62. else:
  63. if w != xseg_res:
  64. img = cv2.resize( img, (xseg_res,xseg_res), interpolation=cv2.INTER_LANCZOS4 )
  65. if len(img.shape) == 2:
  66. img = img[...,None]
  67. mask = xseg.extract(img)
  68. if face_type is not None and img_face_type != face_type:
  69. mask = cv2.resize(mask, (w, w), interpolation=cv2.INTER_LANCZOS4)
  70. mask = cv2.warpAffine( mask, mat, (w,w), np.zeros( (h,w,c), dtype=np.float), cv2.WARP_INVERSE_MAP | cv2.INTER_LANCZOS4)
  71. mask = cv2.resize(mask, (xseg_res, xseg_res), interpolation=cv2.INTER_LANCZOS4)
  72. mask[mask < 0.5]=0
  73. mask[mask >= 0.5]=1
  74. dflimg.set_xseg_mask(mask)
  75. dflimg.save()
  76. def fetch_xseg(input_path):
  77. if not input_path.exists():
  78. raise ValueError(f'{input_path} not found. Please ensure it exists.')
  79. output_path = input_path.parent / (input_path.name + '_xseg')
  80. output_path.mkdir(exist_ok=True, parents=True)
  81. io.log_info(f'Copying faces containing XSeg polygons to {output_path.name}/ folder.')
  82. images_paths = pathex.get_image_paths(input_path, return_Path_class=True)
  83. files_copied = []
  84. for filepath in io.progress_bar_generator(images_paths, "Processing"):
  85. dflimg = DFLIMG.load(filepath)
  86. if dflimg is None or not dflimg.has_data():
  87. io.log_info(f'{filepath} is not a DFLIMG')
  88. continue
  89. ie_polys = dflimg.get_seg_ie_polys()
  90. if ie_polys.has_polys():
  91. files_copied.append(filepath)
  92. shutil.copy ( str(filepath), str(output_path / filepath.name) )
  93. io.log_info(f'Files copied: {len(files_copied)}')
  94. is_delete = io.input_bool (f"\r\nDelete original files?", True)
  95. if is_delete:
  96. for filepath in files_copied:
  97. Path(filepath).unlink()
  98. def remove_xseg(input_path):
  99. if not input_path.exists():
  100. raise ValueError(f'{input_path} not found. Please ensure it exists.')
  101. io.log_info(f'Processing folder {input_path}')
  102. io.log_info('!!! WARNING : APPLIED XSEG MASKS WILL BE REMOVED FROM THE FRAMES !!!')
  103. io.log_info('!!! WARNING : APPLIED XSEG MASKS WILL BE REMOVED FROM THE FRAMES !!!')
  104. io.log_info('!!! WARNING : APPLIED XSEG MASKS WILL BE REMOVED FROM THE FRAMES !!!')
  105. io.input_str('Press enter to continue.')
  106. images_paths = pathex.get_image_paths(input_path, return_Path_class=True)
  107. files_processed = 0
  108. for filepath in io.progress_bar_generator(images_paths, "Processing"):
  109. dflimg = DFLIMG.load(filepath)
  110. if dflimg is None or not dflimg.has_data():
  111. io.log_info(f'{filepath} is not a DFLIMG')
  112. continue
  113. if dflimg.has_xseg_mask():
  114. dflimg.set_xseg_mask(None)
  115. dflimg.save()
  116. files_processed += 1
  117. io.log_info(f'Files processed: {files_processed}')
  118. def remove_xseg_labels(input_path):
  119. if not input_path.exists():
  120. raise ValueError(f'{input_path} not found. Please ensure it exists.')
  121. io.log_info(f'Processing folder {input_path}')
  122. io.log_info('!!! WARNING : LABELED XSEG POLYGONS WILL BE REMOVED FROM THE FRAMES !!!')
  123. io.log_info('!!! WARNING : LABELED XSEG POLYGONS WILL BE REMOVED FROM THE FRAMES !!!')
  124. io.log_info('!!! WARNING : LABELED XSEG POLYGONS WILL BE REMOVED FROM THE FRAMES !!!')
  125. io.input_str('Press enter to continue.')
  126. images_paths = pathex.get_image_paths(input_path, return_Path_class=True)
  127. files_processed = 0
  128. for filepath in io.progress_bar_generator(images_paths, "Processing"):
  129. dflimg = DFLIMG.load(filepath)
  130. if dflimg is None or not dflimg.has_data():
  131. io.log_info(f'{filepath} is not a DFLIMG')
  132. continue
  133. if dflimg.has_seg_ie_polys():
  134. dflimg.set_seg_ie_polys(None)
  135. dflimg.save()
  136. files_processed += 1
  137. io.log_info(f'Files processed: {files_processed}')
Tip!

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

Comments

Loading...