test_video_swapmutil.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import cv2
  2. import torch
  3. import fractions
  4. import numpy as np
  5. from PIL import Image
  6. import torch.nn.functional as F
  7. from torchvision import transforms
  8. from models.models import create_model
  9. from options.test_options import TestOptions
  10. from insightface_func.face_detect_crop_mutil import Face_detect_crop
  11. from util.videoswap import video_swap
  12. import os
  13. from moviepy.editor import AudioFileClip
  14. def lcm(a, b): return abs(a * b) / fractions.gcd(a, b) if a and b else 0
  15. transformer = transforms.Compose([
  16. transforms.ToTensor(),
  17. #transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
  18. ])
  19. transformer_Arcface = transforms.Compose([
  20. transforms.ToTensor(),
  21. transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
  22. ])
  23. detransformer = transforms.Compose([
  24. transforms.Normalize([0, 0, 0], [1/0.229, 1/0.224, 1/0.225]),
  25. transforms.Normalize([-0.485, -0.456, -0.406], [1, 1, 1])
  26. ])
  27. if __name__ == '__main__':
  28. opt = TestOptions().parse()
  29. start_epoch, epoch_iter = 1, 0
  30. crop_size = 224
  31. torch.nn.Module.dump_patches = True
  32. model = create_model(opt)
  33. model.eval()
  34. app = Face_detect_crop(name='antelope', root='./insightface_func/models')
  35. app.prepare(ctx_id= 0, det_thresh=0.6, det_size=(640,640))
  36. pic_a = opt.pic_a_path
  37. # img_a = Image.open(pic_a).convert('RGB')
  38. img_a_whole = cv2.imread(pic_a)
  39. img_a_align_crop, _ = app.get(img_a_whole,crop_size)
  40. img_a_align_crop_pil = Image.fromarray(cv2.cvtColor(img_a_align_crop[0],cv2.COLOR_BGR2RGB))
  41. img_a = transformer_Arcface(img_a_align_crop_pil)
  42. img_id = img_a.view(-1, img_a.shape[0], img_a.shape[1], img_a.shape[2])
  43. # pic_b = opt.pic_b_path
  44. # img_b_whole = cv2.imread(pic_b)
  45. # img_b_align_crop, b_mat = app.get(img_b_whole,crop_size)
  46. # img_b_align_crop_pil = Image.fromarray(cv2.cvtColor(img_b_align_crop,cv2.COLOR_BGR2RGB))
  47. # img_b = transformer(img_b_align_crop_pil)
  48. # img_att = img_b.view(-1, img_b.shape[0], img_b.shape[1], img_b.shape[2])
  49. # convert numpy to tensor
  50. img_id = img_id.cuda()
  51. # img_att = img_att.cuda()
  52. #create latent id
  53. img_id_downsample = F.interpolate(img_id, scale_factor=0.5)
  54. latend_id = model.netArc(img_id_downsample)
  55. latend_id = latend_id.detach().to('cpu')
  56. latend_id = latend_id/np.linalg.norm(latend_id,axis=1,keepdims=True)
  57. latend_id = latend_id.to('cuda')
  58. video_swap(opt.video_path, latend_id, model, app, opt.output_path,temp_results_dir=opt.temp_path)