main_video.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import os
  2. import cv2
  3. import logging
  4. import argparse
  5. from face_detection import select_face
  6. from face_swap import face_swap
  7. class VideoHandler(object):
  8. def __init__(self, video_path=0, img_path=None, args=None):
  9. self.src_points, self.src_shape, self.src_face = select_face(cv2.imread(img_path))
  10. if self.src_points is None:
  11. print('No face detected in the source image !!!')
  12. exit(-1)
  13. self.args = args
  14. self.video = cv2.VideoCapture(video_path)
  15. self.writer = cv2.VideoWriter(args.save_path, cv2.VideoWriter_fourcc(*'MJPG'), self.video.get(cv2.CAP_PROP_FPS),
  16. (int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH)), int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT))))
  17. def start(self):
  18. while self.video.isOpened():
  19. if cv2.waitKey(1) & 0xFF == ord('q'):
  20. break
  21. _, dst_img = self.video.read()
  22. dst_points, dst_shape, dst_face = select_face(dst_img, choose=False)
  23. if dst_points is not None:
  24. dst_img = face_swap(self.src_face, dst_face, self.src_points, dst_points, dst_shape, dst_img, self.args, 68)
  25. self.writer.write(dst_img)
  26. if self.args.show:
  27. cv2.imshow("Video", dst_img)
  28. self.video.release()
  29. self.writer.release()
  30. cv2.destroyAllWindows()
  31. if __name__ == '__main__':
  32. logging.basicConfig(level=logging.INFO,
  33. format="%(levelname)s:%(lineno)d:%(message)s")
  34. parser = argparse.ArgumentParser(description='FaceSwap Video')
  35. parser.add_argument('--src_img', required=True,
  36. help='Path for source image')
  37. parser.add_argument('--video_path', default=0,
  38. help='Path for video')
  39. parser.add_argument('--warp_2d', default=False, action='store_true', help='2d or 3d warp')
  40. parser.add_argument('--correct_color', default=False, action='store_true', help='Correct color')
  41. parser.add_argument('--show', default=False, action='store_true', help='Show')
  42. parser.add_argument('--save_path', required=True, help='Path for storing output video')
  43. args = parser.parse_args()
  44. dir_path = os.path.dirname(args.save_path)
  45. if not os.path.isdir(dir_path):
  46. os.makedirs(dir_path)
  47. VideoHandler(args.video_path, args.src_img, args).start()