test_one_image.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. with torch.no_grad():
  30. pic_a = opt.pic_a_path
  31. img_a = Image.open(pic_a).convert('RGB')
  32. img_a = transformer_Arcface(img_a)
  33. img_id = img_a.view(-1, img_a.shape[0], img_a.shape[1], img_a.shape[2])
  34. pic_b = opt.pic_b_path
  35. img_b = Image.open(pic_b).convert('RGB')
  36. img_b = transformer(img_b)
  37. img_att = img_b.view(-1, img_b.shape[0], img_b.shape[1], img_b.shape[2])
  38. # convert numpy to tensor
  39. img_id = img_id.cuda()
  40. img_att = img_att.cuda()
  41. #create latent id
  42. img_id_downsample = F.interpolate(img_id, scale_factor=0.5)
  43. latend_id = model.netArc(img_id_downsample)
  44. latend_id = latend_id.detach().to('cpu')
  45. latend_id = latend_id/np.linalg.norm(latend_id,axis=1,keepdims=True)
  46. latend_id = latend_id.to('cuda')
  47. ############## Forward Pass ######################
  48. img_fake = model(img_id, img_att, latend_id, latend_id, True)
  49. for i in range(img_id.shape[0]):
  50. if i == 0:
  51. row1 = img_id[i]
  52. row2 = img_att[i]
  53. row3 = img_fake[i]
  54. else:
  55. row1 = torch.cat([row1, img_id[i]], dim=2)
  56. row2 = torch.cat([row2, img_att[i]], dim=2)
  57. row3 = torch.cat([row3, img_fake[i]], dim=2)
  58. #full = torch.cat([row1, row2, row3], dim=1).detach()
  59. full = row3.detach()
  60. full = full.permute(1, 2, 0)
  61. output = full.to('cpu')
  62. output = np.array(output)
  63. output = output[..., ::-1]
  64. output = output*255
  65. cv2.imwrite(opt.output_path + 'result.jpg',output)