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

face_crop.py 1.6 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
  1. import cv2
  2. import numpy as np
  3. import modules.config
  4. faceRestoreHelper = None
  5. def align_warp_face(self, landmark, border_mode='constant'):
  6. affine_matrix = cv2.estimateAffinePartial2D(landmark, self.face_template, method=cv2.LMEDS)[0]
  7. self.affine_matrices.append(affine_matrix)
  8. if border_mode == 'constant':
  9. border_mode = cv2.BORDER_CONSTANT
  10. elif border_mode == 'reflect101':
  11. border_mode = cv2.BORDER_REFLECT101
  12. elif border_mode == 'reflect':
  13. border_mode = cv2.BORDER_REFLECT
  14. input_img = self.input_img
  15. cropped_face = cv2.warpAffine(input_img, affine_matrix, self.face_size,
  16. borderMode=border_mode, borderValue=(135, 133, 132))
  17. return cropped_face
  18. def crop_image(img_rgb):
  19. global faceRestoreHelper
  20. if faceRestoreHelper is None:
  21. from extras.facexlib.utils.face_restoration_helper import FaceRestoreHelper
  22. faceRestoreHelper = FaceRestoreHelper(
  23. upscale_factor=1,
  24. model_rootpath=modules.config.path_controlnet,
  25. device='cpu' # use cpu is safer since we are out of memory management
  26. )
  27. faceRestoreHelper.clean_all()
  28. faceRestoreHelper.read_image(np.ascontiguousarray(img_rgb[:, :, ::-1].copy()))
  29. faceRestoreHelper.get_face_landmarks_5()
  30. landmarks = faceRestoreHelper.all_landmarks_5
  31. # landmarks are already sorted with confidence.
  32. if len(landmarks) == 0:
  33. print('No face detected')
  34. return img_rgb
  35. else:
  36. print(f'Detected {len(landmarks)} faces')
  37. result = align_warp_face(faceRestoreHelper, landmarks[0])
  38. return np.ascontiguousarray(result[:, :, ::-1].copy())
Tip!

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

Comments

Loading...