test_one_image.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. def lcm(a, b): return abs(a * b) / fractions.gcd(a, b) if a and b else 0
  11. transformer = transforms.Compose([
  12. transforms.ToTensor(),
  13. #transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
  14. ])
  15. transformer_Arcface = transforms.Compose([
  16. transforms.ToTensor(),
  17. transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
  18. ])
  19. detransformer = transforms.Compose([
  20. transforms.Normalize([0, 0, 0], [1/0.229, 1/0.224, 1/0.225]),
  21. transforms.Normalize([-0.485, -0.456, -0.406], [1, 1, 1])
  22. ])
  23. if __name__ == '__main__':
  24. opt = TestOptions().parse()
  25. start_epoch, epoch_iter = 1, 0
  26. torch.nn.Module.dump_patches = True
  27. model = create_model(opt)
  28. model.eval()
  29. pic_a = opt.pic_a_path
  30. img_a = Image.open(pic_a).convert('RGB')
  31. img_a = transformer_Arcface(img_a)
  32. img_id = img_a.view(-1, img_a.shape[0], img_a.shape[1], img_a.shape[2])
  33. pic_b = opt.pic_b_path
  34. img_b = Image.open(pic_b).convert('RGB')
  35. img_b = transformer(img_b)
  36. img_att = img_b.view(-1, img_b.shape[0], img_b.shape[1], img_b.shape[2])
  37. # convert numpy to tensor
  38. img_id = img_id.cuda()
  39. img_att = img_att.cuda()
  40. #create latent id
  41. img_id_downsample = F.interpolate(img_id, scale_factor=0.5)
  42. latend_id = model.netArc(img_id_downsample)
  43. latend_id = latend_id.detach().to('cpu')
  44. latend_id = latend_id/np.linalg.norm(latend_id,axis=1,keepdims=True)
  45. latend_id = latend_id.to('cuda')
  46. ############## Forward Pass ######################
  47. img_fake = model(img_id, img_att, latend_id, latend_id, True)
  48. for i in range(img_id.shape[0]):
  49. if i == 0:
  50. row1 = img_id[i]
  51. row2 = img_att[i]
  52. row3 = img_fake[i]
  53. else:
  54. row1 = torch.cat([row1, img_id[i]], dim=2)
  55. row2 = torch.cat([row2, img_att[i]], dim=2)
  56. row3 = torch.cat([row3, img_fake[i]], dim=2)
  57. #full = torch.cat([row1, row2, row3], dim=1).detach()
  58. full = row3.detach()
  59. full = full.permute(1, 2, 0)
  60. output = full.to('cpu')
  61. output = np.array(output)
  62. output = output[..., ::-1]
  63. output = output*255
  64. cv2.imwrite(opt.output_path + 'result.jpg',output)