MCPcopy Create free account
hub / github.com/YZY-stack/DF40 / extract_aligned_face_dlib

Function extract_aligned_face_dlib

DeepfakeBench_DF40/preprocessing/preprocess.py:120–213  ·  view source on GitHub ↗
(face_detector, predictor, image, res=256, mask=None)

Source from the content-addressed store, hash-verified

118
119
120def extract_aligned_face_dlib(face_detector, predictor, image, res=256, mask=None):
121 def img_align_crop(img, landmark=None, outsize=None, scale=1.3, mask=None):
122 """
123 align and crop the face according to the given bbox and landmarks
124 landmark: 5 key points
125 """
126
127 M = None
128 target_size = [112, 112]
129 dst = np.array([
130 [30.2946, 51.6963],
131 [65.5318, 51.5014],
132 [48.0252, 71.7366],
133 [33.5493, 92.3655],
134 [62.7299, 92.2041]], dtype=np.float32)
135
136 if target_size[1] == 112:
137 dst[:, 0] += 8.0
138
139 dst[:, 0] = dst[:, 0] * outsize[0] / target_size[0]
140 dst[:, 1] = dst[:, 1] * outsize[1] / target_size[1]
141
142 target_size = outsize
143
144 margin_rate = scale - 1
145 x_margin = target_size[0] * margin_rate / 2.
146 y_margin = target_size[1] * margin_rate / 2.
147
148 # move
149 dst[:, 0] += x_margin
150 dst[:, 1] += y_margin
151
152 # resize
153 dst[:, 0] *= target_size[0] / (target_size[0] + 2 * x_margin)
154 dst[:, 1] *= target_size[1] / (target_size[1] + 2 * y_margin)
155
156 src = landmark.astype(np.float32)
157
158 # use skimage tranformation
159 tform = trans.SimilarityTransform()
160 tform.estimate(src, dst)
161 M = tform.params[0:2, :]
162
163 # M: use opencv
164 # M = cv2.getAffineTransform(src[[0,1,2],:],dst[[0,1,2],:])
165
166 img = cv2.warpAffine(img, M, (target_size[1], target_size[0]))
167
168 if outsize is not None:
169 img = cv2.resize(img, (outsize[1], outsize[0]))
170
171 if mask is not None:
172 mask = cv2.warpAffine(mask, M, (target_size[1], target_size[0]))
173 mask = cv2.resize(mask, (outsize[1], outsize[0]))
174 return img, mask
175 else:
176 return img, None
177

Callers 1

facecropFunction · 0.85

Calls 2

get_keyptsFunction · 0.70
img_align_cropFunction · 0.70

Tested by

no test coverage detected