MCPcopy Create free account
hub / github.com/OpenTalker/StyleHEAT / align_frames

Function align_frames

utils/video_util.py:196–354  ·  view source on GitHub ↗
(img_dir, save_dir, output_size=1024, transform_size=1024, optical_flow=True, gaussian=True,
                 filter_size=3)

Source from the content-addressed store, hash-verified

194
195# Align faces
196def align_frames(img_dir, save_dir, output_size=1024, transform_size=1024, optical_flow=True, gaussian=True,
197 filter_size=3):
198 os.makedirs(save_dir, exist_ok=True)
199
200 # load face landmark detector
201 fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, flip_input=False, device='cuda')
202
203 # list images in the directory
204 img_list = glob.glob1(img_dir, 'frame*')
205 img_list.sort()
206
207 # save align statistics
208 stat_dict = {'quad': [], 'qsize': [], 'coord': [], 'crop': []}
209 lms = []
210 for idx, img_name in enumerate(img_list):
211
212 img_path = os.path.join(img_dir, img_name)
213 img = io.imread(img_path)
214 lm = []
215
216 preds = fa.get_landmarks(img)
217 for kk in range(68):
218 lm.append((preds[0][kk][0], preds[0][kk][1]))
219
220 # Eye distance
221 lm_eye_left = lm[36: 42] # left-clockwise
222 lm_eye_right = lm[42: 48] # left-clockwise
223 eye_left = np.mean(lm_eye_left, axis=0)
224 eye_right = np.mean(lm_eye_right, axis=0)
225 eye_to_eye = eye_right - eye_left
226
227 if optical_flow:
228 if idx > 0:
229 s = int(np.hypot(*eye_to_eye) / 4)
230 lk_params = dict(winSize=(s, s), maxLevel=5,
231 criteria=(cv2.TERM_CRITERIA_COUNT | cv2.TERM_CRITERIA_EPS, 10, 0.03))
232 points_arr = np.array(lm, np.float32)
233 points_prevarr = np.array(prev_lm, np.float32)
234 points_arr, status, err = cv2.calcOpticalFlowPyrLK(prev_img, img, points_prevarr, points_arr,
235 **lk_params)
236 sigma = 100
237 points_arr_float = np.array(points_arr, np.float32)
238 points = points_arr_float.tolist()
239 for k in range(0, len(lm)):
240 d = cv2.norm(np.array(prev_lm[k]) - np.array(lm[k]))
241 alpha = np.exp(-d * d / sigma)
242 lm[k] = (1 - alpha) * np.array(lm[k]) + alpha * np.array(points[k])
243 prev_img = img
244 prev_lm = lm
245
246 lms.append(lm)
247
248 # Apply gaussian filter on landmarks
249 if gaussian:
250 lm_filtered = np.array(lms)
251 for kk in range(68):
252 lm_filtered[:, kk, 0] = gaussian_filter1d(lm_filtered[:, kk, 0], filter_size)
253 lm_filtered[:, kk, 1] = gaussian_filter1d(lm_filtered[:, kk, 1], filter_size)

Callers

nothing calls this directly

Calls 5

get_landmarksMethod · 0.80
create_videoFunction · 0.70
cropMethod · 0.45
transformMethod · 0.45
saveMethod · 0.45

Tested by

no test coverage detected