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